ggplot2:单个图例中包含单个图例的多个图表

mts*_*mts 9 plot r ggplot2 gridextra

我想要两个情节+他们的传奇的组合情节如下:

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)))
Run Code Online (Sandbox Code Playgroud)

预期产出

但是我不想猜测图和图例的宽度(并指定ncol)但是从中提取p1p2 如此处所示.

所以我希望我需要这样的东西(来自链接的改编代码):

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)
Run Code Online (Sandbox Code Playgroud)

但这并不是将两个图排列成一行而是一列:

不是我想要的

这个问题类似于这个问题,但不同之处在于我也要求改编宽度.我正在使用代码提取来自该问题+答案和github.

Rol*_*and 8

你为什么不使用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")
Run Code Online (Sandbox Code Playgroud)

结果情节