0

How can I make the panels of separate ggplots align when the y-axis labels change in length across plots? Below I've saved two subsets of mtcars with longer and shorter model names. Although the overall plots are the same size, the panels are smaller in the mt_long plot because the y-axis labels take up more of the plot.

library(dplyr)
library(ggplot2)

ds_mt <- mtcars %>% rownames_to_column("model")
mt_short <- ds_mt %>% arrange(nchar(model)) %>% slice(1:4)
mt_long <- ds_mt %>% arrange(-nchar(model)) %>% slice(1:4)

plot_short <- 
    mt_short %>% 
    ggplot(aes(x = model, y = mpg)) + 
    geom_col() + 
    coord_flip()

plot_long <- 
    mt_long %>% 
    ggplot(aes(x = model, y = mpg)) + 
    geom_col() + 
    coord_flip()

plot_short
plot_long

enter image description here enter image description here

For this reprex, it is important that the plots be separate. Is there any way to set just the panel dimensions of the plot rather than the overall size of the plot?

Joe
  • 3,217
  • 3
  • 21
  • 37
  • Is using facets not an option? – Maurits Evers Nov 13 '18 at 05:54
  • @MauritsEvers no facets are out. This is just a reprex. In reality I need to produce a lot of plots from different datasets and want to control panel size explicitly if that is possible. – Joe Nov 13 '18 at 06:02
  • Likely duplicate: [How can I make consistent-width plots in ggplot (with legends)?](https://stackoverflow.com/questions/16255579/how-can-i-make-consistent-width-plots-in-ggplot-with-legends) – Henrik Nov 13 '18 at 07:32

2 Answers2

2

We can use gridarrange from the egg package

library(egg)
ggarrange(plot_short, plot_long, ncol = 1)

enter image description here

To save, use

gg <- ggarrange(plot_short, plot_long, ncol = 1)
ggsave("file.png", gg) 
Maurits Evers
  • 49,617
  • 4
  • 47
  • 68
1

try egg::set_panel_size(plot_short)

  • Please improve your question little bit more and also demonstrate it – Onic Team Nov 13 '18 at 05:54
  • @user10644264, your code is outputting a table rather than a plot. Is there a way to use set_panel_size with explicit measurements for width and length? – Joe Nov 13 '18 at 16:33