【问题标题】:how to show all mean values in the boxplot with ggplot2? [duplicate]如何使用ggplot2显示箱线图中的所有平均值? [复制]
【发布时间】:2021-11-02 04:56:36
【问题描述】:

我正在尝试使用 ggplot2 在箱线图中添加平均值(如下图中的红点所示)。我使用stat_summary 来添加平均值。

但是,下面的情节不是我正在寻找的那个。我想要得到的是显示Y(蓝色框)和N(红色框)的两个平均值,而不是两者的平均值。

这是我的代码。

ggplot(data = df.08.long,
      aes(x = TMT_signals, y = as.numeric(TMT_Intensities), fill = `probe.Mod.or.not(Y/N)`)) +
  geom_boxplot() +
  stat_summary(fun.y=mean, geom="point", shape=20, size=5, color="red", fill="red") +
coord_cartesian(
  xlim = NULL,
  ylim = c(0, 2e4),
  expand = TRUE,
  default = FALSE,
  clip = "on")
  theme_classic() +
  theme(axis.title=element_text(size=8),
        axis.text=element_text(size=10),
        axis.text.x = element_text(angle = 90, vjust = 0.5, hjust = 1))

有人知道如何解决这个问题吗?

非常感谢您的帮助!

【问题讨论】:

  • 一种解决方案是计算 ggplot 外部的平均值,然后使用 geom_point
  • @ViníciusFélix 我想​​过这个,但那将是我要尝试的最后一件事。我想知道是否有一个简单的解决方案。为什么我不能在stat_summary 中使用fill = probe.Mod.or.not(Y/N),就像我在aes 中所做的一样

标签: r ggplot2 boxplot


【解决方案1】:

mtcars 示例

代码

mtcars %>% 
  ggplot(aes(as.factor(vs),drat, fill = as.factor(am)))+
  geom_boxplot()+
  stat_summary(
    fun=mean,
    geom="point",
    shape=21,
    size=5,
    #Define the aesthetic inside stat_summary
    aes(fill = as.factor(am)),
    position = position_dodge2(width = .75),
    show.legend = FALSE
    ) 

输出

【讨论】:

    猜你喜欢
    • 2011-01-30
    • 2012-08-31
    • 2021-01-21
    • 2011-04-19
    • 2020-10-07
    • 2021-08-28
    • 2021-11-25
    • 2019-08-23
    • 1970-01-01
    相关资源
    最近更新 更多