升级至ggplot2 3.3.4版本后绘图出现意外颜色变化问题
ggplot2 3.3.3到3.3.4版本颜色显示异常解决方案
问题原因
ggplot2 3.3.4版本调整了离散色阶的默认匹配逻辑:当scale_colour_manual()只指定breaks但未显式指定limits或给values命名时,未出现在breaks中的因子水平会无法正确匹配预设颜色,最终出现颜色错位、变灰等异常。
效果差异对比

解决方法
有两种兼容两个版本的修正方案,任选其一即可:
- 方案1:为颜色值命名,固定水平与颜色的对应关系
把scale_colour_manual里的values转为命名向量,每个颜色对应固定的stadio水平,不受版本逻辑影响,适配性最强。 - 方案2:显式指定
limits参数
在scale_colour_manual中添加limits参数,指定所有要匹配的因子水平,保证11个颜色按顺序对应1-11的stadio值。
修正后的完整代码
library(RColorBrewer) library(ggplot2) df <- structure(list(name = structure(c(11L, 11L, 11L, 11L, 11L, 11L, 11L, 11L, 11L, 11L, 9L, 9L, 9L, 9L, 9L, 9L, 9L, 9L, 9L, 9L, 12L, 12L, 12L, 12L, 12L, 12L, 12L, 12L, 12L, 12L, 10L, 10L, 10L, 10L, 10L, 10L, 10L, 10L, 10L, 10L), .Label = c("5303 B", "5303 A", "5302 B", "5302 A", "5301 B", "5301 A", "5202 B", "5202 A", "5201 B", "5201 A", "5101 B", "5101 A"), class = "factor"), stadio = c(2, 2, 4, 4, 6, 6, 8, 8, 10, 10, 2, 2, 4, 4, 6, 6, 8, 8, 10, 10, 1, 1, 3, 3, 7, 7, 9, 9, 11, 11, 1, 1, 3, 3, 7, 7, 9, 9, 11, 11 ), variable = structure(c(1L, 2L, 1L, 2L, 1L, 2L, 1L, 2L, 1L, 2L, 1L, 2L, 1L, 2L, 1L, 2L, 1L, 2L, 1L, 2L), .Label = c("start_date", "end_date"), class = "factor"), value = c("15/10/2021", "03/01/2022", "03/01/2022", "30/03/2022", "30/03/2022", "30/03/2023", "30/03/2023", "15/09/2023", "15/09/2023", "29/12/2023", "15/10/2021", "03/01/2022", "03/01/2022", "30/03/2022", "30/03/2022", "30/03/2023", "30/03/2023", "15/09/2023", "15/09/2023", "29/12/2023", "26/11/2021", "14/01/2022", "14/01/2022", "30/06/2022", "30/06/2022", "30/03/2023", "30/03/2023", "15/09/2023", "15/09/2023", "29/12/2023", "26/11/2021", "14/01/2022", "14/01/2022", "30/06/2022", "30/06/2022", "30/03/2023", "30/03/2023", "15/09/2023", "15/09/2023", "29/12/2023"), rating = structure(c(1L, 1L, 1L, 1L, 1L, 1L, 1L, 1L, 1L, 1L, 1L, 1L, 1L, 1L, 1L, 1L, 1L, 1L, 1L, 1L, 2L, 2L, 2L, 2L, 2L, 2L, 2L, 2L, 2L, 2L, 2L, 2L, 2L, 2L, 2L, 2L, 2L, 2L, 2L, 2L), .Label = c("2", "3"), class = "factor")), row.names = c(NA, -40L), class = c("tbl_df", "tbl", "data.frame")) ggplot(df, aes(as.POSIXct(as.Date(value, "%d/%m/%Y")), name, colour = factor(stadio,levels=1:11))) + guides(alpha = "none", colour = guide_legend( override.aes = list(size = 4))) + geom_line(aes(size=rating, alpha=rating)) + scale_alpha_manual(values=c(.5,1)) + labs(colour="(Actual/Baseline)", x = "", y = "") + # 方案1:给values命名,固定对应关系,二选一即可 scale_colour_manual(breaks = c("1", "3", "7","9","11"), values = setNames(brewer.pal(11,"PiYG"), 1:11)) + # 方案2写法:显式指定limits,注释掉方案1后放开下方代码即可 # scale_colour_manual(breaks = c("1", "3", "7","9","11"), values = brewer.pal(11,"PiYG"), limits = as.character(1:11)) + scale_size_manual(breaks = levels(df$rating), values = as.integer(levels(df$rating)), guide = "none")
内容的提问来源于stack exchange,提问作者Yorgos
相关产品推荐
相关产品推荐

