Warning: file_get_contents(/data/phpspider/zhask/data//catemap/3/flash/4.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
如何在R中动态更改图表标题?_R_Ggplot2_Ggtitle - Fatal编程技术网

如何在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