如何在R中动态更改图表标题?
下面是一个使用如何在R中动态更改图表标题?,r,ggplot2,ggtitle,R,Ggplot2,Ggtitle,下面是一个使用mtcars将变量拆分为单独绘图的示例。我创建的是一个vs和mpg散点图,通过cyl分割数据集。首先创建一个空列表。然后我使用lappy循环遍历cyl(4,6,8)的值,然后根据该值过滤数据。之后,我绘制了子集的散点图,并将其保存到空列表中 library(dplyr) library(ggplot2) gglist <- list() gglist <- lapply(c(4,6,8), function(x){ ggplot(filter(mtc
mtcars
将变量拆分为单独绘图的示例。我创建的是一个vs
和mpg
散点图,通过cyl
分割数据集。首先创建一个空列表。然后我使用lappy
循环遍历cyl(4,6,8)的值,然后根据该值过滤数据。之后,我绘制了子集的散点图,并将其保存到空列表中
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 when cyl is 4"
#"Relationship between vs and mpg when cyl is 6"
#"Relationship between vs and mpg when cyl is 8"
您可以使用paste
或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
gglist
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