How to force multiple r plots to have the same length of x-ticks?

517 Views Asked by At

Several packages in R are able to arrange mulitple plots into a grid, such as gridExtra and cowplot. The plots in the same row/column is by default aligned on their boundary. The following is an example. Three histograms are vertically arranged on the same plot. You can notice that the x-ticks are not algned and thus the grid plot looks a little ugly.

library(ggplot2);library(grid);library(cowplot)

p1 <- ggplot(data = NULL, aes(x = rt(10,19))) + 
  geom_histogram(bins = 5, fill = "darkgreen", color = "darkgrey", alpha = 0.6) +
  labs(y = "", x = "")
# similar plots for p2, p3

plot_grid(p1, textGrob("N=10"),
             p2, textGrob("N=100"),
             p3, textGrob("N=10000"),
             nrow=3, rel_widths = c(4/5, 1/5))

example grid plot

The problem is that plotting tools in base and ggplot2 would not fix the length of x-ticks and cowplot::plot_grid just automatically stretches the plots to the max width. Some of the plots have wider y-labels so they end up with shorter x-ticks.

Now I want to force the three histogram to have same lengths of x-ticks. I would like to know is there any method/package for this kind of problems? Note that usually data reshaping combined with funcitons like ggplot2::facet_wrap should solve this issue but I still wonder if there is a more direct solution.

2

There are 2 best solutions below

1
On BEST ANSWER

I personally think that patchwork handles the alignments of the plots gracefully and you can have the plots share an x-axis by setting the limits on a common scale.

library(ggplot2)
library(patchwork)

set.seed(123)

plots <- lapply(c(10, 100, 1000), function(n) {
  ggplot(mapping = aes(x = rt(n, 19))) +
    geom_histogram(bins = round(sqrt(n)) * 2,
                   fill = "darkgreen", colour = "darkgrey",
                   alpha = 0.6) +
    labs(y = "", x = "")
})

plots[[1]] / plots[[2]] / plots[[3]] &
  scale_x_continuous(limits = c(-5, 5),
                     oob = scales::oob_squish)

Created on 2020-11-26 by the reprex package (v0.3.0)

0
On

The plot_grid() function can align plots, see here: https://wilkelab.org/cowplot/articles/aligning_plots.html

library(ggplot2)
library(grid)
library(cowplot)

set.seed(123)

plots <- lapply(c(10, 100, 1000), function(n) {
  ggplot(mapping = aes(x = rt(n, 19))) +
    geom_histogram(bins = round(sqrt(n)) * 2,
                   fill = "darkgreen", colour = "darkgrey",
                   alpha = 0.6) +
    labs(y = "", x = "") +
    scale_x_continuous(
      limits = c(-5, 5),
      oob = scales::oob_squish
    )
})

plot_grid(
  plots[[1]], textGrob("N=10"),
  plots[[2]], textGrob("N=100"),
  plots[[3]], textGrob("N=10000"),
  nrow=3, rel_widths = c(4/5, 1/5), align = "v", axis = "l"
)

Created on 2020-11-26 by the reprex package (v0.3.0)