如何在 R 中动态更改图表标题?
How to change the chart title dynamically in R?
这是一个使用 mtcars
将变量拆分为单独绘图的示例。我创建的是 vs
和 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
输出returns三个散点图,标题为"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
或 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
这是一个使用 mtcars
将变量拆分为单独绘图的示例。我创建的是 vs
和 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
输出returns三个散点图,标题为"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
或 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