3

Using stat_summary to get mean & ci onto a plot along with a box plot

p1 <- ggplot(data=df, aes(x=group, y=metric ) ) +
  geom_boxplot(outlier.shape = NA, fill = fill, color=line, alpha = 0.5) +
  stat_summary(fun.data=mean_cl_normal, aes(color = "Mean and CI"))

Beyond this , I also have a requirement to limit the y-axis to avoid displaying values beyond a range. This is done via

p1 <- p1 + scale_y_continuous(limits =c(lower.limit,upper.limit) )

However, the observation is that when the limits are applied, the mean value as shown in the plot is different from the case where limits are not applied. Is this the way it is expected to work ? It seems like stat_summary only includes the points within the limits applied via scale_y_continuous

Is there a way I can get the mean & ci using stat_summary including the points outside the limits in the plot even when axis limits are applied ?

user3206440
  • 4,749
  • 15
  • 75
  • 132
  • 1
    Possible duplicate of [How to set limits for axes in ggplot2 R plots?](http://stackoverflow.com/questions/3606697/how-to-set-limits-for-axes-in-ggplot2-r-plots) – cuttlefish44 Nov 04 '16 at 05:26

1 Answers1

10

Its easier to help you if you provide a reproducible example with sample data. I think what you want is coord_cartesian().

?lims says;

Observations not in this range will be dropped completely and not passed to any other layers. ... . For changing x or y axis limits without dropping data observations, see coord_cartesian.

set.seed(1); df <- data.frame(x = "a", y = c(rnorm(18, 12, 3), 1, 2, 3))

g <- ggplot(df, aes(x, y, fill = x)) +
  geom_boxplot(alpha = 0.5) +
  stat_summary(fun.data=mean_cl_normal, aes(x = 0.9), colour = "blue") +
  theme(legend.position = "none")

g                                          # no limits
g + scale_y_continuous(limits = c(4, 17))  # outliers are dropped 
g + coord_cartesian(ylim = c(4, 17))       # outliers aren't dropped but not printed

enter image description hereenter image description hereenter image description here

cuttlefish44
  • 6,586
  • 2
  • 17
  • 34