ggplot2的简单实用
本文参考了《ggplot2作图详解》http://www.plob.org/2014/01/24/7452.html, 这篇文章比较详细介绍ggplot2的绘图过程,本文只是一个简单使用的总结,能满足数据分析过程的大部分图标要求。
ggplot2包有两个绘图方法,一个是qplot,一个是ggplot方法。
qplot()函数即 quick plot(快速绘图),是R语言的plot过渡到ggplot而存在的,怕用户直接使用ggplot不习惯,当然qplot也包含了ggplot的很多思想,在使用qplot会慢慢理解ggplot的映射,分组,图层等的概念。虽然使用qplot函数也能实现大部分ggplot的功能,但是只是用qplot就没办法体现ggplot的强大了。
ggplot()函数是ggplot2包的核心函数,也是我们要重点学习的。但是也不难,因为我们只是使用它的绘图接口,常用的图形也就是那几个,从学以致用的角度来说是很容易的。
1.qplot函数的使用
qplot(x, y = NULL, ..., data, facets = NULL,
margins = FALSE, geom = "auto", stat = list(NULL),
position = list(NULL), xlim = c(NA, NA),
ylim = c(NA, NA), log = "", main = NULL,
xlab = deparse(substitute(x)),
ylab = deparse(substitute(y)), asp = NA)
- x, y: 告诉qplot应该使用什么数据作为x轴和y轴。
- data: 这个可以有,为数据框(data.frame)类型;如果有这个参数,那么x,y的名称必需对应数据框中某列变量的名称。
- facets: 图形/数据的分面。这是ggplot2作图比较特殊的一个概念,它把数据按某种规则进行分类,每一类数据做一个图形,所以最终效果就是一页多图。
- margins: 是否显示边界
- geom: 图形的几何类型(geometry),这又是ggplot2的作图概念。ggplot2用几何类型表示图形类别,比如point表示散点图、line表示曲线图、bar表示柱形图等。
- stat: 统计类型(statistics),这个更加特殊。直接将数据统计和图形结合,这是ggplot2强大和受欢迎的原因之一。
- position: 图形或者数据的位置调整,这不算太特殊,但对于图形但外观很重要
- xlim, ylim, xlab, ylab, main: 可以按照plot函数的相应参数来理解,x,y轴的范围,标签,主标题
- 其他参数:color:指定颜色,size:指定大小,shape:指定形状。如果是因子型变量,则会分组绘图。
1.1 散点图(默认)
str(diamonds)
set.seed(1000) # 设置随机种子
datax<- diamonds[sample(53940, 100), seq(1,7)] #抽100条数据绘图
qplot(x=carat, y=price, data=datax, xlab="Carat", ylab="Price", main="这是散点图")
1.2 分组绘图
这个概念可以理解为不同因子水平的数据用不同颜色,大小,形状来标记。
color:颜色
shape:形状
size:大小
qplot(x=carat, y=price, data=datax, color=cut, shape=cut, main="分组绘图")
1.3 其他图形
使用qplot绘制其他图形通过 geom 参数指定。
- point:散点图
- line:曲线图
- smooth:平滑曲线,拟合曲线
- jitter:另一种散点图
- boxplot:箱线图
- histogram:直方图
- density:密度分布图
- bar:柱状图
# 曲线图
qplot(x=carat, y=price, data=datax, color=cut, geom="line", main="曲线图")
# 曲线图+散点图
qplot(x=carat, y=price, data=datax, color=cut, geom=c("line", "point"), main="曲线图+散点图")
# 拟合曲线(平滑曲线)
qplot(carat, price, data = diamonds, color=cut, geom = "smooth", main = "拟合曲线")
# 箱线图
qplot(cut, price, data = diamonds, fill=cut, geom = "boxplot", main = "箱线图")
# 直方图
qplot(price, data = diamonds, fill=cut, geom = "histogram", main = "直方图")
# 密度分布图
qplot(price, data = diamonds, color=cut, geom = "density", main = "密度分布图")
1.4 柱状图
做柱形图很少直接用原始数据,一般都要通过计算变换如求平均值,计数后再做。这其实是一个统计过程,所以多数柱形图应该也是统计类型的图。ggplot2对柱形图的处理体现了这一思想:柱形图是一种特殊的直方图。所以ggplot2可以直接用原始数据做出柱形图,这是它的优点之一。
通过 stat 和 fun.y 和指定统计函数
# 柱状图
qplot(x=cut, y=price, data = diamonds, fill=cut, geom = "histogram",stat="summary", fun.y="mean")
2 ggplot的简单使用
ggplot绘图使用类似PS图层的概念,底层是一个空的图层,但是指定了x,y轴的数据映射,颜色,形状,大小等映射也可以指定。然后在底层图层上面不断添加的点图,曲线图等的其他图层,在添加图层的时候也可以指定和底层图层不同的颜色,形状等的映射。
下面是一个简单的但是比较全的ggplot的使用过程。
# 1.选择500条记录画图
library(ggplot2)
set.seed(100)
d.sub <- diamonds[sample(nrow(diamonds), 500), ]
# 2.作图首先要指定x和y数据,即建立数据框变量和x/y之间的映射:
p <- ggplot(data=d.sub, aes(x=carat, y=price))
# 3.作出散点图
p + geom_point()
# 4.如果还要建立其他映射,比如用钻石颜色(color),形状(cut)分类数据确定点的颜色,图形外观就会发生变化
p + geom_point() + aes(color=color, shape=cut)
#或者
p + geom_point(aes(color=color, shape=cut))
2.1 ggplot支持的geom_绘图类型
ls("package:ggplot2", pattern="^geom_.+")
函数 | 说明 |
---|---|
geom_abline | Lines: horizontal, vertical, and specified by slope and intercept. |
geom_bar | Bars, rectangles with bases on x-axis |
geom_bin2d | Add heatmap of 2d bin counts. |
geom_blank | Blank, draws nothing. |
geom_boxplot | Box and whiskers plot. |
geom_contour | Display contours of a 3d surface in 2d. |
geom_count | Count the number of observations at each location. |
geom_density | Display a smooth density estimate. |
geom_density2d | Contours from a 2d density estimate. |
geom_dotplot | Dot plot |
geom_errorbarh | Horizontal error bars |
geom_hex | Hexagon binning. |
geom_freqpoly | Histograms and frequency polygons. |
geom_jitter | Points, jittered to reduce overplotting. |
geom_crossbar | Vertical intervals: lines, crossbars & errorbars. |
geom_map | Polygons from a reference map. |
geom_line | Connect observations. |
geom_point | Points, as for a scatterplot |
geom_polygon | Polygon, a filled path. |
geom_quantile | Add quantile lines from a quantile regression. |
geom_area | Ribbons and area plots. |
geom_rug | Marginal rug plots. |
geom_curve | Line segments and curves. |
geom_smooth | Add a smoothed conditional mean. |
geom_spoke | A line segment parameterised by location, direction and distance. |
geom_label | Textual annotations. |
geom_raster | Draw rectangles. |
geom_violin | Violin plot. |
geom_qq | Calculation for quantile-quantile plot. |
update_geom_defaults | Modify geom/stat aesthetic defaults for future plots |
2.2 ggplot支持的 stat_ 统计函函数
ls("package:ggplot2", pattern="^stat_.+")
[1] "stat_bin" "stat_bin_2d" "stat_bin_hex" "stat_bin2d"
[5] "stat_binhex" "stat_boxplot" "stat_contour" "stat_count"
[9] "stat_density" "stat_density_2d" "stat_density2d" "stat_ecdf"
[13] "stat_ellipse" "stat_function" "stat_identity" "stat_qq"
[17] "stat_quantile" "stat_smooth" "stat_spoke" "stat_sum"
[21] "stat_summary" "stat_summary_2d" "stat_summary_bin" "stat_summary_hex"
[25] "stat_summary2d" "stat_unique" "stat_ydensity"