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

如何基于GDP变化条件实现matplotlib fill_between填充并解决空白问题

问题描述

有一份2002到2017年的DataFrame数据,样例如下:

Team,Finish.1_x,Finish.1_y,Win%Detroit,Win%Chicago,Date,GdpDetroit,GdpChicago,D_GDP_Change,C_GDP_Change,detroitdummy,chicagodummy
2002–03,1st,6th,0.61,0.366,2002-01-01,49650,54744,933.0,-27.0,1,0
2003–04,2nd,8th,0.659,0.28,2003-01-01,51101,55273,1451.0,529.0,1,1
2004–05,1st,2nd,0.659,0.573,2004-01-01,50935,56507,-166.0,1234.0,0,1
2005–06,1st,4th[k],0.78,0.5,2005-01-01,52028,57608,1093.0,1101.0,1,1
2006–07,1st,3rd,0.646,0.598,2006-01-01,50576,58717,-1452.0,1109.0,0,1
2007–08,1st,4th,0.72,0.402,2007-01-01,50450,59240,-126.0,523.0,0,1
2008–09,3rd,2nd,0.476,0.5,2008-01-01,47835,57197,-2615.0,-2043.0,0,0
2009–10,5th,3rd,0.329,0.5,2009-01-01,43030,54802,-4805.0,-2395.0,0,0
2010–11,4th,1st,0.366,0.756,2010-01-01,45735,55165,2705.0,363.0,1,1
2012–13,4th,2nd,0.354,0.549,2012-01-01,48469,57254,926.0,1463.0,1,1
2013–14,4th,2nd,0.354,0.585,2013-01-01,48708,56939,239.0,-315.0,1,0
2014–15,5th,2nd,0.39,0.61,2014-01-01,49594,57823,886.0,884.0,1,1
2015–16,3rd,4th,0.537,0.512,2015-01-01,50793,59285,1199.0,1462.0,1,1
2016–17,5th,4th,0.451,0.5,2016-01-01,51578,60191,785.0,906.0,1,1
2017–18,4th,5th,0.476,0.329,2017-01-01,52879,61170,1301.0,979.0,1,1

需求为绘制x轴为Date列、y轴为底特律胜率的图表,fill_between填充区域根据底特律GDP变化的正负设置条件:GDP增长填充蓝色,GDP下降填充红色。

当前使用代码如下:

fig, ax = plt.subplots()
ax.fill_between(df["Date"],np.max(df["Win%Detroit"]), where=(np.sign(df["D_GDP_Change"])<= 0), color='r', alpha=.1)
ax.fill_between(df["Date"],np.max(df["Win%Detroit"]), where=(np.sign(df["D_GDP_Change"])> 0), color='b', alpha=.1)
ax.plot(df["Date"],df["Win%Detroit"])
plt.show()

运行后填充色块存在空白区域,不符合预期效果。

问题原因

fill_between默认不会对where条件切换的相邻离散点做插值处理,当相邻两个点的GDP正负状态不同时,两点之间的过渡区域会被判定为不满足任意填充条件,就会出现空白。

解决方法

在fill_between参数中添加interpolate=True开启插值填充即可,同时建议提前将Date列转换为datetime格式,避免x轴为字符串类型导致的渲染异常。

修正后代码如下:

import pandas as pd
import matplotlib.pyplot as plt
import numpy as np

# 转换日期格式
df["Date"] = pd.to_datetime(df["Date"])

fig, ax = plt.subplots()
# 开启插值填充,y1设为0让填充覆盖整个y轴底部到胜率最大值的范围
ax.fill_between(df["Date"], y1=0, y2=np.max(df["Win%Detroit"]), 
                where=(np.sign(df["D_GDP_Change"])<= 0), 
                color='r', alpha=0.1, interpolate=True)
ax.fill_between(df["Date"], y1=0, y2=np.max(df["Win%Detroit"]), 
                where=(np.sign(df["D_GDP_Change"])> 0), 
                color='b', alpha=0.1, interpolate=True)
ax.plot(df["Date"], df["Win%Detroit"])
# 可选:旋转x轴标签避免重叠
plt.xticks(rotation=45)
plt.tight_layout()
plt.show()

interpolate参数会自动计算条件切换的交叉点,填充原本空缺的过渡区域,彻底解决色块空白问题。


内容的提问来源于stack exchange,提问作者KArrow'sBest

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.09.29 20:54:06