简体   繁体   中英

ggplot multiple boxplots and stat_summary position

I have the following code. I'd like to change the color of the boxplots so they all have the same fill color (grey). Also I'd like to have the stat_summary texts to stick to the bottom of each barplot but vjust only seem to provide relative position?

Thanks

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

在此处输入图像描述

Here is a possible solution, but it needs ggplot v3.3.0 for the stage() function.

To point out major changes:

  • Instead of using the fill as an implicit grouping, I've explicitly set the grouping so it isn't tied to the fill.
  • I added the fill as an aesthetic of the bar geom.
  • The boxplot now has the unmapped aesthetic fill = 'gray'
  • The text stat summary uses stage() to calculate the statistic but then uses 0 as actual placement.
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()

Created on 2020-05-06 by the reprex package (v0.3.0)

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM