Changing bar width when using stat_summary with gg

2020-08-12 03:36发布

问题:

I am using stat_summary in ggplot to plot a bar chart. I would like to change the width of the bars. Usually this is done using the width option. With pre-summarised data and stat="identity it works as expected:

data <- data.frame(group=rep(c("a","b"), 20), y=rnorm(40,100,50))
se <- function(x, na.rm=T) sd(x, na.rm=na.rm)/sqrt(length(x))
data2 <- cast(data, group ~ ., value="y", c(mean, se))
ggplot(data2, aes(group, mean, ymin=mean-1.96*se, ymax=mean+1.96*se)) +
 geom_bar(stat="identity", width=0.5) + geom_errorbar(width=0, size=2)

However, in the same plot on original data using stat_summary, the bars don't change width, while errorbars do:

ggplot(data, aes(group, y)) + stat_summary(fun.y="mean", geom="bar", width=0.5) +
 stat_summary(fun.data="mean_cl_normal", geom="errorbar", width=0, size=2)

Is there a way to change bar width even when using stat_summary?

Since the first example works, this question obviously already has a work-around, however, I would really like to know if there is any way to do it with stat_summary, because I use it a lot and is often more convenient.

Thank you!

回答1:

This is the subject of a known issues 444 and 235

The current solution is to pass width within aes -- this goes against the principles of ggplot (mapping vs setting), but at least it works....

Note that you can use linerange if you want the error bars without erro bars!

ggplot(data, aes(group, y)) + 
 stat_summary(fun.y="mean", geom="bar", aes(width=0.5)) +
  stat_summary(fun.data="mean_cl_normal", geom="linerange",  size=2)



回答2:

This issue has been resolved. width now also works with stat_summary and geom="errorbar".



标签: r ggplot2