wilkelab / cowplot

cowplot: Streamlined Plot Theme and Plot Annotations for ggplot2
https://wilkelab.org/cowplot/
704 stars 84 forks source link

Using any `align` option in `plot_grid()` adds unwanted space to the plot margins when plots have axes on the top/right #105

Closed dtdoering closed 6 years ago

dtdoering commented 6 years ago

I'm currently trying to align some plots using plot_grid(), with the axis text displayed on the outside edges of the plot and with minimal spacing between the plots. I want to have both of their axes aligned. However, when I use the align options, the plots have unwanted space between them as if the axes are still in their normal positions.

Here's a reprex:

p <- ggplot(mtcars, aes(x = mpg, y = cyl)) + geom_point()

p1 <- p +
  scale_x_continuous(position = "top") +
  theme(plot.background = element_rect(fill = "red"),
        panel.background = element_rect(fill = "white"),
        plot.margin = unit(c(0,0,0,0), "lines"))

p2 <- p +
  scale_x_continuous(position = "top") +
  scale_y_continuous(position = "right") +
  theme(plot.background = element_rect(fill = "blue"),
        panel.background = element_rect(fill = "white"),
        plot.margin = unit(c(0,0,0,0), "lines"))

p3 <- p +
  theme(plot.background = element_rect(fill = "orange"),
        panel.background = element_rect(fill = "white"),
        plot.margin = unit(c(0,0,0,0), "lines"))

p4 <- p +
  scale_y_continuous(position = "right") +
  theme(plot.background = element_rect(fill = "green"),
        panel.background = element_rect(fill = "white"),
        plot.margin = unit(c(0,0,0,0), "lines"))

This seems to be due to the use of scale_x_continuous(position = "right") or scale_y_continuous(position = "top") when attempting to align them:

Un-aligned: OK

plot_grid(p1, p2, p3, p4, ncol = 2) 

rplot

Align horizontally: space along middle line

plot_grid(p1, p2, p3, p4, ncol = 2, align = "h")

rplot01

Align vertically: space along center line

plot_grid(p1, p2, p3, p4, ncol = 2, align = "v")

rplot02

Align both: space along both

plot_grid(p1, p2, p3, p4, ncol = 2, align = "vh")

rplot03

Any idea what could be causing this behavior?

clauswilke commented 6 years ago

Yes, this is a limitation of the specific alignment algorithm that I use, and it cannot be circumvented within plot_grid(). I recommend you try ggarrange() from the egg package or plot composition via the patchwork package.