3.8 Plotting Error Bars (ggplot2)

As mentioned above, when plotting error bars ggplot2 is much easier. Whether this is because of the general ongoing discussion about the usefulness of these plots we do not want to judge.

Anyway, plotting error bars in ggplot2 is as easy as everything elseā€¦

errbar_ggplot <- ggplot(cuts, aes(cut, fit, ymin = fit - se.fit, 
                                  ymax=fit + se.fit))
g_err <- errbar_ggplot + 
  geom_pointrange() +
  coord_flip() +
  theme_classic()

print(g_err)
A **ggplot2** dotplot including error bars and using a classic theme.

Figure 3.27: A ggplot2 dotplot including error bars and using a classic theme.

Especially, when plotting them as part of a bar plot.

g_err <- errbar_ggplot + 
  geom_bar(stat = "identity", fill = "grey80") +
  geom_errorbar(width = 0.2) +
  coord_flip() +
  theme_classic()

print(g_err)
A **ggplot2** bar plot including error bars and using a classic theme.

Figure 3.28: A ggplot2 bar plot including error bars and using a classic theme.

Just as before with the box widths, though, applying this to each facet is a little more complicatedā€¦ But still, trust us on this, much easier than to achieve the same result in lattice.

errbar_ggplot_facets <- ggplot(diamonds, aes(x = color, y = price))

### function to calculate the standard error of the mean
se <- function(x) sd(x)/sqrt(length(x))

### function to be applied to each panel/facet
myFun <- function(x) {
  data.frame(ymin = mean(x) - se(x), 
             ymax = mean(x) + se(x), 
             y = mean(x))
  }

g_err_f <- errbar_ggplot_facets + 
  stat_summary(fun.y = mean, geom = "bar", 
               fill = rep(clrs_hcl(7), 5)) + 
  stat_summary(fun.data = myFun, geom = "linerange") + 
  facet_wrap(~ cut)

print(g_err_f)
A **ggplot2** panel bar plot with error bars and modified fill colors.

Figure 3.29: A ggplot2 panel bar plot with error bars and modified fill colors.