Search code examples
rggplot2facet

ggplot with facets and geom_abline


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)

enter image description here

Now I'd like to add vertical lines whenever logical == TRUE.

enter image description here

Something like:

## Does not work
ggplot(df, aes(num2, num1)) + 
geom_jitter() + 
facet_grid(~ char) +
geom_vline(xintercept = num2)

Solution

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

    enter image description here