First, some mock graphs:
df <- data.frame(x = 1:10, y = 2:11)
Because my real graphs are fairly complicated, I'm going not going to provide them here, but will use other graphs that reproduce the problem. Suffice it to say that when align
is set to "hv"
in plot_grid
, it creates a lot of white space between my graphs. To fix that, I set the margins in the original plots like so:
library(ggplot2)
plot1 <- ggplot(df, aes(x = x, y = y)) +
geom_point() +
theme(plot.margin = unit(c(-1, 0, 0, 0), "cm"))
plot2 <- ggplot(df, aes(x = y, y = -x)) +
geom_point() +
theme(plot.margin = unit(c(-1, 0, 0, 0), "cm"))
plot3 <- ggplot(df, aes(x = x, y = y)) +
geom_point() +
theme(plot.margin = unit(c(-1, 0, 0, 0), "cm"))
plot4 <- ggplot(df, aes(x = y, y = -x)) +
geom_point() +
theme(plot.margin = unit(c(-1, 0, 0, 0), "cm"))
Which extended the tops of the plots so they fill the white space. All fine and dandy (in this example, there may be a little overlap between the top and bottom):
library(cowplot)
plot5 <- plot_grid(plot1, plot2, plot3, plot4, nrow = 2, ncol = 2,
align = "hv")
plot5
Until I tried to add labels. Because I had extended the plots, I wanted to add the labels higher than the y = 1
limit.
plot5 <- plot_grid(plot1, plot2, plot3, plot4, nrow = 2, ncol = 2,
align = "hv", labels = c("A", "B", "C", "D"),
label_x = 0.1,
label_y = 1.15)+
theme(plot.margin = unit(c(3, 1, 1, 1), "cm"))
plot5
Returns this warning:
Removed 1 rows containing missing values (geom_text).
Meaning it took off the two top labels, even though there appears to be sufficient space. So, I thought, perhaps the plot margins aren't being applied until after the labels are plotted, or perhaps clipping was causing a problem. So, I did this:
plot5 <- plot_grid(plot1, plot2, plot3, plot4, nrow = 2, ncol = 2,
align = "hv") +
theme(plot.margin = unit(c(3, 0, 0, 0), "cm")) +
coord_cartesian(clip = "off")
plot5 +
draw_plot_label(c("A", "B", "C", "D"), c(0, 0.5, 0, 0.5), c(1.1, 1.1, .5, .5))
Which returns the same error as before, although, as you can see, there is more space availiable at the top of the plot. As a last resort, I also turned off the clipping in the original plots, but that didn't fix anything either, eg:
plot1 <- ggplot(df, aes(x = x, y = y)) +
geom_point() +
theme(plot.margin = unit(c(-1, 0, 0, 0), "cm")) +
coord_cartesian(clip = "off")
The problem only occurs when I plot past y = 1
. y = 1.01
causes problems, for instance.
How do I fix this problem? It seems like a rather simple issue, unless there's a problem with ggplot
or cowplot
.