DatistEQ之ggplot2可视化基础
2021-03-10 本文已影响0人
了无_数据科学
ggplot( )是ggplot系统的核⼼函数,一般先初始化一个ggplot图形,然后再逐渐在上面添加各式的图层。
例:研究mtcars数据集中,不同汽缸分组的汽车wt与mpg的关系
1.初始化图形
library(ggplot2)
g <- ggplot(mtcars, aes(wt, mpg))
ggsave(gettempfile(), width = 15, height = 10, dpi=300,units = "cm")
此时系统不知道要如何绘制数据,如不知道是用点、线或是其他形状绘制,还没有足够的信息来在屏幕上绘出这幅图。
注,以下几个小节的代码,是在基于上述代码的。
2.“+”添加各种图层
2.1 geom_point( )添加点
g + geom_point()
ggsave(gettempfile(), width = 15, height = 10, dpi=300,units = "cm")
调用时不带任何参数将使用一些默认值。
2.2 geom_smooth( )添加平滑曲线
g + geom_point()+ geom_smooth()
ggsave(gettempfile(), width = 15, height = 10, dpi=300,units = "cm")

g + geom_point() + geom_smooth(method = "lm")
ggsave(gettempfile(), width = 15, height = 10, dpi=300,units = "cm")

默认使用LOESS/LOWESS平滑器,边界处有很多噪音,数据少的区域置信区间变得很宽。线性模型的阴影区域代表的不确定性要比LOESS小得多。
2.3 facet_grid( )绘制分面图
g + geom_point() + facet_grid(. ~ cyl) + geom_smooth(method = "lm")
ggsave(gettempfile(), width = 15, height = 10, dpi=300,units = "cm")

cyl变量在“~”右边表示每个cyl水平的独立图排成一行。每个面板上的标签为条件因子变量的水平。
3.可以调整美学参数修改点的样式
3.1 修改点的颜色
g + geom_point(color = "steelblue", size = 4, alpha = 1/2)
ggsave(gettempfile(), width = 15, height = 10, dpi=300,units = "cm")

将表示颜色的字符变量赋给color,颜色设为steelblue。
g + geom_point(aes(color = cyl), size = 4, alpha = 1/2)
ggsave(gettempfile(), width = 15, height = 10, dpi=300,units = "cm")

将因子变量赋值给color,不同水平的点赋予不同的颜色,并添加图例。
3.2 labs( )添加标签
g + geom_point(aes(color = cyl)) + labs(title = "Automobile Data") +
labs(x = "weight", y = "Miles Per Gallon")
ggsave(gettempfile(), width = 15, height = 10, dpi=300,units = "cm")

3.3 调整平滑曲线
g + geom_point(aes(color = cyl), size = 2, alpha = 1/2) +
geom_smooth(size = 1, linetype = 2, method = "lm", se = FALSE) #se=FALSE不显示置信区间
ggsave(gettempfile(), width = 15, height = 10, dpi=300,units = "cm")

3.4 theme_bw( )设置黑白背景及字体
g + geom_point(aes(color = cyl)) + theme_bw(base_family = "Times")#使用Times字体
ggsave(gettempfile(), width = 15, height = 10, dpi=300,units = "cm")

上面介绍了ggplot2的基本使用方法,领略了一种全新的基于图层的绘图思想,以及一些具体统计图形的绘制方法,并穿插了诸如更换颜色、增加分面以及添加拟合线等小技巧。
参考文献: