简体   繁体   中英

ggplot: How to change boxplot settings when stat_summary is used

I would like to have grouped boxplots which whiskers is defined by stat_summary. With help of changing-whisker-definition I wrote the following code:

# Data
xdf2 <- data.frame(month = rep(1:6,each=100)
                  , grp = rep(c('A','B'), 50*6)
                  )
xdf2$m <- rpois(n=nrow(xdf2),10)
# Definition of whiskers
f <- function(x) {
  r <- quantile(x, probs = c(0.10, 0.25, 0.5, 0.75, 0.90))
  names(r) <- c("ymin", "lower", "middle", "upper", "ymax")
  r
}

# Add points outside of whiskers
o <- function(x) {
  subset(x, x < quantile(x,probs=0.1) | quantile(x,probs=0.9) < x)
}


# Plot
ggplot(data = xdf2
         , aes(factor(month),m, color=grp)
         ) +
       stat_summary(fun.data = f
                    , geom="boxplot"
                    , position=position_dodge(width=1)
                    , size=1
                    ) +
        stat_summary(fun.y = o, geom="point", position=position_dodge(width=1)) +
        scale_color_manual(values = c("gray30","darkgrey"),labels = c("AAA","BBB")) +
        theme_bw()

which gives the following graphs: 在此输入图像描述

There are some changes I would like to perform:

  • How can I change the width of the boxes?
  • How can I fill the boxes with the same color of the border?

I would be happy for any help. Thanks a lot.

Map fill aesthetic to grp and add a similar scale for it. I'm using slightly different colours to make the mean visible.

To change boxplot widths, use ggsave with various width parameters, boxplots will be adjusted automatically. If you would like to add some space in between, you'll have to cheat a bit, see below.

It is not easy to modify width in conjunction with stat_summary : though there is a width parameter for geom_bar and geom_boxplot , I couldn't make it work properly with stat_summary . Instead, I'm using some dirty tricks with scale_x .

K <- length(unique(xdf2$month))
lev <- seq_len(1 + 2 * K)

xdf2$month2 <- factor(2 * xdf2$month, 
                      levels = lev)

ggplot(data = xdf2, aes(month2, m, color = grp, fill = grp)) +
  stat_summary(fun.data = f, geom="boxplot", 
               position=position_dodge(width=1.5), size=1) +
  stat_summary(fun.y = o, geom="point", position=position_dodge(width=1.5)) +
  scale_color_manual(values = c("gray30","darkgrey"),labels = c("AAA","BBB")) +
  scale_fill_manual(values = c("gray20","grey75"),labels = c("AAA","BBB")) +
  theme_bw() +
  scale_x_discrete(limits = lev, breaks = 1:K*2, labels = 1:K) 

在此输入图像描述

Play around width in position_dodge for additional adjustment.

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