編輯 - 包括以下R'ggplot2'用多個(網格化)繪圖對象排列常見和獨特的圖例。
我已經使用this function與GGPLOT2包再現的例子Add a common Legend for combined ggplots其中工程perfecty當每個小區僅具有1型傳說例如爲...,color =, ...
。
不過,我想安排其共用一個傳說多條曲線,但每個人都有一個額外的獨特傳奇如:
ggplot(df1, aes(x=Site, y=RESULT, color=Position , shape=DETNAME)) +
geom_point(size=5) + ylab ("concentration (mg/L)") +
labs (shape = "Determinand")
主要生產:
我有3倍以下位置圖例是共享的,但決定和圖例是唯一的。
所以我想知道是否有一個額外的參數,我可以傳遞給grid_arrange_shared_legend()
將保留Determinand傳說(shape = DETNAME
),即繪製它們使用類似legend.position = "top"
網格中的每個情節之上,但具有位置共同的圖例( color = position
)?
我知道我可以添加+ guides(shape = FALSE)
到每個情節對象,然後使用grid_arrange_shared_legend()
使我有共同立場的傳說,但我想實現這樣的事情,但有獨特Determinand傳說每個情節:
或者任何人都可以建議grid_arrange_shared_legend()
函數的源代碼的哪一部分需要編輯來執行此操作?
編輯 - 可重複的例子
library (ggplot2)
library(gridExtra)
library (grid)
# two ggplot plot objects with multiple legends 1 common legend and 2 unique
p1<- ggplot(diamonds, aes(x=price, y= depth, color= clarity , shape= cut)) +
geom_point(size=5) + labs (shape = "unique legend", color = "common legend")
p2 <- ggplot(diamonds, aes(x=price, y= depth, color= clarity , shape= color)) +
geom_point(size=5) + labs (shape = "unique legend", color = "common legend")
# shared legend function
grid_arrange_shared_legend <- function(..., ncol = length(list(...)), nrow = 1, position = c("bottom", "right")) {
plots <- list(...)
position <- match.arg(position)
g <- ggplotGrob(plots[[1]] + theme(legend.position = position))$grobs
legend <- g[[which(sapply(g, function(x) x$name) == "guide-box")]]
lheight <- sum(legend$height)
lwidth <- sum(legend$width)
gl <- lapply(plots, function(x) x + theme(legend.position="none"))
gl <- c(gl, ncol = ncol, nrow = nrow)
combined <- switch(position,
"bottom" = arrangeGrob(do.call(arrangeGrob, gl),
legend,
ncol = 1,
heights = unit.c(unit(1, "npc") - lheight, lheight)),
"right" = arrangeGrob(do.call(arrangeGrob, gl),
legend,
ncol = 2,
widths = unit.c(unit(1, "npc") - lwidth, lwidth)))
grid.newpage()
grid.draw(combined)
# return gtable invisibly
invisible(combined)
}
grid_arrange_shared_legend (p1,p2)
這裏使用grid_arrange_shared_legend()
功能是指獨特的傳說只能對電網
問題的曲線圖的一個是正確的如何保留(提取?)獨特的圖例並將它們繪製在網格上的每個圖上方,但保留常見的圖例底部?