ggplot2 | aes_string和aes函数有什么区别?
1 两个函数的区别aes_string()函数和aes()函数的功能是一致的,都是ggplot2绘图系统中用来引用具有映射关系的变量的函数。区别在于使用方法不同:aes()函数引用变量时不需要加引号;aes_string()函数则需要加引号。library(ggplot2)ggplot(mtcars,aes(mpg,qsec))+geom_point()+...
1 两个函数的区别
aes_string()
函数和aes()
函数的功能是一致的,都是ggplot2绘图系统中用来引用具有映射关系的变量的函数。区别在于使用方法不同:
aes()
函数引用变量时不需要加引号;aes_string()
函数则需要加引号。
library(ggplot2)
ggplot(mtcars, aes(mpg, qsec)) +
geom_point() +
geom_smooth() +
theme_bw(base_size = 18, base_family = "mono")
ggplot(mtcars, aes_string("mpg", "qsec")) +
geom_point() +
geom_smooth() +
theme_bw(base_size = 18, base_family = "mono")
如果使用aes()
函数给变量名加引号或使用aes_string()
函数不加引号,程序运行结果如下面的示例。
使用aes()
函数时变量名加引号:
ggplot(mtcars, aes("mpg", "qsec")) +
geom_point() +
geom_smooth() +
theme_bw(base_size = 18, base_family = "mono")
使用aes_string()
函数时变量名不加引号,直接报错:
ggplot(mtcars, aes_string(mpg, qsec)) +
geom_point() +
geom_smooth() +
theme_bw(base_size = 18, base_family = "mono")
# Error in `check_aesthetics()`:
# ! Aesthetics must be either length 1 or the same as the data (32): x and y
# Run `rlang::last_error()` to see where the error occurred.
2 aes_string()
函数的应用场景
aes_string()
函数最常使用的场景是在循环语句中绘制图形。
例如,使用mtcars
数据集,固定以mpg
为横轴,分别以disp
、wt
、qsec
三个变量为纵轴绘制散点图和平滑曲线。
yvar <- c("disp", "wt", "qsec")
for(i in 1:3) {
F0 <- ggplot(mtcars, aes_string("mpg", yvar[i])) +
geom_point() +
geom_smooth() +
theme_bw(base_size = 18, base_family = "mono")
assign(paste0("F", i), F0)
}
library(patchwork)
(F1 + F2)/F3
yvar[i]
本身指向的是一个字符串,因此不需要再加引号。
使用aes()
函数很难达到这个效果。在这里,我们尝试使用数据框索引的形式进行绘图。代码如下,c(3,6,7)
表示三个纵轴变量分别位于数据框的第3、6、7列:
data("mtcars")
for(i in c(3,6,7)) {
F0 <- ggplot(mtcars, aes(mpg, mtcars[,i])) +
geom_point() +
geom_smooth() +
theme_bw(base_size = 18, base_family = "mono")
assign(paste0("F2", i), F0)
}
(F23 + F26)/F27
可以看出,尽管能绘制出图形,但是三幅图形实际上是同一副图,即纵轴变量均为qsec
。
这是因为,每次循环都会修改i
的值,aes()
函数接受的参数是mtcars[,i])
本身,它所指向的对象会随着i
的变化而变化,循环结束后所指向的是qsec
变量。
aes_string()
函数接受的参数是yvar[i]
所对应的字符串,该字符串不会随i
变化而变化,相当于进行了一次“锁定”。
更多推荐
所有评论(0)