stackinator
stackinator

Reputation: 5819

gridExtra panel plot with identical panel sizes in ggplot

library(tidyverse)
library(grid)
df <- tibble(
  date = as.Date(40100:40129, origin = "1899-12-30"), 
  value = rnorm(30, 8)
  )

p1 <- ggplot(df, aes(date, value)) + 
  geom_line() + 
  scale_x_date(date_breaks = "1 day") + 
  theme(
    axis.title.x = element_blank(), 
    axis.text.x = element_text(angle = 90, vjust = 0.5)
  ) + 
  coord_cartesian(xlim = c(min(df$date) + 0, max(df$date) - 0))

p2 <- ggplot(df, aes(date, value)) + 
  geom_bar(stat = "identity") + 
  scale_x_date(date_breaks = "1 day") + 
  theme(
    axis.title.x = element_blank(), 
    axis.text.x = element_text(angle = 90, vjust = 0.5)
  ) + 
  coord_cartesian(xlim = c(min(df$date) + 0, max(df$date) - 0))

Let's create the plots p1 and p1 as shown above. I can plot these stacked on top of each other with widths that are exactly identical (zoom to full screen to make it obvious). Note that the dates line up perfectly. Code is directly below.

grid.newpage()
grid.draw(rbind(ggplotGrob(p1), ggplotGrob(p2), size = "last"))

Unfortunately I can't use ggsave() with this code chunk above so I go to the gridExtra package.

gridExtra::grid.arrange(p1, p2)

This almost works, but notice the dates don't quite line up perfectly, in a vertical fashion comparing the top graph to the bottom graph. So... what's the equivalent to rbind()s size = "last" to get me two grid.arrange'd objects with exactly identical widths (so the dates line up properly)?

Upvotes: 0

Views: 339

Answers (2)

stackinator
stackinator

Reputation: 5819

I discovered a solution using the egg package which I think is included as part of ggplot2. I'm going to go this route to prevent having to install patchwork. It appears you need R 3.5+ to be able to install patchwork.

egg::ggarrange(p1, p2)
p <- egg::ggarrange(p1, p2)
ggsave(plot = p, "panel-plot.png")

Capture.png

Upvotes: 0

Jon Spring
Jon Spring

Reputation: 66415

As an alternative to grid, the new patchwork library might help here. It works with ggsave and does a good job of aligning plots.

https://github.com/thomasp85/patchwork

patchwork::plot_layout(p1 / p2)

enter image description here

Upvotes: 1

Related Questions