Search code examples
rggplot2colorbrewer

How can I keep my custom legend order in R while also utilizing the ColorBrewer palettes?


I know how to change the order of my legend by using breaks within scale_color_discrete. I also know how to change the color palette using scale_color_brewer.

However, I do not know how to group these together in the proper way. If I use the code below, R will assign the color palette I want, and then re-order my list. I want this to happen in the reverse order, because I want the sequential palette coloring to be done based on the order I specified. How can I do this without having to manually enter color codes?

library(ggplot2)

df <- data.frame(team=c("liquid","faze","faze","wtsg","liquid","wtsg","faze","liquid","faze","wtsg"),elo=c(1550,1530,1511,1541,1499,1522,1480,1470,1510,1440),date=c("2020-03-08","2020-03-08","2020-03-01","2020-03-08","2020-02-24","2020-02-24","2020-02-24","2020-02-16","2020-02-16","2020-02-16"))

df$team <- as.character(df$team)
df$date <- as.Date(df$date)

order=c("liquid","wtsg","faze")

# This will give me the palette I desire and the order I desire, however, the color progression of the palette will not be in the same order as the legend, which is what I want. 
ggplot(data=df)+
  geom_line(mapping=aes(x=date,y=elo,color=team),size=2)+
  scale_color_discrete(palette="Spectral", breaks=order)

Solution

  • In response to your edit, rather than trying to set both custom levels and a custom palette on the fly, it would be easier to set the group levels before plotting.

    df$team <- factor(df$team, levels = order)
    
    ggplot(data = df) +
      geom_line(mapping = aes(x = date, y = elo, color = team), size = 2) +
      scale_color_brewer(palette = "Spectral")
    

    enter image description here