Search code examples
rggplot2line-plot

ggplot line plot with one group`s lines on top


I am making a line plot of several groups and want to make a visualization where one of the groups lines are highlighted

ggplot(df) + geom_line(aes(x=timepoint ,y=var, group = participant_id, color=color)) + 
  scale_color_identity(labels = c(red = "g1",gray90 = "Other"),guide = "legend")

However, the group lines are partially obscured by the other groups lines

image

How can I make these lines always on top of other groups lines?


Solution

  • The simplest way to do this is to plot the gray and red groups on different layers.

    First, let's try to replicate your problem with a dummy data set:

    set.seed(1)
    
    df <- data.frame(
      participant_id = rep(1:50, each = 25),
      timepoint = factor(rep(0:24, 50)),
      var = c(replicate(50, runif(1, 50, 200) + runif(25, 0.3, 1.5) *
              sin(0:24/(0.6*pi))^2/seq(0.002, 0.005, length = 25))),
      color = rep(sample(c("red", "gray90"), 50, TRUE, prob = c(1, 9)), each = 100)
    )
    

    Now we apply your plotting code:

    library(ggplot2)
    
    ggplot(df) + 
      geom_line(aes(x=timepoint ,y=var, group = participant_id, color = color)) + 
      scale_color_identity(labels = c(red = "g1", gray90 = "Other"),
                           guide = "legend") +
      theme_classic()
    

    This looks broadly similar to your plot. If instead we plot in different layers, we get:

    ggplot(df, aes(timepoint, var, group = participant_id)) +
      geom_line(data = df[df$color == "gray90",], aes(color = "Other")) +
      geom_line(data = df[df$color == "red",], aes(color = "gl")) +
      scale_color_manual(values = c("red", "gray90")) +
      theme_classic()
    

    Created on 2022-06-20 by the reprex package (v2.0.1)