r - 控制ggplot2中多层图的图例

标签 r plot ggplot2

我的问题与R: Custom Legend for Multiple Layer ggplot密切相关,然后到 Format legend for multiple layers ggplot2即:我想为多层图创建自定义图例。但是,有一个微妙的区别:
在原题中,想要的效果是从两种不同的分组方式中分离出来:fillcolor这就是为什么可以使用两个不同的 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)

结果如下:

before

我想要的是将点和线的图例分开,使图例看起来像这样:

after

我找不到一种方法来采用所引用问题的方法来处理我的情况。有任何想法吗?

最佳答案

以下是一个黑客。它从临时图中提取图例,然后使用 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))
enter image description here
您需要多花些功夫才能获得预期输出中的理由。

关于r - 控制ggplot2中多层图的图例,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/19911134/

相关文章:

从手稿复制 ODE 食物网模型

r - ggplot : Add different lines in each facet of geom_bar

r - `level` 如何用于在 geom_smooth 中生成置信区间?

r - colClasses 日期和时间 read.csv

r - 使用 R 中的 data.table 创建一个新列,其中每行包含多个列的总和

R函数用阴影绘制不等式

r - 绘制 xts 对象 - 为 lwd 和 col 参数传递值创建错误

graphics - 查找绘图的最终显示区域中的框架/轴的坐标

r - 在 R 中绘制按年折叠的唯一值

r - 如何在ggplot2中将geom_vline()和geom_hline()图例与其他图例分开