这是一个使用的示例mtcars
按变量分割成单独的图。我创建的是一个散点图vs
and mpg
通过将数据集拆分为cyl
。首先创建一个空列表。然后我用了lapply
循环遍历 cyl (4,6,8) 的值,然后filter
按该值的数据。之后,我绘制了子集的散点图并将其保存到空列表中。
library(dplyr)
library(ggplot2)
gglist <- list()
gglist <- lapply(c(4,6,8), function(x){
ggplot(filter(mtcars, cyl == x))+
geom_point(aes(x=vs,y=mpg))+
labs(title = "Relationship between vs and mpg based on the respective cyl")
})
gglist
输出返回三个散点图,标题为"Relationship between vs and mpg based on the respective cyl"
。但是,我希望根据 的唯一值动态更改每个散点图的标题cyl
.
unique(mtcars$cyl)
#[1] 6 4 8
各种图表标题的预期输出如下。
#"Relationship between vs and mpg when cyl is 4"
#"Relationship between vs and mpg when cyl is 6"
#"Relationship between vs and mpg when cyl is 8"
您可以使用paste
or paste0
连接字符串然后将其用作标题:
gglist <- lapply(c(4,6,8), function(x){
ggplot(filter(mtcars, cyl == x))+
geom_point(aes(x=vs,y=mpg))+
labs(title = paste("Relationship between vs and mpg when cyl is ", x))
})
gglist
本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系:hwhale#tublm.com(使用前将#替换为@)