ggplot - how to show individual observations with geom_line but group their color?

Hi,

I have time series data with N different categories. I'd like to highlight 1 line and turns the other lines gray and apply a legend label of "Other". The problem I'm encountering is that once I group the "other" lines together, ggplot assumes they should be grouped and blends their data points into a single line.

Here is the original plot without grouping:

And here it is with the "other" group:

I'd like my plot to use the colors and labels of the second chart while keeping the individual lines from items b:e

Code to reproduce these is here:

library(tidyverse)
date <- rep(Sys.Date()-(7:1),5)
label <- sort(rep(letters[1:5],7))
value <- sample(1:10,7*5,replace=T)
df <- data.frame(date=date, label=label,value=value)

ggplot(df) + geom_line(aes(x=date,y=value,color=label))

df <- df %>% mutate(color = case_when(
  label == "a" ~ "blue",
  TRUE ~ "gray"
))

# This groups together all the 'gray' values
ggplot(df) + geom_line(aes(x=date,y=value,color=color)) + 
  scale_color_identity(labels = c(blue = "a",gray = "Other"),guide = "legend")

# This outputs too many "Other" labels
ggplot(df) + geom_line(aes(x=date,y=value,color=label)) + 
    scale_color_manual(
      values = c(a = "blue",b = "gray", c = "gray", d = "gray", e = "gray"),
      labels = c(a = "a",b = "Other", c = "Other", d = "Other", e = "Other"),
    guide = "legend")


I think you need to use the group aesthetic.

library(ggplot2)
library(dplyr)
#> 
#> Attaching package: 'dplyr'
#> The following objects are masked from 'package:stats':
#> 
#>     filter, lag
#> The following objects are masked from 'package:base':
#> 
#>     intersect, setdiff, setequal, union
date <- rep(Sys.Date()-(7:1),5)
label <- sort(rep(letters[1:5],7))
value <- sample(1:10,7*5,replace=T)
df <- data.frame(date=date, label=label,value=value)

ggplot(df) + geom_line(aes(x=date,y=value,color=label))


df <- df %>% mutate(color = case_when(
  label == "a" ~ "blue",
  TRUE ~ "gray"
))

# This groups together all the 'gray' values
ggplot(df) + geom_line(aes(x=date,y=value, group = label, color=color)) + 
  scale_color_identity(labels = c(blue = "a",gray = "Other"),guide = "legend")

Created on 2020-06-08 by the reprex package (v0.3.0)

This topic was automatically closed 7 days after the last reply. New replies are no longer allowed.