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

如何修改ggplot组合图中Electricity和Gas柱状图的填充颜色?

问题解决:自定义ggplot组合图中柱状图与折线图的颜色

问题说明

现有包含Date、Utility(分为Electricity和Gas)、usage、price字段的data.frame,绘制组合ggplot图表时,折线图颜色可修改,但柱状图中Electricity和Gas的颜色无法自定义,需调整代码实现需求。

数据结构

structure(list(Date = structure(c(18686, 18686, 18714, 18714, 
18745, 18745), class = "Date"), Utility = c("Gas", "Electricity", 
"Gas", "Electricity", "Gas", "Electricity"), usage = c(0, 0, 
125, 208, 104, 232), price = c(0, 0, 45.46, 37.82, 39.67, 43.09
)), row.names = c(NA, -6L), class = c("tbl_df", "tbl", "data.frame"
))

现有代码

ggplot(cost) +
  geom_bar(aes(x = Date, fill = Utility, weight = usage), alpha = 0.5) +
  scale_color_manual(values = c(Electricity = 'green', 
                                Gas = 'red')) +
  geom_line(aes(x = Date, y = price, colour = Utility),  size = 0.5) +
  scale_fill_hue(direction = 1) +
  scale_color_manual(
    values = c(Electricity = "firebrick1",
               Gas = "darkorchid1")
  ) +
  theme_minimal() + scale_x_date(date_breaks = "2 month")

解决方案

问题核心:一是重复调用scale_color_manual导致设置冲突,二是scale_fill_hue自动生成的颜色覆盖了柱状图的自定义需求。修改后的代码如下:

ggplot(cost) +
  # 柱状图:fill映射到Utility,保留透明度设置
  geom_bar(aes(x = Date, fill = Utility, weight = usage), alpha = 0.5) +
  # 折线图:colour映射到Utility
  geom_line(aes(x = Date, y = price, colour = Utility), size = 0.5) +
  # 自定义柱状图填充色
  scale_fill_manual(
    values = c(Electricity = "limegreen", 
               Gas = "tomato")
  ) +
  # 自定义折线图颜色(可与填充色对应或独立设置)
  scale_color_manual(
    values = c(Electricity = "firebrick1",
               Gas = "darkorchid1")
  ) +
  theme_minimal() + 
  scale_x_date(date_breaks = "2 month")

关键修改点

  • 移除重复的scale_color_manual调用,只保留一次自定义设置;
  • 删除scale_fill_hue,改用scale_fill_manual为柱状图的Utility类别指定自定义颜色;
  • 可根据需求自由调整scale_fill_manual和scale_color_manual中的颜色值,确保柱状图与折线图的颜色符合预期。

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.08.19 19:45:33