I would like to remove part of a color legend while keeping the manual color I set, and I do not manage to do that.
Here is an example:
library(data.table)
library(ggplot2)
# create dummy data
df <- data.table(x = rep(1:10,10),year = rep(2011:2020,each = 10))
df[,y := rnorm(.N,year[1] - 2011,.5),year]
unique_years <- df$year %>% unique()
# number of lines I want to highlight
Ncol <- 4
grey_gradient <- paste0("grey",round(seq(90,55,length.out = length(unique_years)-Ncol)))
highlight_colors <- viridis::inferno(Ncol,begin = .2,end = .8)
ggplot(df,aes(x,y,color = as.factor(year),group = year))+
geom_line()+
scale_color_manual(breaks = unique_years,
values = c(grey_gradient ,highlight_colors ))+
theme_minimal()
Here in this example, I want to highlight the last 4 years with the viridris colors. I would like to keep only these years in the legend, but keep the other years with the grey gradient color I defined.
I tried:
ggplot(df,aes(x,y,color = as.factor(year),group = year))+
geom_line()+
scale_color_manual(breaks = 2017:2020,
values = c(highlight_colors,grey_gradient ))+
theme_minimal()
But this does not keep the grey gradient for the other years:
How can I do that?
>Solution :
You could subset your data to two geom_lines where your first geom is only with the grey lines using show.legend=FALSE. To use a new scale for your colors you could use new_scale_color from the package ggnewscale to add your color lines in the second geom like this with legend:
library(data.table)
library(ggplot2)
library(dplyr)
library(ggnewscale)
ggplot() +
geom_line(df |> filter(year %in% c(2011:2016)),
mapping = aes(x,y,color = as.factor(year), group = year),
show.legend = FALSE) +
scale_color_manual(values = grey_gradient) +
new_scale_color() +
geom_line(df |> filter(year %in% c(2017:2020)),
mapping = aes(x,y,color = as.factor(year), group = year)) +
scale_color_manual(values = highlight_colors)

Created on 2023-07-11 with reprex v2.0.2

