如果满足条件,则在R中绘制垂直线

Jay*_*Bee 2 r ggplot2

如果条件满足,我试图绘制垂直线.

示例数据帧:

require(ggplot2)
require(dplyr)

example <- data.frame(
  X = c (1:5), 
  Y = c(8,15,3,1,4),
  indicator = c(1,0,1,0,0) 
)

example %>% ggplot(aes(x=X,y=Y)) + geom_line() + geom_vline(xintercept=X)
Run Code Online (Sandbox Code Playgroud)

当指标值为1时,截距中的X是X的值.所以在这种情况下,我只想要指标值为1时的垂直线.在这个例子中,这将在X =处创建一条垂直线1和X = 3.有没有人对如何解决这个问题有任何想法?谢谢!

ste*_*veb 6

以下应该做你想要的

library(ggplot2)
library(dplyr)

example <- data.frame(
  X = c (1:5), 
  Y = c(8,15,3,1,4),
  indicator = c(1,0,1,0,0) 
)

example %>%
    ggplot(aes(x=X,y=Y)) +
    geom_line() +
    geom_vline(aes(xintercept = X),
               data = example %>% filter(indicator == 1))
Run Code Online (Sandbox Code Playgroud)

这是生成的图像.

在此输入图像描述

注意:在上面的示例中,在调用中使用了data.framenamed ,但这可以是包含要用作拦截的所需值的任何其他名称.examplegeom_vlinedata.frame