使用ggplot2+RColorBrewer绘图时不同图类型配色不一致问题求助
解决ggplot2多图配色一致问题
问题根源
你的代码里第二张图同时映射了color=y和fill=y,但仅为fill设置了Set3调色板,color用的是ggplot默认配色,这才是两张图颜色不匹配的核心原因。此外,虽然你的y因子顺序固定,但显式指定因子水平与调色板的对应关系能避免潜在的顺序错乱。
修正后的代码
library(tidyverse) library(ggplot2) library(RColorBrewer) set.seed(1) df <- tibble(x=rnorm(600), y = as.factor(rep(1:6, 100))) # 箱线图 p1 <- ggplot(df, aes(x=x, y=y, fill=y)) + stat_boxplot(alpha=.7, outlier.shape=5) + theme_minimal() + # 显式指定因子水平,确保颜色映射固定 scale_fill_brewer(palette = "Set3", limits = levels(df$y)) ggsave(file="fig1.pdf", plot=p1, width = 210/2, height = 297/2, units = "mm") # 统计摘要点图 p2 <- ggplot(df, aes(x=x, y=y, fill=y, color=y)) + stat_summary(fun=median, geom='point', shape=17, size=3, alpha=.7) + theme_minimal() + # 为fill和color都设置Set3调色板,且绑定相同的因子水平 scale_fill_brewer(palette = "Set3", limits = levels(df$y)) + scale_color_brewer(palette = "Set3", limits = levels(df$y)) ggsave(file="fig2.pdf", plot=p2, width = 210/2, height = 297/2, units = "mm")
关键改动说明
- 为两张图的
scale_fill_brewer添加limits = levels(df$y),强制调色板颜色按y的因子水平顺序映射,避免因数据子集或图层差异导致顺序变化。 - 第二张图新增
scale_color_brewer(palette = "Set3", limits = levels(df$y)),让color也使用Set3调色板,且和fill保持相同的因子-颜色对应关系。 - 将绘图对象赋值给变量后再调用
ggsave,避免原代码中语法错误(ggplot语句后直接接ggsave缺少正确的调用逻辑)。
内容的提问来源于stack exchange,提问作者Otto Kässi
相关产品推荐
相关产品推荐

