Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

ggplot2: multiple plots in a single row with a single legend

I want a combined plot of two plots + their legend like this:

library(ggplot2) 
library(grid)
library(gridExtra)
dsamp <- diamonds[sample(nrow(diamonds), 1000), ]    
p1 <- qplot(price, carat, data=dsamp, colour=clarity)
p2 <- qplot(price, depth, data=dsamp, colour=clarity)
g <- ggplotGrob(p1 + theme(legend.position="bottom"))$grobs
legend <- g[[which(sapply(g, function(x) x$name) == "guide-box")]]
grid.arrange(arrangeGrob(p1+theme(legend.position="right"),p2+theme(legend.position="none"),legend,ncol=3,widths=c(3/7,3/7,1/7)))

expected output

However I do not want to guess the width of the plots and legends (and specify ncol) but have it extracted from p1 and p2 as shown here.

So I expect I would need something like this (adapted code from the link):

grid_arrange_shared_legend_row <- function(...) {
  plots <- list(...)
  g <- ggplotGrob(plots[[1]] + theme(legend.position="right"))$grobs
  legend <- g[[which(sapply(g, function(x) x$name) == "guide-box")]]
  lwidth <- sum(legend$width)
  grid.arrange(
    do.call(arrangeGrob, lapply(plots, function(x)
      x + theme(legend.position="none"))),
    legend,
    ncol = length(plots)+1,
    widths = unit.c(rep(unit(1, "npc") - lwidth, length(plots)), lwidth))
}
grid_arrange_shared_legend_row(p1, p2)

but this is not arranging the two plots in one row but rather one column:

not what I want

This question is similar to this one here but different in that I am asking for the adapted widths as well. I am using code extracts both from that question + answer and the github.

like image 959
mts Avatar asked Jan 15 '16 15:01

mts


People also ask

How do I plot two Ggplots together?

Combine multiple ggplot on one page.Use the function ggarrange() [ggpubr package], a wrapper around the function plot_grid() [cowplot package]. Compared to plot_grid(), ggarange() can arrange multiple ggplots over multiple pages.

What does GG in ggplot mean?

ggplot2 [library(ggplot2)] ) is a plotting library for R developed by Hadley Wickham, based on Leland Wilkinson's landmark book The Grammar of Graphics ["gg" stands for Grammar of Graphics]. Some documentation can be found on the ggplot website .

Does par work with ggplot?

One disadvantage for par() is that it cannot work for ggplot, we can see below that the plot should appear on the upper left of the page, but it just happen as if par() isn't written here.


1 Answers

Why don't you use facetting?

library(reshape2)
dmelt <- melt(dsamp, id.vars = c("price", "clarity"), measure.vars = c("carat", "depth"))
ggplot(dmelt, aes(x = price, y = value, color = clarity)) +
  geom_point() +
  facet_wrap(~ variable, scales = "free")

resulting plot

like image 82
Roland Avatar answered Oct 23 '22 02:10

Roland