rggplot2facet-wrapgghighlight

gghighlight not working with ggplot faceting


I'm using ggplot and gghighlight. I have a dataframe with 2 continuous variables and 2 factors, and I wish to create a facetted plot and then highlight certain variable ranges using gghighlight.

library(ggplot2)
library(gghighlight)

n = 50
x = runif(n)
slope = sample(c(2,4), n, replace = TRUE)
intercept = sample(c(0, 0.5), n, replace = TRUE)
y <- slope * x + intercept

df <- data.frame(x = x, y = y, slope = slope, intercept = intercept)
df$slope <- as.factor(df$slope) 
df$intercept <- as.factor(df$intercept)

When I create the first example plot below, the highlighting works but the problem is that I can't see the unhighlighted variables that I want to be in dark grey

ggplot(df, aes(x, y)) +
  gghighlight(y < 1.5, unhighlighted_params = list(colour = "darkgrey")) +
  geom_line(aes(group = interaction(slope, intercept), colour = slope)) +
  geom_point(aes(shape = intercept, colour = slope)) +
  facet_wrap(~ slope)

When I move the gghighlight line down

ggplot(df, aes(x, y)) +
  geom_line(aes(group = interaction(slope, intercept), colour = slope)) +
  geom_point(aes(shape = intercept, colour = slope)) +
  gghighlight(y < 1.5, unhighlighted_params = list(colour = "darkgrey")) +
  facet_wrap(~ slope)

the unhighlighted data shows up in dark grey but up I am also getting all the data shown in each facet. Any advice would be much appreciated.


Solution

  • Using the option calculate_per_facet = TRUE:

    (The default is FALSE because a common use case is to use each facet to highlight all the data in a specific group against the unhighlighted backdrop of the data for all other groups.)

    library(ggplot2)
    library(gghighlight)
    
    n = 50
    x = runif(n)
    slope = sample(c(2,4), n, replace = TRUE)
    intercept = sample(c(0, 0.5), n, replace = TRUE)
    y <- slope * x + intercept
    
    df <- data.frame(x = x, y = y, slope = slope, intercept = intercept)
    df$slope <- as.factor(df$slope) 
    df$intercept <- as.factor(df$intercept)
    
    ggplot(df, aes(x, y)) +
      geom_line(aes(group = interaction(slope, intercept), colour = slope)) +
      geom_point(aes(shape = intercept, colour = slope)) +
      gghighlight(y < 1.5, unhighlighted_params = list(colour = "darkgrey"), 
                  calculate_per_facet = TRUE
                  ) +
      facet_wrap(~ slope)
    

    Created on 2024-05-04 with reprex v2.1.0