填充在matplotlib线图的上方/下方 [英] Filling above/below matplotlib line plot

查看:43
本文介绍了填充在matplotlib线图的上方/下方的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

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

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:

如您所见,我可以正确地填充蓝色,但是我不能正确地填充红色.这是我正在使用的基本代码:

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

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

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.

推荐答案

您提供的代码段应按以下方式更正:

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

fill_between 方法至少需要两个参数 xy1,同时还有一个参数 y2,默认值为 0.该方法会填充 y1 之间的区域和 y2 用于指定的 x-values.

The fill_between method takes at least two arguments x and y1, while it also has a parameter y2 with default value 0. The method will fill the area between y1 and y2 for the specified x-values.

您没有在 x 轴下方进行任何填充的原因是因为您已指定 fill_between 方法应填充 y1=0 之间的区域 y2 = 0 ,即 no 区域.为了确保填充不仅显示在 explicit x值上,请指定该方法应插值 y1 ,以查找与 y2 ,这是通过在方法调用中指定 interpolate=True 来完成的.

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_between method should fill the area between y1=0 and y2=0, i.e. no area. To make sure that the fill does not only appear on explicit x-values, specify that the method should interpolate y1 as to find the intersections with y2, which is done by specifying interpolate=True in the method call.

这篇关于填充在matplotlib线图的上方/下方的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆