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!
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.
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.
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With