I 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:
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")
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())
I think there are two advantages to facets:
- Simpler code, more efficient, allowing ggplot to handle everything in one step.
- 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 usingpatchwork
, though those axis limits can easily be fixed as well.)