【问题标题】:Control over legends of multiple layer plot in ggplot2控制ggplot2中多层图的图例
【发布时间】:2013-11-23 12:53:11
【问题描述】:

我的问题与R: Custom Legend for Multiple Layer ggplotFormat 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)

结果如下:

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

我找不到针对我的情况采用引用问题的方法的方法。有什么想法吗?

【问题讨论】:

  • 你可以看看this post and comments therein,例如“ggplot2 的设计不允许多个图例用于相同的美学”。因此,解决方案很可能是 hack-ish。

标签: r plot ggplot2


【解决方案1】:

以下是一个 hack。它从临时图中提取图例,然后使用 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))

您需要多花点时间才能获得预期输出中的理由。

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2013-05-28
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2016-10-20
    • 1970-01-01
    相关资源
    最近更新 更多