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

Matplotlib根据多条件为时间序列面积图设置分段填充色的实现方法

问题原因

你代码的两个核心错误:

  • colors[type]中的type是Python内置关键字,并非你DataFrame中的type字段,直接调用会触发类型错误
  • plt.fill_between第一个必填参数为x轴坐标序列,你误将value作为第一个参数传入,参数位置错误
正确实现代码
import pandas as pd
import matplotlib.pyplot as plt

# 你已有的数据集构造代码
df = pd.DataFrame({'date': {0: '2021-07-31',
  1: '2021-08-31',
  2: '2021-09-30',
  3: '2021-10-30',
  4: '2021-11-30',
  5: '2021-12-31'},
 'value': {0: 6.32, 1: 5.93, 2: 5.43, 3: 4.72, 4: 4.23, 5: 3.96},
 'type': {0: 1, 1: 1, 2: 2, 3: 2, 4: 3, 5: 3}})

# 预处理:将日期转为datetime格式,保证x轴时间展示正确
df['date'] = pd.to_datetime(df['date'])
# 建立type到填充色的映射关系
color_map = {
    1: 'gray',
    2: 'lightpink',
    3: 'skyblue'
}

# 按type分组逐段绘制填充区域
for type_val, group in df.groupby('type', sort=True):
    # 补充上一组最后一个数据点,避免不同type衔接处出现空隙
    if type_val != 1:
        prev_last = df[df['type'] == type_val - 1].iloc[-1]
        group = pd.concat([pd.DataFrame([prev_last]), group], ignore_index=True)
    plt.fill_between(
        x = group['date'],
        y1 = 0,
        y2 = group['value'],
        color = color_map[type_val],
        alpha = 0.5,
        label = f'type={type_val}'
    )

# 图表样式调整
plt.xticks(rotation=45)
plt.legend()
plt.tight_layout()
plt.show()

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.09.26 22:36:07