Reputation: 2126
I would like to adjust the spacing between plots that are aligned in a panel using the cowplot
package when some plots contain axis titles/labels, and others don't.
Example
Let's create three plots:
library(tidyverse)
library(cowplot)
set.seed(123)
df <- data.frame(x = rnorm(n = 100),
y = rnorm(n = 100))
plot <- ggplot(data = df, aes(x, y)) + geom_point()
plot_grid(plot, plot, plot, nrow = 1, align = "vh")
These plots are aligned perfectly! But often, I have a scenario in which I would like to create a 'cleaner' panel figure. One way to do this is to remove the titles/text of the y-axis of the second and third plots.
Like this:
plot2 <- plot + theme(axis.title.y = element_blank(),
axis.text.y = element_blank())
plot_grid(plot, plot2, plot2, nrow = 1, align = "vh")
Again, perfectly aligned, but the spacing between the first and the second plot (and the second and third plot) is quite large. I would like to reduce the spacing to create a more compact plot, while the axis remain exactly the same size.
Expected output
Is this possible with cowplot
? Or is there another way to do this?
Upvotes: 2
Views: 1120
Reputation: 28441
Here is a solution using the patchwork
package
library(tidyverse)
set.seed(123)
df <- data.frame(x = rnorm(n = 100),
y = rnorm(n = 100))
plot1 <- ggplot(data = df, aes(x, y)) + geom_point()
plot2 <- plot1 + theme(axis.title.y = element_blank(),
axis.text.y = element_blank())
# install.packages("patchwork", dependencies = TRUE)
library(patchwork)
plot1 + plot2 + plot2 +
plot_layout(ncol = 3)
Created on 2020-07-24 by the reprex package (v0.3.0)
Upvotes: 0
Reputation: 13863
Referencing this post on github, plot_grid()
doesn't add any space by default and uses the margins of your plot. To remove the space outside your plot area, you can use them(plot.margin=...)
to remove.
With that being said... that's not what's going on here! Printing either plot
or plot2
will yield a plot with no margins. It appears the issue is with the use of the align=
argument in plot_grid()
. I'm not sure why, but setting it to anything other than the default values (align="none"
) results in the extra whitespace around the plots. Very strange... needless to say, removing that argument fixes your problem:
plot_grid(plot, plot2, plot2, nrow = 1, align="vh")
plot_grid(plot, plot2, plot2, nrow = 1, align="none")
Any further space would be added according to your graphics device, since the actual plot you get depends on the size and resolution of that device.
Upvotes: 2