Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Plotting a vertical line in R if a condition is met

Tags:

r

ggplot2

I'm trying to plot vertical lines if a condition is met.

Example dataframe:

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)

where X in the intercept is the value of X when the indicator value is 1. So in this case, I would only want the vertical lines for when the indicator value is 1. In this example, that would create a vertical line at X=1 and X=3. Does anyone have any ideas on how to tackle this? Thanks!

like image 672
JayBee Avatar asked Dec 18 '22 21:12

JayBee


2 Answers

The following should do what you want

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))

Here is the resulting image.

enter image description here

Note: In the example above, the data.frame named example was used in the call to geom_vline, but this can be any other data.frame that contains the desired values to use as an intercept.

like image 193
steveb Avatar answered Jan 06 '23 00:01

steveb


Minor tweak from above:

example %>% ggplot(aes(x=X,y=Y)) + geom_line() + 
  geom_vline(aes(xintercept=X), data=. %>% filter(indicator == 1))

data can also be a function, so you don't need to hard code example in the geom_vline layer. Since you are using dplyr anyway, it's easy to convert a pipe to a function by starting the pipeline with a dot.

like image 27
Neal Fultz Avatar answered Jan 06 '23 01:01

Neal Fultz