3

Ggplot2 allows one to add error bars to a plot. To calculate the error bar limits for you, it wraps functions from Hmisc. For example, to bootstrap one can use the mean_cl_boot option:

m <- ggplot(mtcars, aes(x=cyl, y=am)) + stat_summary(fun.y=mean,geom="point")
m2 <- m + stat_summary(fun.data = "mean_cl_boot", geom = "errorbar", conf.int=.95)
m2

But what if you need to write a custom function to calculate the error bar limits? How should the function be written to be invoked from a stat_summary call?

1 Answer 1

9

Here's an example using the add4ci function from PropCIs providing a confidence interval. You just need to have the function return a list of numbers named "y", "ymin", and "ymax":

library(PropCIs)
add4ciForGgplot <- function(x,conf.int) {
  numCorrect <- sum(x)
  numTrials <- length(x)
  CI <- add4ci(numCorrect,numTrials,conf.int)
  triplet <- data.frame(numCorrect/numTrials, CI$conf.int[1], CI$conf.int[2])
  names(triplet) <- c("y","ymin","ymax") #this is what ggplot is expecting
  return (triplet)
}

m <- ggplot(mtcars, aes(x=cyl, y=am)) + stat_summary(fun.y=mean,geom="point")
mCustom <- m + stat_summary(fun.data = "add4ciForGgplot", geom = "errorbar", conf.int=.95)
mCustom
Sign up to request clarification or add additional context in comments.

1 Comment

At some stage (from at least ggplot2 3.2.0) the syntax has changed to stat_summary(fun.data = "add4ciForGgplot", geom = "errorbar", fun.args = list(conf.int=.95))

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.