Daniel Valencia C.
Daniel Valencia C.

Reputation: 2279

How to minimize the white space created by the guide_area() function of the patchwork package in plots made with ggplot2?

I made 3 plots with the ggplot2 package. To arrange the plots in a single figure I used the patchwork package. In the arrangement, I put 2 plots at the top, the common legend below these plots and below the common legend the third plot. I created the common legend space with the guide_area() function, but a big unused blank area is created along with it.

How can I keep this unused blank space to a minimum?

library(ggplot2)
library(patchwork)

p1 <- ggplot(data = mpg,
             aes(x = fl,
                 y = displ)) +
  geom_col(aes(fill = cty))

p2 <- ggplot(data = mpg,
             aes(x = year,
                 y = hwy)) +
  geom_point(aes(color = drv))

p3 <- ggplot(data = mpg,
             aes(x = class,
                 y = displ)) +
  geom_col() +
  facet_grid(~year)

((p1+p2)/guide_area()/p3) +
  plot_layout(guides = "collect") &
  theme(legend.position = "bottom")

White space remains in different sizes and proportions of the figure (the white space is marked with red).

enter image description here

Upvotes: 10

Views: 1512

Answers (1)

Kra.P
Kra.P

Reputation: 15123

Use heights = ... inside plot_layout.

For example,

((p1+p2)/guide_area()/p3) +
  plot_layout(guides = "collect", heights = c(3,1,3)) &
  theme(legend.position = "bottom")

enter image description here

Upvotes: 6

Related Questions