Home > Back-end >  Get all the legends on the top of the plot
Get all the legends on the top of the plot

Time:01-25

enter image description hereI have a multiple plot within a plot, generated by ggpubr::ggarrange(). However the legends only appears for the first plot i.e., A and B. I wanted to get the legends for rest of the colours, C, D, E on the top. Setting common.legend = TRUE only gives the first two legends.

Thanks for the help!

library(ggpubr)

arranged_plot <- ggarrange(
  plot_list[[1]]   rremove("ylab")   rremove("xlab")   rremove("x.text"),
  plot_list[[2]]   rremove("ylab")   rremove("xlab")   rremove("axis.text"),
  plot_list[[3]]   rremove("ylab")   rremove("xlab"),
  plot_list[[4]]   rremove("ylab")   rremove("xlab")   rremove("y.text"),
  labels = NULL, ncol = 2, nrow = 2,align = "hv", 
  font.label = list(size = 10, color = "black", face = "bold", family = NULL, position = "top"),
  common.legend=TRUE)

CodePudding user response:

I'm not sure how to do this with ggarrange, but if you're willing to look at other methods, here are two options:

  1. Using patchwork (and ggplot2 with patchwork

  2. Facets.

    # sample data, starting with `mtdat1` from above
    mtdat2 <- do.call(rbind, args = mtdat1)
    ggplot(mtdat2, aes(mpg, disp, color = cyl))  
      facet_wrap(~ CY)  
      geom_point()  
      scale_color_manual(values = setNames(c("gray", "red", "blue"), c(4, 6, 8)), drop = FALSE)  
      theme(legend.position = "top")
    

    ggplot2 with facets

    If you prefer to not have the facet strips, we can remove those in a theme:

    ggplot(mtdat2, aes(mpg, disp, color = cyl))  
      facet_wrap(~ CY)  
      geom_point()  
      scale_color_manual(values = setNames(c("gray", "red", "blue"), c(4, 6, 8)), drop = FALSE)  
      theme(legend.position = "top", strip.text.x = element_blank())
    

    ggplot2 with facets, no strips

    I think there are two advantages to facets:

    1. Simpler code, more efficient, allowing ggplot to handle everything in one step.
    2. Since we don't explicitly free the scales (e.g., not doing scales="free"), the axes are all on the same scale, no need to explicitly control them. For comparisons as in your graph, this can be a big difference in visualizing the differences between levels. (Compare this plot with the first plot using patchwork, though those axis limits can easily be fixed as well.)
  • Related