如何在使用 ColorBrewer 调色板的同时在 R 中保留我的自定义图例顺序?
How can I keep my custom legend order in R while also utilizing the ColorBrewer palettes?
我知道如何在 scale_color_discrete 中使用中断来更改图例的顺序。我也知道如何使用 scale_color_brewer 更改调色板。
但是,我不知道如何以正确的方式将它们组合在一起。如果我使用下面的代码,R 将分配我想要的调色板,然后重新排序我的列表。我希望它以相反的顺序发生,因为我希望顺序调色板着色根据我指定的顺序完成。如何在无需手动输入颜色代码的情况下执行此操作?
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)
根据您的编辑,与其尝试动态设置自定义级别和自定义调色板,不如在绘图之前设置组级别更容易。
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")
我知道如何在 scale_color_discrete 中使用中断来更改图例的顺序。我也知道如何使用 scale_color_brewer 更改调色板。
但是,我不知道如何以正确的方式将它们组合在一起。如果我使用下面的代码,R 将分配我想要的调色板,然后重新排序我的列表。我希望它以相反的顺序发生,因为我希望顺序调色板着色根据我指定的顺序完成。如何在无需手动输入颜色代码的情况下执行此操作?
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)
根据您的编辑,与其尝试动态设置自定义级别和自定义调色板,不如在绘图之前设置组级别更容易。
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")