MWE:
library(ggplot2)
library(dplyr)
df <- data.frame(GROUP = factor(c("AL", "AS", "B", "HI", "I", "P", "T", "W", "E", "NE", "EL", "EP", "SW", "SOD"), ordered = TRUE),
color.codes = c("#000000",
"#b05cc6",
"#afb045",
"#7777c8",
"#db8f47",
"#4dacd0",
"#cb5242",
"#56b88f",
"#c75a88",
"#5db74e",
"#4f7e3b",
"#ff0000",
"#8d7134",
"#000080"),
Year = rep(paste0(2010:2025, "-", 2011:2026), each=14),
value = runif(224))
df$Year <- factor(df$Year,
levels=sort(unique(df$Year)),
ordered=TRUE)
ggplot(df,
aes(x = Year, y = value, color = GROUP, group = GROUP)) +
geom_point() +
geom_line(linetype = "dotted") + # make all dotted by default
geom_line(data = (df %>% filter(Year <= "2014-2015")),
aes(x = Year, y = value, color = GROUP),
lty = "solid") + # and then make all prior to 2015 solid
scale_color_manual(values = df$color.codes) +
xlab("School Year") +
ylab("Proficiency Rate")
让我们检查数据框:
> head(df)
GROUP color.codes Year value
1 AL #000000 2010-2011 0.5540173
2 AS #b05cc6 2010-2011 0.0301139
3 B #afb045 2010-2011 0.7469069
4 HI #7777c8 2010-2011 0.4981707
5 I #db8f47 2010-2011 0.9677573
6 P #4dacd0 2010-2011 0.7777855
例如,根据Google的说法,#b05cc6
属于purple shade。但它显然看起来很红,尽管它应该是紫色的。
B
与AL
颜色相同也没有任何意义。如何解决这个问题?
答案 0 :(得分:4)
制作组名称和颜色代码映射的调色板:
pal = unique(df[,c("GROUP","color.codes")])
> head(pal)
GROUP color.codes
1 AL #000000
2 AS #b05cc6
3 B #afb045
4 HI #7777c8
5 I #db8f47
6 P #4dacd0
将颜色代码修正为字符而不是因子,否则它们会转换为数字并在调色板中查找:
> pal$color.codes=as.character(pal$color.codes)
现在从调色板列创建一个命名向量:
> pval = pal$color.codes
> names(pval) = pal$GROUP
> pval
AL AS B HI I P T W
"#000000" "#b05cc6" "#afb045" "#7777c8" "#db8f47" "#4dacd0" "#cb5242" "#56b88f"
E NE EL EP SW SOD
"#c75a88" "#5db74e" "#4f7e3b" "#ff0000" "#8d7134" "#000080"
然后在scale_color_manual(values=pval)
中使用它。
现在AS看起来很pur,B看起来像一种绿色的色彩。
EP看起来很红。等