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

自定义调色板无法生效,图表全呈灰色的技术求助

问题解决:自定义调色板不生效的原因及修复

你的代码里存在一个关键错误:你在ggplot的aes()中用color = Sample_Type来映射线条和点的颜色,但后续调用的是scale_fill_manual()——这个函数是用来控制填充色的(比如柱状图、面积图的内部填充),而非线条/点的轮廓色,所以自定义调色板完全没起作用,图表只能显示默认灰色。

修复步骤

把scale_fill_manual(values = color_palette)替换为scale_color_manual(values = color_palette)即可,后者专门对应aes()中的color映射。

修正后的完整代码

# Define custom colors
color_palette <- c("2020 Urban" = "darkred", "2020 Suburban" = "gold", "2020 Rural" = "darkblue")

# Plot the data with custom color palette
ggplot(average_Pb_monthly, aes(x = Month, y = avg_Pb, group = Sample_Type, color = Sample_Type)) +
  geom_line(size = 1) +
  geom_point(size = 3) +
  labs(title = "Average Monthly Concentration of Pb in Honey Samples (2020) by Land Use",
       x = "Month",
       y = "Average Pb Concentration",
       color = "Land Use and Time") + # Label for legend
  scale_color_manual(values = color_palette) + # 替换为scale_color_manual
  theme_minimal() + # Change theme to remove grey background
  theme(axis.text.x = element_text(angle = 45, hjust = 1))

补充说明

  • scale_color_manual():控制线条、点的轮廓色,对应aes()中的color参数
  • scale_fill_manual():控制填充区域的颜色,对应aes()中的fill参数

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.06.26 22:54:58