示例数据框(如果有更好/更惯用的方法,请告诉我):
n <- 10
group <- rep(c("A","B","C"),each = n)
x <- rep(seq(0,1,length = n),3)
y <- ifelse(group == "A",1+x,ifelse(group == "B",2+2*x,3+3*x))
df <- data.frame(group,x,y)
xd <- 0.5
des <- data.frame(xd)
我想为df
中的数据绘制创建点线图,在x
指示的xd
位置添加垂直曲线,并获取两者的可读图例。我尝试了以下方法:
p <- ggplot(data = df, aes(x = x, y = y, color = group)) + geom_point() + geom_line(aes(linetype=group))
p <- p + geom_vline(data = des, aes(xintercept = xd), color = "blue")
p
一个小修改(我不明白为什么geom_vline
是具有show.legend
参数的少数几何之一,而且默认为FALSE
!):
p <- ggplot(data = df, aes(x = x, y = y, color = group)) + geom_point() + geom_line(aes(linetype=group))
p <- p + geom_vline(data = des, aes(xintercept = xd), color = "blue", show.legend = TRUE)
p
至少现在垂直条显示在图例中,但我不希望它出现在相同的&#34;类别&#34; (?)为group
。我想要另一个标题为Design
的图例条目,并且只包含垂直线。我怎样才能做到这一点?
答案 0 :(得分:4)
一种可能的方法是添加额外的虚拟审美,例如fill =
,我们随后将其用于与scale_fill_manual()
组合创建第二个图例:
ggplot(data = df, aes(x = x, y = y, color = group)) +
geom_point() +
geom_line(aes(linetype=group), show.legend = TRUE) +
geom_vline(data = des,
aes(xintercept = xd, fill = "Vertical Line"), # add dummy fill
colour = "blue") +
scale_fill_manual(values = 1, "Design", # customize second legend
guide = guide_legend(override.aes = list(colour = c("blue"))))