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

使用fill_between()添加上下限带时未铺满X轴的技术问题

解决fill_between()限值带无法铺满X轴的问题

我已完成图表绘制,需要为其中两条曲线添加最大、最小限值带,但使用fill_between()生成的限值带无法铺满整个X轴,相关代码如下:

import pandas as pd
import matplotlib.pyplot as plt

dados = {'Trajetória Prometida': {'2023': -0.5,
                             '2024': 0,
                             '2025': 0.5,
                             '2026': 1},
        'Nova Trajetória': {'2023': None,
                        '2024': 0,
                        '2025': 0,
                        '2026': 0.25},
        'Focus': {'2023': -2.3,
            '2024': -0.8,
            '2025': -0.6,
            '2026': -0.5},
        'SAMI': {'2023': None,
             '2024': -0.7,
             '2025': -0.8,
             '2026': -0.6},
             }
df = pd.DataFrame(dados)

fig, ax = plt.subplots(figsize=(5,5))

max1 = [-0.25, 0.25, 0.75, 1.25]
min1 = [-0.75, -0.25, 0.25, 0.75]
ax.fill_between(df['Trajetória Prometida'], max1, min1, alpha=.5, linewidth=2)
ax.plot(df)

效果说明

  • 当前效果:限值带仅覆盖曲线数据点对应的纵向范围,未延伸至X轴两端
  • 预期效果:限值带铺满整个X轴宽度,覆盖图表全部横向区域

解决方案

问题根源是你将曲线的Y值(df['Trajetória Prometida'])作为fill_between()的X轴参数,导致填充范围被限制在Y值的区间内。只需将参数替换为X轴的索引位置,即可让填充带铺满整个X轴:

import pandas as pd
import matplotlib.pyplot as plt

dados = {'Trajetória Prometida': {'2023': -0.5,
                             '2024': 0,
                             '2025': 0.5,
                             '2026': 1},
        'Nova Trajetória': {'2023': None,
                        '2024': 0,
                        '2025': 0,
                        '2026': 0.25},
        'Focus': {'2023': -2.3,
            '2024': -0.8,
            '2025': -0.6,
            '2026': -0.5},
        'SAMI': {'2023': None,
             '2024': -0.7,
             '2025': -0.8,
             '2026': -0.6},
             }
df = pd.DataFrame(dados)

fig, ax = plt.subplots(figsize=(5,5))

max1 = [-0.25, 0.25, 0.75, 1.25]
min1 = [-0.75, -0.25, 0.25, 0.75]
# 将X轴参数替换为df.index,对应年份的位置索引
ax.fill_between(df.index, max1, min1, alpha=.5, linewidth=2)
ax.plot(df)
# 确保X轴正确显示年份标签
plt.xticks(range(len(df)), df.index)
plt.show()

修改后,fill_between()会基于X轴的完整索引范围(从第一个年份到最后一个年份)进行填充,限值带即可铺满整个X轴,达到预期效果。


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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.06.25 12:32:28