先前写过几篇用ggplot2进行基本绘图的文章,但对于初学者,或只需绘制简单图形时,这些命令显得繁琐,这里介绍ggplot2中的快速绘图函数qplot(). 此函数相对能较快速便捷地绘制图形。
往期文章:
张光耀:ggplot2数据包画图系列1(散点图)zhuanlan.zhihu.com张光耀:ggplot2数据包画图系列2(条形图)zhuanlan.zhihu.com张光耀:ggplot2数据包画图系列3(分组条形图)zhuanlan.zhihu.com张光耀:ggplot2数据包画图系列4(交互作用折线图)zhuanlan.zhihu.com首先说一下qplot()中参数的含义:
qplot(x = , # 变量Xy = , # 变量Ydata = , # 某数据名(如果要根据某数据绘图)color = , # 定义线的颜色和方块的边界颜色fill = , # 定义方块的填充颜色shape = , # 定义几何对象的形状alpha = , # 定义透明度(范围0–1)facets = , # 定义分面margins = , # 是否显示分面后的列统计geom = , # 定义几何对象xlim = , # 定义X轴的范围ylim = , # 定义Y轴的范围log = , # 是否对X和Y进行对数转换main = , # 定义主标题xlab = , # 定义X轴标题ylab = , # 定义Y轴标题asp = , # 定义Y/X轴的比率... = )
下面我以R中自带的mtcars数据,对各参数举例演示一下。
mtcars收集了32辆不同品牌车辆的指标信息,包括重量(wt),百公里耗油量(加仑)(mpg),变速器类型(am)等。
- simple start
qplot(x = wt, y = mpg, data = mtcars)
指定x和y后,默认绘图为散点图。
- color
qplot(x = wt, y = mpg, data = mtcars, color = am)
这里用对不同变速器用不同的颜色来表示,但是变速器为0-1编码,默认为连续型变量,可以将其转化为因子型:
qplot(x = wt, y = mpg, data = mtcars, color = factor(am))
color也可以人为设置为某个颜色,但是需要注意,如果以下面的方式设置,其实是将blue当做一个变量,而不是一个颜色:
qplot(x = wt, y = mpg, data = mtcars, color = 'blue')
要想设置为蓝色,应该用I()函数来实现:
qplot(x = wt, y = mpg, data = mtcars, color = I('blue'))
- facet
qplot(x = wt, y = mpg, data = mtcars, facets = ~am) # 按照变速器分面
qplot(x = wt, y = mpg, data = mtcars, facets = cyl~am) # 按照气缸数和变速器分面,气缸数为行分面,变速器为列分面
qplot(x = wt, y = mpg, data = mtcars, facets = ~am*cyl) # 按照气缸数和变速器分面,气缸数和变速器都为列分面
- margins
qplot(x = wt, y = mpg, data = mtcars, facets = cyl~am,margins = T) # 对行分面进行汇总
- geom
qplot(x = mpg, data = mtcars, geom = 'dotplot') # 点图
qplot(x = mpg, data = mtcars, geom = 'histogram')
qplot(x = wt, y = mpg, data = mtcars,geom = 'line') # 折线
qplot(x = wt, y = mpg, data = mtcars,geom = 'smooth') # 拟合曲线
qplot(x = wt, y = mpg, data = mtcars,geom = c('point','line')) # 散点+折线
- xlim & ylim
qplot(x = wt, y = mpg, data = mtcars)
qplot(x = wt, y = mpg, data = mtcars, xlim = c(2,4), ylim = c(15,30))
- log
qplot(x = wt, y = mpg, data = mtcars,log = 'x')
qplot(x = wt, y = mpg, data = mtcars,log = 'xy')
- main & xlab & ylab
qplot(x = wt, y = mpg, data = mtcars,main = 'Example of qplot()',xlab = 'Weight',ylab = 'Miles per gallon')
- asp
qplot(x = wt, y = mpg, data = mtcars,asp = 2)
qplot(x = wt, y = mpg, data = mtcars,asp = 1/2)