如何在ggplot中添加表达式到标签

时间:2015-02-04 04:15:47

标签: r ggplot2

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

“平均值= 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)

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

1 个答案:

答案 0 :(得分:2)

你有(至少)两个选择。

  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. parse=TRUE的通话中使用geom_text。在这种情况下,您需要根据?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)
    
  3. 选项2将在可视化时创建“更好”的表情。