我想要两个地块及其图例的组合图,如下所示:
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
和p2
as 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提取的代码。
最佳答案
你为什么不使用刻面?
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")
关于r - ggplot2:具有单个图例的单行中有多个图,我们在Stack Overflow上找到一个类似的问题:https://stackoverflow.com/questions/34814478/