Python 填充上方/下方 matplotlib 线图

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/16917919/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-18 23:59:52  来源:igfitidea点击:

Filling above/below matplotlib line plot

pythonmatplotlib

提问by user1728853

I'm using matplotlib to create a simple line plot. My plot is a simple time-series data set where I have time along the x-axis and the value of something I am measuring on the y-axis. y values can have postitive or negative values and I would like to fill in the area above and below my line with the color blue if the y-value is > 0 and red if the y values is < 0. Here's my plot:

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

enter image description here

在此处输入图片说明

As you can see, I can get the blue color to fill in correctly, but I can not get the red color to fill in properly. Here's the basic code I am using:

如您所见,我可以正确填充蓝色,但无法正确填充红色。这是我正在使用的基本代码:

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')

How can I get the area from a positive y-value to the x-axis to be blue and the area from a negative y-value to the x-axis to be red? Thanks for the help.

如何使从正 y 值到 x 轴的区域为蓝色,而从负 y 值到 x 轴的区域为红色?谢谢您的帮助。

采纳答案by sodd

The code snippet you provided should be corrected as follows:

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

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')

The fill_betweenmethod takes at least two arguments xand y1, while it also has a parameter y2with default value 0. The method will fill the area between y1and y2for the specified x-values.

fill_between方法至少接受两个参数xand y1,同时它还有一个y2默认值为 0 的参数。该方法将填充指定-valuesy1和之间的区域。y2x

The reason why you didn't get any filling below the x-axis, is due to the fact that you had specified that the fill_betweenmethod should fill the area between y1=0and y2=0, i.e. noarea. To make sure that the fill does not only appear on explicitx-values, specify that the method should interpolate y1as to find the intersections with y2, which is done by specifying interpolate=Truein the method call.

为什么你没有得到的x轴下方的任何填充究其原因,是由于这样的事实,你已指定的fill_between方法应填写之间的区域y1=0y2=0,即区域。为确保填充不仅出现在显式x 值上,请指定该方法应进行插值y1以找到与 的交集y2,这是通过interpolate=True在方法调用中指定来完成的。

回答by Thriveth

Try setting the keyword interpolate=True.

尝试设置关键字interpolate=True