在matplotlib线图上方/下方填充p

2024-05-22 23:50:44 发布

您现在位置:Python中文网/ 问答频道 /正文

我正在使用matplotlib创建一个简单的线条图。我的图是一个简单的时间序列数据集,其中我有沿x轴的时间和在y轴上测量的值。y值可以是正值或负值,如果y值为>;0,我希望用蓝色填充行上下的区域;如果y值为<;0,我希望用红色填充行上下的区域。我的计划是:

enter image description here

如你所见,我能正确地填写蓝色,但我不能正确地填写红色。下面是我使用的基本代码:

plt.plot(x, y, marker='.', lw=1)
d = scipy.zeros(len(y))
ax.fill_between(xs,ys,where=ys>=d, color='blue')
ax.fill_between(xs,0,where=ys<=d, color='red')

怎样才能得到从正y值到x轴的区域是蓝色的,从负y值到x轴的区域是红色的?谢谢你的帮助。


Tags: 数据区域matplotlib时间序列betweenaxwhere
2条回答

尝试设置关键字interpolate=True

您提供的代码段应更正如下:

plt.plot(x, y, marker='.', lw=1)
d = scipy.zeros(len(y))
ax.fill_between(xs, ys, where=ys>=d, interpolate=True, color='blue')
ax.fill_between(xs, ys, where=ys<=d, interpolate=True, color='red')

^{}方法至少接受两个参数xy1,同时它还有一个默认值为0的参数y2。该方法将为指定的x值填充y1y2之间的区域。

之所以在x轴以下没有得到任何填充,是因为您指定了fill_between方法应该填充y1=0y2=0之间的区域,即no区域。为了确保填充不仅出现在显式的x值上,指定该方法应该插值y1,以找到与y2的交点,这是通过在方法调用中指定interpolate=True来完成的。

相关问题 更多 >

    热门问题