ggplot2绘图入门系列之二:图层控制与直方图
如前文所述,ggplot2使用圖層將各種圖形元素逐步添加組合,從而形成最終結(jié)果。第一層必須是原始數(shù)據(jù)層,其中data參數(shù)控制數(shù)據(jù)來源,注意數(shù)據(jù)形式只能是數(shù)據(jù)框格式。aes參數(shù)控制了對哪些變量進行圖形映射,以及映射方式,aes是Aesthetic的縮寫。
下面我們來繪制一個直方圖作為示例。數(shù)據(jù)集仍采取mpg,對hwy變量繪制直方圖。首先加載了擴展包,然后用ggplot函數(shù)建立了第一層,hwy數(shù)據(jù)映射到X軸上;使用+號增加了第二層,即直方圖對象層。此時p被視為一種層對象,使用summary函數(shù)可得到關于它的更多信息,print(p)命令即可進行繪圖。
1 library(ggplot2) 2 p <- ggplot(data = mpg,aes(x = hwy)) 3 p <- p + geom_histogram() 4 summary(p) 5 data: manufacturer, model, displ, year, cyl, trans, 6 drv, cty, hwy, fl, class [234x11] 7 mapping: x = hwy 8 faceting: facet_grid(. ~ ., FALSE) 9 ----------------------------------- 10 geom_histogram: 11 stat_bin: 12 position_stack: (width = NULL, height = NULL)?
上面的信息告訴我們,p對象含有兩層,第一層數(shù)據(jù)層描述了變量和映射方式,第二層是直方圖對象(geom_histogram),geom表示幾何對象,它是ggplot中重要的圖層控制對象,因為它負責圖形渲染的類型。geom_histogram是圖形渲染類型的一種,其它類型可參見官網(wǎng)。
每個geom對象都需要有數(shù)據(jù)輸入,數(shù)據(jù)可以從第一層中自動讀取,也可以在aes參數(shù)中直接設置。而且每個geom還默認搭配某種統(tǒng)計變換(stat),geom_histogram的默認統(tǒng)計變換是stat_bin。它負責對數(shù)據(jù)進行分組計數(shù)。
下面我們嘗試兩種更為復雜的直方圖,首先將數(shù)據(jù)按照year這個變量劃分為兩組,用不同的顏色繪制直方圖,而且用頻率而非計數(shù)來刻畫Y軸,并添加密度曲線。
p <- ggplot(mpg,aes(hwy)) p + geom_histogram(position = 'identity',alpha=0.5,aes(y = ..density..,fill = factor(year))) +stat_density(geom = 'line',position = 'identity',aes(colour = factor(year)))?
如果想將兩個直方圖分開繪制,也可以使用facet_grid參數(shù),結(jié)果如下圖所示。
?
? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ?轉(zhuǎn)載于:http://r-ke.info/2012/02/06/ggplot2-intro-2.html
轉(zhuǎn)載于:https://www.cnblogs.com/liulunyang/p/3868852.html
總結(jié)
以上是生活随笔為你收集整理的ggplot2绘图入门系列之二:图层控制与直方图的全部內(nèi)容,希望文章能夠幫你解決所遇到的問題。
- 上一篇: smokeping部署安装
- 下一篇: dede:arclist 不能调用文章的