【问题标题】:ggplot: two distinct legends on shape aestheticsggplot:关于形状美学的两个截然不同的传说
【发布时间】:2014-07-21 19:22:52
【问题描述】:

如何在 ggplot 中为形状美学添加第二个图例?

图表显示不同的开始类型(形状)、不同的过程(颜色)和不同的 结束类型(再次塑造)。目前,我只能显示两个图例:一个用于颜色,一个用于形状(合并 start.type 和 end.tpye)。关于如何获得单独的第三个图例(用于 end.type)的任何帮助?引入线型作为额外的美学不是一种选择。非常感谢。

id <- c("1","2","3")
start.date <- c("01/01/2010","05/05/2004","01/08/2006")
end.date <- c("31/12/2012","05/05/2007","01/09/2009")
start.type <- c("x1","x2","x3")
end.type <- c("y1","y2","y3")
process.type <- c("p1","p2","p3")
u <- data.frame(id,start.date, end.date,start.type,end.type,process.type)

u.plot <- ggplot(u)+
  geom_segment(aes(color=process.type, x=start.date, xend=end.date, y=id, yend=id), size=1)+
  geom_point(aes(shape=start.type, x=start.date, y=id), size=3)+
  geom_point(aes(shape=end.type, x=end.date, y=id), size=3)

plot(u.plot)

【问题讨论】:

  • 标准 ggplot 只允许每个美学一个图例。如果你愿意,你将不得不大量破解它。那是你想做的事情吗?事后在图形程序中编辑它以分割图例的一部分可能会更容易。这取决于这对你有多重要。
  • 我已经担心会是这种情况。对此没有标准方法感到非常惊讶。问题是这个(类似的)代码在许多数据帧上循环运行。不过还是谢谢。

标签: r ggplot2 legend gantt-chart


【解决方案1】:

编辑图例可能会很痛苦并且很容易被破坏,但如果你必须尝试这里是一种快速而肮脏的方法

require(gtable)
g = ggplotGrob(u.plot) # calls ggplot_build and ggplot_gtable
a = g$grobs[[8]][["grobs"]][[2]] # extract the legend (a gtable itself)
a = gtable_add_rows(a, unit(c(0.5,1),"line"), 6) # add two rows
new = editGrob(a[["grobs"]][[2]], label = "I'm in") # copy legend title with new text

a = gtable_add_grobs(a, new, 8, l=2, r=5) # place the new title
g$grobs[[8]][["grobs"]][[2]] = a # replace with new legend in the plot
grid.newpage()
grid.draw(g)

【讨论】:

  • 非常感谢。这看起来已经很有希望了。如果你有第二个,你介意简要评论一下单独的步骤吗?我不确定我是否完全理解它们。 ggplotGrob 的帮助似乎非常有限(除非我错过了某事)。原则上,在处理方面时,这种方法是否也适用 - 需要修改?
  • gtable 包提供了一些相关功能的文档;还有一个介绍性的wiki page
  • 我认为更可靠的策略是制作两个版本的情节,每个版本都有一个特定的(修剪下来的)形状图例,提取与其中一个图例对应的 gtable 并将其与另一个合并(rbind)。
  • a = gtable_add_grobs(a, new, 8, l=2, r=5) # 放置新标题;难道最后应该是gtable_add_grob(不带s)?
  • 可能吧,我一直觉得应该是复数,所以我在fork上就这么写了。
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2020-12-31
  • 2021-06-09
相关资源
最近更新 更多