数据分析中最常用的图形是散点图。当我们想了解两个变量之间关系时,可以画个散点图看看。
今天来学习使用ggplot2包绘制带环绕曲线的散点图。
1. 加载数据集
使用mtcars数据集来演示。
data(mtcars)
View(mtcars)
使用str()函数看下数据集的结构。
str(mtcars)
2. 安装和加载R包
安装很简单。
install.packages("ggplot2")
install.packages("ggalt")
library(ggplot2)
library(ggalt)
3. 绘图
先绘个简单图形。
p1 <- ggplot(mtcars, aes(x=drat, y=mpg)) +
geom_point()
p1
映射分组变量和连续变量。
p2 <- ggplot(mtcars, aes(x=drat, y=mpg,
col=factor(vs), size=qsec)) +
geom_point()
p2
geom_smooth()函数添加平滑曲线,使用method参数指定平滑曲线的计算方法,se参数表示是否显示置信区间。
p3 <- ggplot(mtcars, aes(x=drat, y=mpg,
col=factor(vs), size=qsec)) +
geom_point() +
geom_smooth(method="loess", se=F)
p3
设置添加置信区间试试,设置se=T。
看看跟上面的区别。
p4 <- ggplot(mtcars, aes(x=drat, y=mpg)) +
geom_point(aes(col=factor(vs), size=qsec)) +
geom_smooth(method="loess", se=F)
p4
我们可以自定义设置主题外观,比如说添加轴标签、标题,设置轴范围等。
p5 <- p4 + xlim(c(2.5, 5)) +
ylim(c(10, 40)) +
labs(title="我是图形标题",
y="我是y轴标签",
x="我是x轴标签")
p5
可以添加自定义好的图形主题。
p6 <- p5 + theme_bw()
p6
在绘图时,我们可以将图上的某个区域围绕起来,从而达到突出显示的效果。
这个可以通过ggalt包里的geom_encircle()函数实现。
在geom_encircle()中,我们需要指定突出显示的数据范围,设置expand参数来指定曲线在散点之外,不在散点之上;另外也可以使用color和size参数来指定线的颜色及大小。
先选择需要突出显示的数据,这个就相当于在图上指定x轴的范围和y的范围。
mtcars_select <- mtcars[mtcars$drat > 2.5 &
mtcars$drat <= 4.3 &
mtcars$mpg > 20 &
mtcars$mpg < 26, ]
p7 <- p6 + geom_encircle(aes(x=drat, y=mpg),
data=mtcars_select,
color="red",
size=2,
expand=0.08)
p7
如上图所示,我们就在图形画了一个圈,圈住了我们需要显示的数据部分。
参考资料
http://r-statistics.co/Top50-Ggplot2-Visualizations-MasterList-R-Code.html