Search code examples
ggplot2graph

ggarange: graphs with different size legend


I am trying to group three different graphs using ggarrange. The graphs are exactly the same, but the legend on the bottom graph is too long. Therefore, I am getting the following figure:

enter image description here

I tried to include to theme(legend.box = "horizontal") in the graph code and use the following for the ggarrange:

ggarrange(plot_sex, plot_ethnicity, plot_disability + 
          rremove("x.text"), 
          labels =  c("A", "B", "C"),
          ncol = 1, nrow = 3,
          legend = "right",
          widths = c(1, 1, 5),
          align = "v")

I want the graphs on the right to be aligned. Can someone help me?

Thank you!


Solution

  • Here is a patchwork solution.

    library(tidyverse)
    library(patchwork)
    
    # Create plots individually
    p1 <- mpg %>%
      ggplot(aes(x = cty, y = hwy, color = manufacturer)) +
      geom_point() +
      theme_bw() +
      labs(x = NULL) +
      theme(axis.text.y = element_blank(),
            legend.position = 'none')
    
    p2 <- mpg %>%
      ggplot(aes(x = cty, y = hwy, color = manufacturer)) +
      geom_point() +
      labs(x = NULL,
           y = NULL) +
      theme_bw() +
      theme(axis.text.x = element_blank(),
            axis.text.y = element_blank(),
            legend.justification = 'left') +  # To left align the top legend
      guides(color = guide_legend(ncol = 2))
    
    p3 <- mpg %>%
      ggplot(aes(x = cty, y = hwy, color = model)) +
      geom_point() +
      theme_bw() +
      theme(legend.position = 'none')
    
    p4 <- mpg %>%
      ggplot(aes(x = cty, y = hwy, color = model)) +
      geom_point() +
      labs(y = NULL) +
      theme_bw() +
      theme(axis.text.y = element_blank()) +
      guides(color = guide_legend(ncol = 3))
    
    # Stitch the individual plots together (will look better on your local machine)
    p1 + p2 + p3 + p4 + plot_layout(ncol = 2)
    

    Created on 2024-06-27 with reprex v2.1.0