【问题标题】:How to add expression to label in ggplot如何在ggplot中将表达式添加到标签
【发布时间】:2015-02-04 04:15:46
【问题描述】:

我已经能够添加基于构面的标签,但是,如何将其作为文本标签:

“平均值 = 0.235”,而不仅仅是“0.235”

这是我的ggplot,其中重要的部分是geom_text

ggplot(data = filter(season_melt,(HOUSEHOLD_ID_ANONYMISED %in% c(37218002754,37218032412, 38443537620))), aes(factor(HOUSEHOLD_ID_ANONYMISED), value)) + 
geom_boxplot(aes(fill = factor(HOUSEHOLD_ID_ANONYMISED))) + 
facet_wrap(~Season) + 
theme(text = element_text(size=40), legend.position = "none") + 
xlab("Household ID") + 
ylab("Usage") + 
geom_hline(data = mean_season, aes(yintercept = Mean), size = 1, colour = "blue", linetype = "dashed") + 
geom_text(data = mean_season, aes(0,Mean,label = round(Mean,3),  vjust = -1, hjust = -0.1), color = "blue", size = 11)

这是一张显示每个方面的标签的图片:

【问题讨论】:

    标签: r ggplot2


    【解决方案1】:

    你有(至少)两个选择。

    1. 创建合适的字符串

      # Something like
      geom_text(data = mean_season, 
             aes(0, Mean, label = sprintf('Mean = %0.3f', Mean),
                 vjust = -1, hjust = -0.1),
             color = "blue", size = 11)
      # or
            geom_text(data = mean_season, 
             aes(0, Mean, label = paste('Mean = ',round(Mean, 3)),
                 vjust = -1, hjust = -0.1),
             color = "blue", size = 11)
      
    2. 在对geom_text 的调用中使用parse=TRUE。在这种情况下,您需要根据?plotmath(和?geom_text)构造一个适当的表达式

        geom_text(data = mean_season, parse = TRUE
             aes(0, Mean, label = paste('Mean ==',round(Mean, 3)),
                 vjust = -1, hjust = -0.1),
             color = "blue", size = 11)
      

    选项 2 将在可视化时创建一个 “更好” 外观的表达式。

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 2018-09-04
      • 2020-12-27
      • 1970-01-01
      • 1970-01-01
      • 2021-09-19
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多