1

When I facet a plot I often want to point out interesting comparisons between groups. For instance, in the plot produced by this code I'd like to point out that the second and third columns are nearly identical.

library(tidyverse)

ggplot(mtcars, aes(x = as.factor(am), y = mpg)) + 
    stat_summary(fun.y = "mean", geom = "col") + 
    stat_summary(fun.data = mean_se, geom = "errorbar", width = .1) + 
    facet_grid(~ vs) 

facetted plot

Currently I can only make this annotation by exporting my plot to another app like Preview or Powerpoint and manually adding the lines and text across facets.

with annotation

My efforts to add an annotation across facets results in annotations that do not leave their own facet. See below.

ggplot(mtcars, aes(x = as.factor(am), y = mpg)) + 
    stat_summary(fun.y = "mean", geom = "col") + 
    stat_summary(fun.data = mean_se, geom = "errorbar", width = .1) + 
    facet_grid(~ vs) +
    annotate("errorbarh", xmin = 2, xmax = 3, y = 25, height = .5, 
      color = "red") + 
    annotate("text", x = 2.5, y = 27, label = "NS", color = "red")

failed annotation

Any advice about how to extend lines and annotations across facets would be greatly appreciated.

Joe
  • 3,217
  • 3
  • 21
  • 37
  • 4
    Perhaps this might help... https://stackoverflow.com/questions/31690007/ggplot-drawing-line-between-points-across-facets – Andrew Gustar Jul 06 '17 at 17:25
  • 1
    @AndrewGustar, the code provided at that link and others (https://stackoverflow.com/questions/42151880/ggplot-drawing-multiple-lines-across-facets?rq=1) no longer works with the newest version of ggplot. Thank you for the suggestion, I will see if I can augment the older code to work in the latest version of ggplot2. – Joe Jul 06 '17 at 18:10
  • 2
    I guess it's worth pointing out that such custom solutions have always had a really short lifespan, so you may want to consider the alternative option of adding annotations manually in a drawing program. – baptiste Jul 06 '17 at 19:45
  • 1
    Thank you, @baptiste. I was thinking that if I used packrat I'd at least be able to lock in the package versions for any solution arrived at. I've been trying to make my plots fully reproducible from RStudio. – Joe Jul 06 '17 at 19:56

0 Answers0