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)