13

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!

2
  • 3
    Welcome to stackoverflow. Congratulations on a well written first question with a reproducible example!! Commented Jul 5, 2013 at 1:26
  • I had a similar problem and discovered in the documentation for stat_summary that the width aesthetic can be defined in the fun.data function. Commented Jun 6, 2018 at 2:22

2 Answers 2

12

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)

enter image description here

Sign up to request clarification or add additional context in comments.

3 Comments

It works, thanks! I'll use it for the time being while the issue is being resolved.
I have been looking for this for a long time and now i found it. Thanks for the very useful tip.
In ggplot2_3.3.5 using width = .7 directrly without aes()
1

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

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.