rggplot2facet-wrapgghighlight

gghighlight and facet_wrap one always highlighted


First time poster, so I'm sorry if I made any mistakes!

I'm trying to make a small multiples plot in ggplot2 in R, using the gghighlight package. I have the temperature over time in multiple locations, and the temperature of the surroundings. My goal is to have 1 location highlighted in each plot (and all other locations in the background), but also to have the temperature of the surroundings highlighted in each plot. Does anyone know how to do this?

So in the following example code:

    library(ggplot2)
    library(gghighlight)

    # Example dataset
    set.seed(42)
    data <- data.frame(
    day = rep(1:100, 6),
    temp = rnorm(600, mean = 20, sd = 5),
    location = rep(c("Location_1", "Location_2", "Location_3", "Location_4", 
    "Location_5", "surrounding"), each = 100)
    )


    # Plot
    ggplot(data, aes(x = day, y = temp, color = location)) +
    geom_line() +
    facet_wrap(~location, ncol = 3) +
    gghighlight()

my image

But then not have a separate plot of surroundings, but have surroundings be highlighted in every plot.

I tried to add a line for surrounding after the gghighlight() function, like so:

     ggplot(data, aes(x = day, y = temp, color = location)) +
     geom_line(data = subset(data, location != "surrounding")) + 
     facet_wrap(~location, ncol = 3) +
     gghighlight() +
     geom_line(data = subset(data, location == "surrounding"))

But that didn't change anything in the plot.


Solution

  • Basically your approach with subset is right. However, you have to drop or rename the column used for facetting for the geom_line which you want to display in each facet:

    library(ggplot2)
    library(gghighlight)
    
    library(ggplot2)
    library(gghighlight)
    
    ggplot(mapping = aes(x = day, y = temp, color = location)) +
      geom_line(
        data = subset(data, location != "surrounding")
      ) +
      geom_line(
        data = subset(data, location == "surrounding", select = -location),
        aes(color = I("grey40"))
      ) +
      facet_wrap(~location, ncol = 3) +
      gghighlight()
    #> label_key: location