我有一个ggplot2对象,我试图为一些vlines添加一个图例。我遵循了以下内容:(ggplot2: manually add a legend)但是我无法得到我想要的输出。任何建议都是非常感谢的。
在那里我得到了:

我想要的输出是将手动图例直接放在物种图例的上方(或下方)
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") 但正如你所看到的,它没有添加破折号,而是将它与另一种线型结合在一起……

发布于 2020-04-19 08:24:39
实现所需输出的一种可能的解决方案是使用ggnewscale包中的new_scale_color函数为垂直线设置新的颜色图例。
在我的解决方案中,我还用geom_vline替换了geom_linerange,只需指定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 = "")

这是你要找的东西吗?
https://stackoverflow.com/questions/61297054
复制相似问题