0

I'm trying to align multiple plots in R, using ggplot2, so that the x axes line up vertically. However, as you can see, since the legends are different sizes, each 'x' axis is coming out a different width:

enter image description here

The code that I'm using right now is shown below. I'm happy to use any technique that works, not necessarily the approach that I'm using now.

th = theme(legend.key.width = unit(5, "cm"))

plots <- function() {
  ss <<- read_csv("support.csv")
  ww <<- read_csv("weight.csv")
  tt <<- read_csv("totals.csv")
  p1 <<- ggplot(data=ss, mapping=aes(t, support, colour=id)) + geom_line() + th
  p2 <<- ggplot(data=ww, mapping=aes(t, weight, colour=suppid)) + geom_line() + th
  p3 <<- ggplot(data=tt, mapping=aes(t, y, colour=total)) + geom_line() + th
  multiplot(p1, p2, p3, cols=1)
}

where multiplot is copied from cookbook-r.com. As you can see, my attempt to set the width of the legends did not work. I do need to see the legends so that I can tell which line is which (or at least make educated guesses about the middle graph).

Ben Kovitz
  • 4,920
  • 1
  • 22
  • 50
  • 1
    Have you looked at the `cowplot` package? (strange name, I know... but it can handle alignments which take into account margins and legends. – Melissa Key Apr 28 '18 at 23:23
  • @MelissaKey I tried to install `cowplot` but it requires a later version of R than I can install on my computer (a MacBook Air from 2009). – Ben Kovitz Apr 28 '18 at 23:24
  • Try either `cowplot`, `egg` or `patchwork` packages. See this answer for example https://stackoverflow.com/a/48164920/786542 – Tung Apr 28 '18 at 23:25
  • 1
    @Tung I just successfully installed `egg`, and `egg:ggarrange` aligned everything correctly! Now seeing about how to shrink the legends, since they're taking up most of the window. But even this is workable! Thanks! – Ben Kovitz Apr 28 '18 at 23:28
  • @Gregor Please don't close this question. One difference from the other question is that in my problem, the legends are causing the plots to be misaligned. I had previously looked at the other question and didn't think it was applicable because the plots there don't have legends. – Ben Kovitz Apr 28 '18 at 23:35
  • @Gregor Even after applying the solution in the other question, the legends are still obscuring each other. – Ben Kovitz Apr 29 '18 at 01:02
  • @BenKovitz: to tweak the legend, you can try the `lemon` package https://cran.r-project.org/web/packages/lemon/vignettes/legends.html – Tung Apr 29 '18 at 04:54

0 Answers0