1
votes

I have count data with two types of density (level: 1 and 3). I have plotted the raw data with boot-strapped confidence intervals using summary_stat function in R. I want to extract the upper and lower limits of the confidence interval from this plot. How can I achieve that?

data <- data.frame(set = c(1, 1, 1, 2, 2, 3, 3, 3, 3, 3, 4, 4), 
                   density = c(1, 3, 3, 1, 3, 1, 1, 1, 3, 3, 1, 3), 
                   counts = c(100, 2, 3, 76, 33, 12, 44, 13, 54, 36, 65, 1), 
                   ratio = c(1, 2, 3, 4, 1, 2, 3, 4, 5, 6, 90, 1))
data$density <- as.factor(data$density)

pd <- position_dodge(0.82)
library(ggplot2)
ggplot(data, aes(x=density, y=counts, fill=density)) + 
   theme_bw() +  
   stat_summary(geom="bar", fun.y=mean, position = "dodge") + 
   stat_summary(geom="errorbar", fun.data=mean_cl_boot, width = 0.1, 
                size = 1.2, col = "grey57", position = pd) + 
   ylab("Counts")
1

1 Answers

1
votes

You can use ggplot_build().
The function gives you two pieces of information: a list of data frames (one for each layer), and a panel object, which contain all information about axis limits, breaks etc.:

p <- ggplot(data, aes(x=density, y=counts, fill=density)) + 
  theme_bw() +  
  stat_summary(geom="bar", fun.y=mean, position = "dodge") + 
  stat_summary(geom="errorbar", fun.data=mean_cl_boot, width = 0.1, 
               size = 1.2, col = "grey57", position = pd) + 
  ylab("Counts")

plot_info <- ggplot_build(p)$`data`[[2]]

In your case, all relevant information is stored in the ymin and ymax columns of the second list in $data.

 # density 1 error bounds
 density1_error_min <- plot_info[1, 'ymin']
 density1_error_max <- plot_info[1, 'ymax']

 # density 3 error bounds
 density3_error_min <- plot_info[2, 'ymin']
 density3_error_max <- plot_info[2, 'ymax']