示例数据框(如果有更好/更惯用的方法,请告诉我):
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
中的数据绘制创建点线图,在xd
指示的x
位置添加一条垂直曲线,并获得两者的可读图例。我尝试了以下方法:
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
至少现在竖线显示在图例中,但我不希望它与 group
属于同一“类别”(?)。我想要另一个图例条目,标题为 Design
,并且只包含垂直线。我怎样才能做到这一点?
最佳答案
一种可能的方法是添加一个额外的虚拟美学,如 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"))))
关于r - 有一组点线图和垂直线图的单独图例,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/38588925/