ggplot2工具箱架構
ggplot2的圖層化架構讓咱們以一種結構化的方法來設計和構建圖形,這裏每一小節解決一個特定的做圖問題。ide
1.基本圖形類型工具
使用如下代碼繪製幾何對象:佈局
> library(ggplot2) > df <- data.frame( + x=c(3,1,5), + y=c(2,4,6), + lable=c("a","b","c") + ) > p <- ggplot(df,aes(x,y))+xlab(NULL)+ylab(NULL) > p + geom_point()+labs(title="geom_point") > p + geom_bar(stat="identity")+labs(title="geom_bar(stat=\"identity\")") > p + geom_line() + labs(title="geom_line") > p + geom_area()+labs(title="geom_area") > p+ geom_path()+labs(title="geom_path") > p + geom_text(aes(label=lable))+labs(title="geom_text") > p + geom_tile() + labs(title="geom_tile") > p + geom_polygon() + labs(title="geom_polygon")
2.展現數據分佈測試
爲了找到一個表現力強的視圖,屢次測試組距的佈局細節是必不可少的。設計
> depth_dist1 <- ggplot(diamonds , aes(depth)) + xlim(40,80) > depth_dist1 + geom_histogram() #左圖 > depth_dist2 <- ggplot(diamonds,aes(depth)) + xlim(55,70) > depth_dist2 + geom_histogram(binwidth=0.1)#右圖
永遠不要期望依靠默認的參數就能對某個具體的分佈得到一個表現力強的圖形(上圖左),圖右對x軸進行了放大,並選取了一個更小的組距寬度,binwidth=0.1orm
較左圖揭示出了更多的細節,咱們發現這個分佈是輕度右偏的。對象
有多種方式能夠用來進行分佈的跨組比較,同時繪製多個小的直方圖:facets=.~var ,使用頻率多邊形:position="fill" blog
咱們使用直方圖展現diamond數據中的depth變量:it
> library(ggplot2) > depth_dist <- ggplot(diamonds , aes(depth)) + xlim(58,68) > depth_dist + geom_histogram(aes(y=..density..),binwidth=0.1) + facet_grid(cut ~ .)
用cut屬性進行填充:
> depth_dist <- ggplot(diamonds , aes(depth)) + xlim(58,68) > depth_dist + geom_histogram(aes(fill=cut),binwidth=0.1,position="fill")
如下是頻率多邊形:freqpoly
> depth_dist + geom_freqpoly(aes(y=..density..,colour=cut),binwidth=0.1)
變量density基本上至關於count除以count的總和,和分佈相關的許多幾何對象都是以幾何對象(geom)/統計變換(stat)的形式成對出現的。
一個基本幾何對象結合一個統計變換,便可繪製出想要的圖形。
3.處理遮蓋繪製問題
散點圖是研究兩個連續變量間關係的重要工具。但當數據量很大時,這些點會常常出現重疊現象,掩蓋真實的關係。這種問題被稱爲遮蓋繪製,提供如下幾種方法:
> df <- data.frame(x = rnorm(2000),y=rnorm(2000)) > norm <- ggplot(df,aes(x,y)) > norm + geom_point()
> norm + geom_point(shape=1)
> norm + geom_point(shape=".") ##點的大小爲像素級
> norm + geom_point(colour = "black",alpha=1/3) > norm + geom_point(colour = "black",alpha=1/5) > norm + geom_point(colour = "black",alpha=1/10)