【发布时间】:2016-01-15 15:30:05
【问题描述】:
我想要两个情节的组合情节 + 他们的传说是这样的:
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)))
但是我不想猜测图和图例的宽度(并指定ncol),而是从p1 和p2as shown here 中提取它。
所以我希望我需要这样的东西(来自链接的改编代码):
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)
但这不是将两个图排成一行,而是一列:
这个问题与to this one here 相似,但不同之处在于我也要求调整宽度。我正在使用从那个问题 + 答案和 github 中提取的代码。
【问题讨论】: