1

我有一个 ggplot2 对象,我正在尝试为一些 vlines 添加图例。我遵循以下内容:( ggplot2:手动添加图例)但我无法获得我想要的输出。任何建议都非常感谢。

我要去的地方:

在此处输入图像描述

我想要的输出是将手动图例直接放在 Species 图例上方(或下方)

library(ggplot2)  
library(grid)  
library(gtable)
library(dplyr)

plot2 <- iris %>% 
  ggplot() + 
  geom_line(aes(Sepal.Length, Sepal.Width, color = Species)) + 
  facet_wrap(Species ~ ., nrow = 3) +
  geom_vline(xintercept = 6, y = 4.5, linetype = "dashed", color = "darkblue") +
  geom_vline(xintercept = 7, y = 4.5, linetype = "dashed", color = "black") 

L1 = linesGrob(x = unit(c(.5, .5), "npc"), y = unit(c(.25, .75), "npc"),
               gp = gpar(col = "black", lty = "longdash"))
L2 = linesGrob(x = unit(c(.5, .5), "npc"), y = unit(c(.25, .75), "npc"),
               gp = gpar(col = "darkblue", lty = "longdash"))
T1 = textGrob("line 1 explaing something", x = 0, just = "left")
T2 = textGrob("line 2 explaing something", x = 0, just = "left")

leg = gtable(width = unit(c(1,5), "cm"), height = unit(c(1,1,1,1), "cm"))
#leg = gtable_add_grob(leg, rectGrob(gp = gpar(fill = NA, col = "black")), t=2,l=1,b=4,r=2)

leg = gtable_add_grob(leg, L1, t=2, l=1)
leg = gtable_add_grob(leg, L2, t=3, l=1)
leg = gtable_add_grob(leg, T1, t=2, l=2)
leg = gtable_add_grob(leg, T2, t=3, l=2)

g = ggplotGrob(plot2)

pos = g$layout[grepl("panel", g$layout$name), c('t', 'l')]
g = gtable_add_cols(g, sum(leg$widths), pos$l[1])
g = gtable_add_grob(g, leg, t = pos$t[1], l = pos$l[1] + 1)
g = gtable_add_cols(g, unit(6, "pt"), pos$l[1])

# Draw it
grid.newpage()
grid.draw(g)

我也尝试过这种方法:

vlines <- data.frame(line = c("Line 1 Explaining Something", "Line 2 Explaining Something"), 
                     y = c(4.5, 4.5), x = c(6, 7))

ggplot() + 
  geom_line(data = iris, aes(Sepal.Length, Sepal.Width, color = Species)) + 
  facet_wrap(Species ~ ., nrow = 3) +
  geom_linerange(data = vlines, 
                 aes(x = x, 
                     ymax = y,
                     ymin = 0,
                     color = line),
             linetype = "dashed") +
  geom_linerange(data = vlines, 
                 aes(x = x, 
                     ymax = y,
                     ymin = 0,
                     color = line),
             linetype = "dashed") 

但正如你所看到的,它没有添加破折号,而是将它与其他线条类型结合在一起......

在此处输入图像描述

4

1 回答 1

1

实现所需输出的一种可能解决方案是使用包中的new_scale_color函数ggnewscale为垂直线设置新的颜色图例。

在我的解决方案中,我还替换了geom_linerangeby的使用,geom_vline它允许仅通过指定 x 截距值来绘制垂直线。

用你的例子,你可以画出这样的东西:

library(ggnewscale)
library(ggplot2)

ggplot(iris, aes(Sepal.Length, Sepal.Width, color = Species)) + 
  geom_line()+
  facet_wrap(Species ~ ., nrow = 3) +
  new_scale_color()+
  geom_vline(data = vlines, 
             aes(xintercept = x, color = line), linetype = "dashed")+
  scale_color_manual(values = c("blue","black"), name = "")

在此处输入图像描述

是你要找的吗?

于 2020-04-19T00:24:38.637 回答