ggplot: How to change boxplot settings when stat_summary is used

▼魔方 西西 提交于 2019-12-04 04:02:08

问题


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.


回答1:


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.



来源:https://stackoverflow.com/questions/28363933/ggplot-how-to-change-boxplot-settings-when-stat-summary-is-used

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!