在part 1里我們了解了ggplot2的基本繪圖功能qplot, 這次我們來看看另一個(gè)重要功能qplot
七個(gè)圖形對(duì)象
- DATA FRAME 數(shù)據(jù)幀
- AESTHETIC MAPPINGS 外觀圖法
- GEOMS 幾何對(duì)象
- FACETS 面板
- STAT 統(tǒng)計(jì)轉(zhuǎn)換,比如bin, smooth
- SCALES ??
- COORDINATE SYSTEM 坐標(biāo)系
ggplot2繪圖分步顯示
使用層來建立圖形
- Plot the data 先對(duì)數(shù)據(jù)繪圖
- Overlay a summary 再把數(shù)據(jù)概要覆蓋在數(shù)據(jù)圖形上面
- Metadata and annotation 最后是元數(shù)據(jù)和注釋
qplot(displ, hwy, data=mpg, geom=c("point", "smooth"), facets=.~drv)

散點(diǎn)圖-3面板
分步解讀畫圖步驟
>g <- ggplot(mpg,aes(displ, hwy))
> summary(g)
data: manufacturer, model, displ, year, cyl, trans, drv, cty, hwy, fl,
class [234x11]
mapping: x = ~displ, y = ~hwy
faceting: <ggproto object: Class FacetNull, Facet, gg>
compute_layout: function
draw_back: function
draw_front: function
draw_labels: function
draw_panels: function
finish_data: function
init_scales: function
map_data: function
params: list
setup_data: function
setup_params: function
shrink: TRUE
train_scales: function
vars: function
super: <ggproto object: Class FacetNull, Facet, gg>
從摘要中可以看出gg對(duì)象中包括:data(mpg), mapping(x,y), faceting(no)
> print(g)
# ggplot 不能用print打印gg對(duì)象
g + geom_point()

# 增加平滑曲線
g + geom_point() + geom_smooth()

# 改變平滑功能參數(shù)為線性回歸
g + geom_point() + geom_smooth(method="lm")

# 子面板分組繪圖
g + geom_point() + geom_smooth(method="lm") + facet_grid(. ~ drv)

增加注釋
g + geom_point() + geom_smooth(method="lm") + facet_grid(.~drv) + ggtitle("Swirl Rules!")

增加繪圖主標(biāo)題
下面開始來改變圖形的外觀AESTHETIC, 設(shè)置散點(diǎn)的大小,顏色,透明度
g + geom_point(color="pink", size=4, alpha=1/2)

外觀設(shè)置,顏色深的表示數(shù)據(jù)有重疊
按顏色分組,設(shè)置aes clor 到一個(gè)因子變量,實(shí)現(xiàn)不同顏色變量的分組顯示
g + geom_point(aes(color = drv), size = 4, alpha = 1/2)

設(shè)置color=factor變量
設(shè)置標(biāo)題和標(biāo)簽 (圖略)
g + geom_point(aes(color = drv)) + labs(title="Swirl Rules!") + labs(x="Displacement", y="Hwy Mileage")
定制平滑線
g + geom_point(aes(color = drv),size=2,alpha=1/2) + geom_smooth(size=4,linetype=3,method="lm",se=FALSE)

ggplot圖層的復(fù)雜例子
> head(testdat)
x y
1 1 -1.13782391
2 2 0.57977757
3 3 -0.87085224
4 4 -0.39750827
5 5 0.08576791
6 6 0.92132965
# R原生畫圖
plot(myx, myy, type = "l", ylim = c(-3,3))
# ggplot 圖層演示
g <- ggplot(testdat, aes(x = myx, y = myy))
# 對(duì)比原生繪圖函數(shù),離線點(diǎn)50,100會(huì)壓縮整個(gè)圖形
g + geom_line()
# 顯示y軸數(shù)值范圍,但是圖形有中斷
g + geom_line() + ylim(-3,3)
# 選擇合適的坐標(biāo)系,笛卡爾坐標(biāo),同時(shí)設(shè)置y軸范圍
g + geom_line() + coord_cartesian(ylim=c(-3,3))

plog原生畫圖

ggplot, 離群點(diǎn)沒有丟棄

ggplot,設(shè)置y軸范圍,圖形不連續(xù)

ggplot, 設(shè)置坐標(biāo)系
繼續(xù)以mpg數(shù)據(jù)集演示
> g <- ggplot(mpg,aes(x=displ,y=hwy,color=factor(year)))
...沒有圖形顯示,因?yàn)闆]有定義圖層
> g + geom_point()

子面板分組顯示
> g + geom_point() + facet_grid(drv ~ cyl, margins=TRUE)
