Home > Blockchain >  ggplot line plot with one group`s lines on top
ggplot line plot with one group`s lines on top

Time:06-21

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?

Thanks in advance

CodePudding user response:

You can use factor releveling to bring the line (-s) of interest to front.

First, let's plot the data as is, with the red line partly hidden by others.

library(ggplot2)
library(dplyr)
    
set.seed(13)
df <- 
      data.frame(timepoint = rep(c(1:100), 20),
             participant_id = paste0("p_", sort(rep(c(1:20), 100))),
             var = abs(rnorm(2000, 200, 50) - 200),
             color =  c(rep("red", 100), rep("gray90", 1900)))
    
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")

wrong line plot

Now let's bring p_1 to front by making it the last factor level.

    df %>% 
      mutate(participant_id = factor(participant_id)) %>% 
      mutate(participant_id = relevel(participant_id, ref = "p_1")) %>% 
      mutate(participant_id = factor(participant_id, levels = rev(levels(participant_id)))) %>%
      ggplot()   
      geom_line(aes(x=timepoint, 
y=var, 
group = participant_id, 
color = color))   
      scale_color_identity(labels = c(red = "g1", gray90 = "Other"), 
guide = "legend")

correct line plot

CodePudding user response:

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)

  • Related