3

I have created multiple bar charts from my data, using stat_summary. However, I want to manually specify the limits of the error bars (instead of using mean_cl_boot). How can this be done for data graphed using facet_grid?

The code I used to create the charts is below:

graph <- ggplot(slantclean, aes(x = View,value, fill = Texture))

graph + stat_summary(fun.y = mean, geom = "bar", position = "dodge") + 
     stat_summary(fun.data = mean_cl_boot, geom = "pointrange", 
                     position = position_dodge(width = 0.90)) + 
     labs(x = "View", y = "Vertical height of ellipse (cm)", fill = "Texture") + 
     facet_grid( Shape ~ TNOGroup)

Unfortunately, the complex nature of the data means that a minimal example is impossible. The data frame can be accessed here. An example of the plot is here.

3
  • 1
    You likely will be more successful if you summarize your data outside the ggplot call (not relying on stat_summary). Then you could specify the size of the error bars at that time and just use that summarized data as a data argument to geom_pointrange. Commented Apr 22, 2013 at 18:23
  • I ended up doing this, was surprisingly simple. Thanks for the suggestion. Commented Apr 23, 2013 at 13:35
  • possible duplicate of How can one write a function to create custom error bars for use with ggplot2? Commented Jan 16, 2014 at 8:01

1 Answer 1

8

You can define your own function to use in stat_summary(). If you use geom="pointrange" in stat_summary() then your function should give y, ymin and ymax value in one dataframe.

Here is just example to make function my.fun that calculates minimal, maximal and mean value. When used in stat_summary() this values will be calculated for each level in your data.

my.fun<-function(x){data.frame(ymin=min(x),ymax=max(x),y=mean(x))}

graph <- ggplot(slantclean, aes(x = View,value, fill = Texture))

graph + stat_summary(fun.y = mean, geom = "bar", position = "dodge") + 
  stat_summary(fun.data = my.fun, geom = "pointrange", position = position_dodge(width = 0.90)) + 
  labs(x = "View", y = "Vertical height of ellipse (cm)", fill = "Texture") + 
  facet_grid( Shape ~ TNOGroup)

enter image description here

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

2 Comments

congrats on reaching 10K @Didzis!
I had to do as the comment on my original post suggested, as R was calculating the means across groups oddly. However, this is very useful for the future, thankyoU!

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.