简体   繁体   中英

Align vertical 3 plots in 2 rows in cowplot package in R

I would like to align vertical plot from row 1 and plot from row 2. It didn't matter how hard I try, but it did not let me align.

在此处输入图像描述

Any ideas?


library(dplyr)
library(forcats)
library(ggplot2)
library(cowplot)

city_mpg <- mpg %>%
  mutate(class = fct_lump(class, 4, other_level = "other")) %>%
  group_by(class) %>%
  summarize(
    mean_mpg = mean(cty),
    count = n()
  ) %>% mutate(
    class = fct_reorder(class, count)
  )

p1 <- ggplot(city_mpg, aes(class, count)) + 
  geom_col() + 
  ylim(0, 65) + 
  coord_flip()

p2 <- ggplot(city_mpg, aes(mean_mpg, count)) + 
  geom_point()

p3 <- ggplot(mtcars, aes(wt, mpg)) +
  geom_point()

first <- plot_grid(p1, p2, align = 'h', axis = 'l',rel_widths = c(2,1))
second <- plot_grid(p3)
plot_grid(first, second,ncol = 1, align = 'v', axis = 'l',rel_heights = c(2,1))

The terminology here in terms of ggplot would be that the plots align just fine - it's the panels that do not align. The "panel" represents the area between the x and y axes, and the "plot" is considered the entire area taken up by the panel + the axis ticks, axis text, and axis titles.

Why is this important? Well, plot_grid() aligns all plots , but not the panels . Since p1 has longer y axis text than the y axis text of p3 , the area to the left of the panel in p1 is also wider. When you align the left side of p1 and p3 , it means the panel of p3 is to the left of p1 .

The simple fix for this is to just add a bit of a margin to p3 . By using theme(plot.margin) , we can add some room to the left of p3 so that the area to the left of the panel in p3 is roughly similar to that in p1 . The unfortunate thing is that it's not really very straightforward to do this in any other way than trial and error. You have to add some margin and plot again to see if it was too much or too little. In the end, the result works though. Similarly, I added some margin to the right side of p3 to get the right part of that panel aligned with the right side of the p2 panel.

To fix, the code for p3 now looks like this:

p3 <- ggplot(mtcars, aes(wt, mpg)) +
  geom_point() +
  theme(plot.margin = margin(l=44, t=0, b=0, r=6, 'pt'))

在此处输入图像描述

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM