我的问题与R: Custom Legend for Multiple Layer ggplot密切相关,然后到 Format legend for multiple layers ggplot2即:我想为多层图创建自定义图例。但是,有一个微妙的区别:
在原题中,想要的效果是从两种不同的分组方式中分离出来:fill
和 color
这就是为什么可以使用两个不同的 scale_XXX
职能。就我而言,我创建了一个情节
包含点(一层)和线(第二层)。两层按颜色区分:
x <- seq(0, 10, .1)
y <- sin(x)
lbl <- ifelse(y > 0, 'positive', 'non-positive')
data.one <- data.frame(x=x, y=y, lbl=lbl)
data.two <- data.frame(x=c(0, 10, 0, 10), y=c(-0.5, -0.5, 0.5, 0.5), classification=c('low', 'low', 'high', 'high'))
plt <- ggplot(data.one) + geom_point(aes(x, y, color=lbl)) + scale_color_discrete(name='one', guide='legend')
plt <- plt + geom_line(data=data.two, aes(x, y, color=classification)) + scale_color_discrete(name='two', guide='legend')
print(plt)
结果如下:
我想要的是将点和线的图例分开,使图例看起来像这样:
我找不到一种方法来采用所引用问题的方法来处理我的情况。有任何想法吗?
最佳答案
以下是一个黑客。它从临时图中提取图例,然后使用 grid.arrange
组合所有内容。 .
g_legend<-function(a.gplot){
tmp <- ggplot_gtable(ggplot_build(a.gplot))
leg <- which(sapply(tmp$grobs, function(x) x$name) == "guide-box")
legend <- tmp$grobs[[leg]]
return(legend)}
n <- 4; cols <- hcl(h=seq(15, 375-360/n, length=n)%%360, c=100, l=65)
cols1 <- cols[4:3]
names(cols1) <- c("positive", "non-positive")
plt_1 <- ggplot(data.one) +
geom_point(data=data.one,aes(x, y, color=lbl)) +
scale_color_manual(values=cols1)
cols2 <- cols[1:2]
names(cols2) <- c("high", "low")
plt_2 <- ggplot(data.one) +
geom_line(data=data.two, aes(x, y, color=classification)) +
scale_color_manual(values=cols2)
mylegend_1<-g_legend(plt_1)
mylegend_2<-g_legend(plt_2)
plt <- ggplot(data.one) +
geom_point(data=data.one,aes(x, y, color=lbl)) +
geom_line(data=data.two, aes(x, y, color=classification)) +
scale_color_discrete(guide="none")
library(gridExtra)
grid.arrange(plt,
arrangeGrob(mylegend_1, mylegend_2, nrow=6),
ncol=2,widths=c(7,1))
您需要多花些功夫才能获得预期输出中的理由。
关于r - 控制ggplot2中多层图的图例,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/19911134/