21
votes

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:

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.

2
I believe the last line in the code snippet should be ax.fill_between(xs,ys,where=ys<=d, color='red'), as you are now trying to fill the area between y1=0 and y2=0 (i.e. no area). The second argument (in this case ys) is passed to the y1 parameter, and since y2 has default value 0, the method will fill the area between the array you have specified for y1 and the line y=0, which is what you want. - sodd
Thanks for the help. Your suggestion partly worked. However, I still am not geting the proper color fill in cases where a point say, (10, 10) is connected to another point that crosses the x-axis, say (11, -10). Here's what the plot looks like: postimg.org/image/u329jhlob - user1728853
Ah, I figured that was what you wanted, seeing how you said the blue fill on the figure above was correct. This should be an easy fix: ax.fill_between(xs,ys,where=ys<=d, interpolate=True, color='red'). The interpolate parameter makes the function interpolate to find the intersection between the y1 and y2 arrays, as to get a "smoother" plot. - sodd
Perfect!!! Thanks so much for the help. - user1728853

2 Answers

26
votes

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_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.

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.

2
votes

Try setting the keyword interpolate=True.