You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

如何使用R的ggplot为堆叠条形图创建自定义调色板?

自定义ggplot堆叠条形图的填充颜色

方法一:直接替换调色板向量

  1. 先把你指定的颜色整理成一个向量(可以保留变量名或直接用色值):
# 定义颜色变量
green <- "#00943b"
berggreen <- "#006551"
technoblue <- "#2f53a0"
signalyellow <- "#fdc300"
hellgrey <- "#f0f0f0"
mittelgrey <- "#a8a8a8"
dunkelgrey <- "#6f6f6f"
dunkelblue <- "#123374"
hellblue <- "#7da9db"
dunkeltuerkis <- "#007982"
helltuerkis <- "#63c3d1"

# 组合成自定义颜色向量
custom_colors <- c(green, berggreen, technoblue, signalyellow, hellgrey, mittelgrey, dunkelgrey, dunkelblue, hellblue, dunkeltuerkis, helltuerkis)
  1. 替换原代码中scale_fill_manual的values参数,把terrain.colors(...)换成上面的custom_colors即可:
pp <- ggplot(dt.data, aes(x = delivMonth, y = val, fill = comp)) +
  geom_bar(stat = "identity") +
  labs(x = "", y = "<b>Val", title = "<b>Stacked Bar Chart") +
  scale_fill_manual(values = custom_colors) +  # 这里替换为自定义颜色向量
  theme_minimal() +
  theme(legend.position = "right") +
  guides(fill = guide_legend(title = "<b>Comp")) +
  scale_x_date(date_labels = "%Y-%m", date_breaks = "1 month") +
  theme(axis.text.x = element_text(angle = 45, hjust = 1)) +
  theme(plot.title = element_text(hjust = 0.5)) +
  theme(legend.key.size = unit(0.7, "cm"))

ggplotly(pp, tooltip = c("x", "y", "fill"), hovermode = "x")

方法二:指定类别与颜色的对应关系(进阶)

如果需要让特定的comp类别绑定固定颜色,可将颜色向量改为命名向量,避免类别顺序变化导致颜色错位:

custom_named_colors <- c(
  "公司A" = green,       # 替换成你实际的comp类别名称
  "公司B" = berggreen,
  "公司C" = technoblue,
  "公司D" = signalyellow,
  # 按需求补充其他类别与颜色的对应
)

# 调用时直接使用命名向量
scale_fill_manual(values = custom_named_colors)

注:如果comp的类别数量少于自定义颜色数量,ggplot会自动取用前N个颜色;如果类别数量超过颜色数量,会循环使用颜色。

内容的提问来源于stack exchange,提问作者Miko

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.06.28 21:03:33