R 将vline添加到现有绘图,并将其显示在ggplot2图例中?

R 将vline添加到现有绘图,并将其显示在ggplot2图例中?,r,ggplot2,R,Ggplot2,我有一些数据可以用来绘制直方图。我还有两组具有一定意义的阈值 我能够用适当的样式绘制直方图和V线。然而,我无法让我的虚拟线路出现在传奇中。我相信类似的东西应该会起作用,但是图例项目永远不会显示 df <- data.frame(val=rnorm(300, 75, 10)) cuts1 <- c(43, 70, 90) cuts2 <- c(46, 79, 86) ggplot(data=df, aes(x=val)) + geom_histogram() + ge

我有一些数据可以用来绘制直方图。我还有两组具有一定意义的阈值

我能够用适当的样式绘制直方图和V线。然而,我无法让我的虚拟线路出现在传奇中。我相信类似的东西应该会起作用,但是图例项目永远不会显示

df <- data.frame(val=rnorm(300, 75, 10))

cuts1 <- c(43, 70, 90)
cuts2 <- c(46, 79, 86)

ggplot(data=df, aes(x=val)) +
  geom_histogram() +
  geom_vline(xintercept=cuts1,
             linetype=1,
             color="red",
             labels="Thresholds A",
             show_guide=TRUE) +
  geom_vline(xintercept=cuts2,
             linetype=2,
             color="green",
             labels="Thresholds B",
             show_guide=TRUE)

df诀窍是将所有阈值数据放在同一数据帧中,然后映射美学,而不是设置它们:

cuts <- rbind(cuts1,cuts2)

ggplot(data=df, aes(x=val)) +
  geom_histogram() +
  geom_vline(data=cuts, 
             aes(xintercept=vals, 
                 linetype=Thresholds,
                 colour = Thresholds),
             show_guide = TRUE)

谢谢你的发帖。我试着使用上面的代码,但数字不正确。只有第一个图形部分有效,但几何图形部分无效。我想知道是否还有其他的把戏?我所做的:y
cuts <- rbind(cuts1,cuts2)

ggplot(data=df, aes(x=val)) +
  geom_histogram() +
  geom_vline(data=cuts, 
             aes(xintercept=vals, 
                 linetype=Thresholds,
                 colour = Thresholds),
             show_guide = TRUE)