为一组点线图和垂直线图提供单独的图例 [英] Have separate legends for a set of point-line plots, and a vertical line plot
问题描述
示例数据框(如果有更好/更惯用的方法,请告诉我):
Example data frame (if there's a better/more idiomatic way to do this, let me know):
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
位置添加一条垂直曲线,并为两者获取可读的图例.我尝试了以下方法:
I want to plot create point-line plots for the data in df
, add a vertical curve at the x
location indicated by xd
, and get readable legends for both. I tried the following:
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
不完全是我的想法,垂直线没有传说.
Not quite what I had in mind, there's no legend for the vertical line.
一个小的修改(我不明白为什么 geom_vline
是少数具有 show.legend
参数的几何之一,而且默认为 FALSE
!):
A small modification (I don't understand why geom_vline
is one of the few geometries with a show.legend
parameter, which moreover defaults to 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
,并且只包含垂直线.我怎样才能做到这一点?
At least now the vertical bar is showing in the legend, but I don't want it to go in the same "category" (?) as group
. I would like another legend entry, titled Design
, and containing only the vertical line. How can I achieve this?
推荐答案
一种可能的方法是添加一个额外的虚拟美学,如 fill =
,我们随后将使用它来创建第二个图例与 scale_fill_manual()
结合:
A possible approach is to add an extra dummy aesthetic like fill =
, which we'll subsequently use to create the second legend in combination with 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"))))
这篇关于为一组点线图和垂直线图提供单独的图例的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!