Suppose I have data like these:
n <- 100
set.seed(123)
df <- data.frame(
num1 = rnorm(n),
num2 = sample(1:4, n, replace = TRUE),
char = sample(c("Green", "Red", "Blue"), n, replace = TRUE),
fac = factor(sample(c("Green", "Red", "Blue"), n, replace = TRUE)),
logical = sample(c(TRUE, FALSE), n, replace = TRUE),
stringsAsFactors = FALSE
)
I'd like to generate a ggplot with facets and reference lines so that the reference lines are plotted in the appropriate facet. For instance:
## Base plot
ggplot(df, aes(num2, num1)) +
geom_jitter() +
facet_grid(~ char)
Now I'd like to add vertical lines whenever logical == TRUE
.
Something like:
## Does not work
ggplot(df, aes(num2, num1)) +
geom_jitter() +
facet_grid(~ char) +
geom_vline(xintercept = num2)
You need to map your xintercept value inside of aes()
, to tell ggplot to look inside of data
for it. And subset the data for just that layer, based on your conditional.
ggplot(df, aes(num2, num1)) +
geom_jitter() +
facet_grid(~ char) +
geom_vline(data = df[df$logical == TRUE,], aes(xintercept = num2))