我有一个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,color = "black")
L1 = linesGrob(x = unit(c(.5,.5),"npc"),y = unit(c(.25,.75),gp = gpar(col = "black",lty = "longdash"))
L2 = linesGrob(x = unit(c(.5,gp = gpar(col = "darkblue",lty = "longdash"))
T1 = textGrob("line 1 explaing something",x = 0,just = "left")
T2 = textGrob("line 2 explaing something",just = "left")
leg = gtable(width = unit(c(1,5),"cm"),height = unit(c(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,l=1)
leg = gtable_add_grob(leg,L2,t=3,T1,l=2)
leg = gtable_add_grob(leg,T2,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,nrow = 3) +
geom_linerange(data = vlines,aes(x = x,ymax = y,ymin = 0,color = line),linetype = "dashed") +
geom_linerange(data = vlines,linetype = "dashed")
但是您可以看到它并没有添加破折号,而是将其与其他线型组合在一起...