1

I'm trying yo aling vertically two plots with cowplot but I can't and I don't know why:

Code:

manufac_count <-  mpg %>%
  count(manufacturer) %>% 
  mutate(ymax = cumsum(n),
         ymin = lag(ymax, n = 1, default = 0))

model_count <- mpg %>%
  group_by(manufacturer) %>%
  count(model) %>%
  ungroup() %>% 
  mutate(ymax = cumsum(n),
         ymin = lag(ymax, n = 1, default = 0))

p1 <- ggplot(manufac_count) +
  geom_rect(aes(xmin = 2,
                xmax = 3,
                ymin = ymin,
                ymax = ymax,
                fill = manufacturer),
            color = 'white') +
  geom_rect(data = model_count,
            aes(xmin = 3,
                xmax = 4,
                ymin = ymin,
                ymax = ymax,
                fill = model),
            color = 'white',
            show.legend = FALSE) +
  xlim(0 , 4) +
  coord_polar(theta = 'y' ) +
  theme(legend.position = 'none')

p2 <- ggplot(data = mpg,
      mapping =  aes(x = hwy)) +
  geom_histogram(
    binwidth = 3)

plot_grid(p1, p2, align = 'v', nrow = 2, ncol = 1)

Plot

Question

How can I align the two plots vertically using cowplot or another library in R? or maybe I should convert the graphics to some other class?

  • 2
    Try the `patchwork` package. After creating the individual plots and loading patchwork, run `p1 / p2`. If you want the widths to be similar to your example, you can do `{p1 + plot_spacer()} / p2`. – eipi10 Jul 27 '21 at 17:23
  • 1
    Another part of this issue might be that the aspect ratio of your polar coordinate plot is 1:1 by definition, but the histogram can be anything. You may need to fix the aspect ratio (using `coord_fixed()`) of the histogram to allow the margins to align. – phalteman Jul 27 '21 at 20:48

0 Answers0