【问题标题】:ggplot2 - annotate means in several graphggplot2 - 在几个图中注释意思
【发布时间】:2014-03-16 21:08:39
【问题描述】:

我尝试用每张图表的平均值来标记我的图表:

ggplot(diamonds, aes(x = carat, fill=cut)) +
stat_density(aes(ymax = ..density..,  ymin = -..density..),
   geom = "ribbon", position = "identity") +
   facet_grid(. ~ cut) +
   xlim(0,2.5) +
   geom_text(data = NULL, x = 0.6, y = 0, label = mean(carat), size=5) +
   coord_flip()

例如,这里我希望“Fair”的图表显示“Fair”的平均值,“Good”的图表显示“Good”的平均值等。

另外,但这是额外的,如果平均值为 1.0,我希望相对于 x 定位,而平均值显示在 x = 1.0

【问题讨论】:

    标签: r annotations ggplot2 mean


    【解决方案1】:

    有多种方法可以获取标签(以及标签的位置)。这里使用dplyr包来总结diamonds数据框;也就是获得所需的手段。另请注意,标签已格式化 - 两位小数。在下面的代码中, diamonds2 数据框包含均值和标签,并用于对 geom_text 的调用。

    library(ggplot2)
    library(dplyr)
    
    diamonds2 = transform(summarise(group_by(diamonds, cut), label = mean(carat)), 
       Label = sprintf("%.02f", label))
    
    ggplot(diamonds, aes(x = carat, fill=cut)) +
    stat_density(aes(ymax = ..density..,  ymin = -..density..), 
       geom = "ribbon", position = "identity") +
    facet_grid(. ~ cut) +
    xlim(0, 2.5) +
    geom_text(data = diamonds2, aes(label = Label, x = label, y = 0),  size=5) +
    coord_flip()
    

    【讨论】:

    • Warning in install.packages : package ‘dplyr’ is not available (for R version 2.15.1) 并且我无法更改R studio(在线服务器服务)的版本
    • 尝试使用 plyr 包中的 ddplylibrary(plyr); diamonds2 = transform(ddply(diamonds, .(cut), summarise, label = mean(carat)), Label = sprintf("%.02f", label)) 否则请查看 ?aggregate?by。 2.15.1 - 差不多 2 岁了。
    • 我已按照您的建议进行操作,但如果我构建此图表,可能会看到 geom_text 中的平均值和 geom_boxplot 中的平均值存在差异,我不知道如何解释它...snag.gy/xtbSs.jpg
    • 箱线图方框内的条形为中位数。
    猜你喜欢
    • 2016-10-27
    • 1970-01-01
    • 1970-01-01
    • 2015-03-16
    • 2015-05-20
    • 2014-05-02
    • 1970-01-01
    • 2012-06-21
    • 1970-01-01
    相关资源
    最近更新 更多