How to control box width when using stat_summary

Hi

Using stat_summary seems to be the only way I could find to create boxplots is non-standards statistics. This would work fine for me if I only could manage to control the box width. As you can see in the reprex below, geom_boxplot and stats_summary create boxes with different widths.

Any suggestion will be welcome.

mystats <- function(x){
  stats <- boxplot.stats(x)$stats
  names(stats) <- c('ymin', 'lower', 'middle', 'upper', 'ymax')
  stats
}
myout <- function(x){
  data.frame(y=boxplot.stats(x)[["out"]])
}

ggplot(mtcars, aes(x=factor(cyl), y=mpg)) + geom_boxplot()

ggplot(mtcars, aes(x=factor(cyl), y=mpg)) +
  stat_summary(fun.data=mystats, geom="boxplot") +
  stat_summary(fun.data=myout, geom="point")

You can set width within the stat_summary call.

mystats <- function(x){
  stats <- boxplot.stats(x)$stats
  names(stats) <- c('ymin', 'lower', 'middle', 'upper', 'ymax')
  stats
}
myout <- function(x){
  data.frame(y=boxplot.stats(x)[["out"]])
}
library(ggplot2)
ggplot(mtcars, aes(x=factor(cyl), y=mpg)) + geom_boxplot()


ggplot(mtcars, aes(x=factor(cyl), y=mpg)) +
  stat_summary(fun.data=mystats, geom="boxplot", width = 0.75) +
  stat_summary(fun.data=myout, geom="point")

Created on 2020-03-13 by the reprex package (v0.3.0)

1 Like

Thanks

This argument seems to be working with versions of ggplot2 that are newer than the one I have access on my production environment...

This topic was automatically closed 7 days after the last reply. New replies are no longer allowed.