【问题标题】:Adding Title to ggplot from the dataset itself从数据集本身向 ggplot 添加标题
【发布时间】:2021-10-17 23:33:54
【问题描述】:

我正在使用 R 编程语言。我使用内置的“mtcars”数据集制作了以下图表:

library(ggplot2)
a = ggplot(data=mtcars, aes(x=wt, y=mpg)) + geom_point() + ggtitle("mtcars: wt vs mpg")

问题:现在,我正在尝试自定义标题,但我希望标题“包含变量引用”,例如:

b = ggplot(data=mtcars, aes(x=wt, y=mpg)) + geom_point() + ggtitle("mtcars: wt vs mpg - average mpg = mean(mtcars$mpg)")

但是这个命令实际上只是打印我写的代码:

我知道“mean”命令自己运行:

 mean(mtcars$mpg)
[1] 20.09062

但是有人可以帮我更改此代码吗:

ggplot(data=mtcars, aes(x=wt, y=mpg)) + geom_point() + ggtitle("mtcars: wt vs mpg - average mpg = mean(mtcars$mpg)")

所以它会产生这样的东西(注意:这里,我手动写了“平均值”):

谢谢

【问题讨论】:

    标签: r ggplot2 data-visualization scatter-plot


    【解决方案1】:

    您可以使用paste() 执行此操作。

    ggplot(data=mtcars, aes(x=wt, y=mpg)) + geom_point() + ggtitle(paste0("mtcars: wt vs mpg - average mpg = ", mean(mtcars$mpg)))
    

    如果需要,您可以使用逗号添加更多文本和变量,如下所示:

    ggtitle(paste0('text ', var1, 'text2 etc ', var2, var3, 'text3'))
    

    请注意,paste0paste 的变体,它连接的事物之间没有空格或分隔符。

    【讨论】:

    • @Elle:非常感谢您的回答!我试过了,它有效!到目前为止,我一直在手动编写所有标题。我迫不及待地想用你给我看的方式自动做到这一点!非常感谢!
    • @Elle:6分钟后,我就能正式接受你的回答了。再次感谢!
    • 很高兴它有帮助! :)
    【解决方案2】:

    我们也可以使用stringr 包中的str_c,它是tidyverse 包的一部分。 str_c 等价于paste0

    library(tidyverse)
    
    ggplot(data=mtcars, aes(x=wt, y=mpg)) + geom_point() + ggtitle(str_c("mtcars: wt vs mpg - average mpg = ", mean(mtcars$mpg)))
    
    

    【讨论】:

      【解决方案3】:

      glue 的选项

      library(ggplot2)
      library(glue)
      ggplot(mtcars, aes(x = wt, y = mpg)) +
            geom_point() + 
            ggtitle(glue("mtcars: wt vs mpg - average mpg = {mean(mtcars$mpg)}"))
      

      【讨论】:

        猜你喜欢
        • 2021-04-26
        • 2011-01-22
        • 1970-01-01
        • 1970-01-01
        • 2012-07-24
        • 1970-01-01
        • 2013-03-31
        • 2011-03-08
        • 1970-01-01
        相关资源
        最近更新 更多