ggplot多个箱形图和stat_summary位置

时间:2020-05-06 13:20:36

标签: r ggplot2 boxplot

我有以下代码。我想更改方框图的颜色,以便它们都具有相同的填充色(灰色)。 我也想让stat_summary文本粘贴到每个小节的底部,但只是似乎只是提供了相对位置?

谢谢

boxp <- ggplot(mtcars, aes(as.factor(cyl), wt, fill=as.factor(am)) ) +
  geom_bar(position = "dodge", stat = "summary", fun.y = "median") +
  geom_boxplot(outlier.shape = NA, width=0.2, color = "black", position = position_dodge(0.9)) +
  stat_summary(aes(label=round(..y..,2)), fun.y=median, geom="text", size=8, col = "white", vjust=8, position = position_dodge(0.9)) +
  stat_summary(fun.y=mean, geom="point", shape=18, size=4, col="white", position = position_dodge(0.9)) +
  labs(x = "Conditions", y = "Medians") +
  scale_y_continuous(limits=c(0,7),oob = rescale_none) +
  theme_bw()
boxp

enter image description here

1 个答案:

答案 0 :(得分:1)

这是一个可能的解决方案,但stage()函数需要ggplot v3.3.0。

指出主要变化:

  • 我没有将填充用作隐式分组,而是显式设置了分组,以使其与填充无关。
  • 我添加了填充物作为条形几何图形的美感。
  • 箱线图现在具有未映射的美感fill = 'gray'
  • 文本统计摘要使用stage()计算统计信息,然后使用0作为实际位置。
library(ggplot2)
library(scales)

ggplot(mtcars, aes(as.factor(cyl), wt,
                   group = interaction(as.factor(cyl), as.factor(am)))) +
  geom_bar(aes(fill=as.factor(am)), position = "dodge", stat = "summary", fun = "median") +
  geom_boxplot(outlier.shape = NA, width=0.2, 
               color = "black", fill = 'gray',
               position = position_dodge(0.9)) +
  stat_summary(aes(label=round(after_stat(y), 2), y = stage(wt, after_stat = 0)), 
               fun=median, geom="text", size=8, col = "white", vjust=-0.5,
               position = position_dodge(0.9)) +
  stat_summary(fun=mean, geom="point", shape=18, size=4, col="white", position = position_dodge(0.9)) +
  labs(x = "Conditions", y = "Medians") +
  scale_y_continuous(limits=c(0,7),oob = rescale_none) +
  theme_bw()

reprex package(v0.3.0)于2020-05-06创建