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

Python实现时序柱状图历史与预测数据颜色动态切换

可以实现,解决方案如下

你的核心问题是硬编码的颜色列表无法适配动态调整的时间范围,解决思路是根据时间索引自动区分历史/预测数据,动态生成对应颜色,而非提前写死颜色列表。

实现步骤

  1. 明确历史数据与预测数据的时间分界点(可根据实际需求灵活调整)
  2. 针对每个图表的时间索引,逐个判断该时间属于历史还是预测,生成对应颜色的列表
  3. 将动态生成的颜色列表传入plt.bar的color参数即可

修改后的代码

import matplotlib.pyplot as plt
import pandas as pd

names = ["Cat1", "Cat2", "Cat3"]
# 定义历史/预测的时间分界(可替换为具体日期,比如pd.Timestamp('2022-12-31'))
history_end_year = 2022
# 动态调整时间范围(支持任意客户需求的时间区间)
timeframe = state["2019":"2026"]
timeframe1 = statepc["2019":"2026"]

for col, name in zip(timeframe.columns, names):
    plt.figure(figsize=(10,10))
    # 动态生成颜色列表:根据索引年份判断属于历史还是预测
    colors = ['#3f4faa' if idx.year <= history_end_year else '#ff573b' for idx in timeframe.index]
    barplot = plt.bar(timeframe.index, timeframe[col], color=colors)
    plt.grid(False)
    plt.ylabel('A')
    plt.bar_label(barplot, labels=timeframe1[col].round(1).astype(str).add('%'), label_type="edge")
    plt.title(name)
plt.show()

关键说明

  • 若时间索引是更精细的日/月/季度格式,只需修改判断条件(比如idx.month或idx.date() <= pd.Timestamp('2022-06-30'))
  • 无论如何调整timeframe的时间范围,颜色都会自动匹配:分界点之前的历史数据用#3f4faa,之后的预测数据用#ff573b
  • 颜色值可根据需求直接替换为其他HEX码或Matplotlib支持的颜色名称

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.07.11 13:34:55