Search code examples
rggplot2facet

Error occurs when changing facet labels in facet_grid and add geom_vline at the same time


I am trying to change the facet labels without revising the data frame, and add a vertical line to the plot to enhance understandability.

library(ggplot2)
df <- data.frame(weeks = rep(-3:3, each = 2),
                 is_manual = rep(c(TRUE, FALSE), times = 7),
                 value = c(rnorm(7, 10), rnorm(7, 20)))

# Plotting
ggplot(df, aes(x = weeks, y = value)) + geom_line() +
  facet_grid(is_manual ~ .) +
  geom_vline(xintercept = 0, color = "blue", linetype = 2)

gives me this, which works fine:

plot1.png

Now I'd like to change the facet labels so that everyone knows what TRUE and FALSE are.

ggplot(df, aes(x = weeks, y = value)) + geom_line() +
  facet_grid(ifelse(is_manual, "Manual", "Uploaded") ~ .) +
  geom_vline(xintercept = 0, color = "blue", linetype = 2)

, but it returns an error:

Error in ifelse(is_manual, "Manual", "Uploaded"): object 'is_manual' not found

However, once I remove the geom_vline part, it works as normal, which means 'is_manual' should be able to be found.

ggplot(df, aes(x = weeks, y = value)) + geom_line() +
  facet_grid(ifelse(is_manual, "Manual", "Uploaded") ~ .)

plot2.png

I can work around by doing

df$is_manual <- ifelse(df$is_manual, "Manual", "Uploaded")
ggplot(df, aes(x = weeks, y = value)) + geom_line() +
  facet_grid(is_manual ~ .) +
  geom_vline(xintercept = 0, color = "blue", linetype = 2)

, but it changes my underlying data.

Is there a way that I can change the facet labels and add the vertical line at the same time while not changing the data frame contents? Or is this a bug which needs reporting?


Solution

  • Just guessing here, but maybe geom_vline is getting the facet label names from the original data frame df passed to ggplot, rather than from the updated formula used in facet_grid, causing an error when geom_vline can't figure out where the facets are.

    In any case, instead of changing your underlying data, you can update it on the fly using the dplyr pipe (%>%) and avoid the error:

    library(tidyverse) 
    
    ggplot(df %>% mutate(is_manual = ifelse(is_manual, "Manual", "Uploaded"),
           aes(x = weeks, y = value)) + geom_line() +
      facet_grid(is_manual ~ .) +
      geom_vline(xintercept = 0, color = "blue", linetype = 2)