How can I resize the boxes in a boxplot created with R and ggplot2 to account for different frequencies amongst different boxplots? [duplicate]

回眸只為那壹抹淺笑 提交于 2019-12-05 14:07:43

As @aosmith mentioned, varwidth is the argument you want. It looks like it may have been accidentally removed from ggplot2 at some point (https://github.com/hadley/ggplot2/blob/master/R/geom-boxplot.r). If you look at the commit title, it is adding back in the varwidth parmeter. I'm not sure if that ever made into the cran package, but you might want to check your version. It works with my version: ggplot2 v.1.0.0 I'm not sure how recently the feature was added.

Here is an example:

library(ggplot2)

set.seed(1234)
df <- data.frame(cond = factor( c(rep("A",200), rep("B",150), rep("C",200), rep("D",10)) ), 
                 rating = c(rnorm(200),rnorm(150, mean=0.2), rnorm(200, mean=.8), rnorm(10, mean=0.6)))

head(df, 5)
tail(df, 5)

p <- ggplot(df, aes(x=cond, y=rating, fill=cond)) + 
  guides(fill=FALSE) + coord_flip()

p + geom_boxplot()

Gives:

p + geom_boxplot(varwidth=T)

Gives:

For a couple of more options, you can also use a violin plot with scaled widths (the scale="count" argument):

p+ geom_violin(scale="count")

Or combine violin and boxplots to maximize your information.

p+ geom_violin(scale="count") + geom_boxplot(fill="white", width=0.2, alpha=0.3)

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