如何在R中动态更改图表标题? [英] How to change the chart title dynamically in R?

查看:99
本文介绍了如何在R中动态更改图表标题?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

以下是使用 mtcars 将变量拆分为单独图的示例.我创建的是通过将数据集划分为 cyl vs mpg 的散点图.首先,创建一个空列表.然后,我使用 lapply 遍历cyl(4,6,8)的值,然后通过该值 filter 过滤数据.之后,我绘制了子集的散点图,并将其保存到空白列表中.

Here is an example using mtcars to split by a variable into separate plots. What I created is a scatter plot of vs and mpg by splitting the data set by cyl. First an empty list is created. Then I used lapply to loop through the values of cyl (4,6,8) and then filter the data by that value. After that I plotted the scatter plot for the subset and saved it to the empty list.

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

输出返回三个散点图,其标题为"vs和mpg之间的关系,基于各自的cyl" .但是,我希望根据 cyl 的唯一值来动态更改每个散点图的标题.

The output returns three scatter plots with the title "Relationship between vs and mpg based on the respective cyl". However I wish to dynamically change the title of each scatter plot based on the unique value of cyl.

unique(mtcars$cyl)
#[1] 6 4 8

各种图表标题的预期输出如下.

Expected output of various chart titles is as folllows.

#"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 连接字符串,然后将其用作标题:

You can use paste or paste0 to concatenate strings and then use that as the title:

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

这篇关于如何在R中动态更改图表标题?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆