matplotlib fill_between with discrete x-values and where parameter produces gaps

Viewed 280

I'm trying to create an area plot where the fill changes based on the y value. Using fill_between and the where parameter mostly works, but leaves unfilled areas:

import numpy as np
import matplotlib.pyplot as plt

x=np.arange(1,10)
y=np.array([1,4,6,8,4,7,5,6,0])

plt.plot(x, y, color='black')
plt.fill_between(x, y, where=y < 5, color='red')
plt.fill_between(x, y, where=y >= 5, color='blue')

plt.show()

Run on trinket.io

Produces this result: Plot without interpolation

What does it take to get rid of any white areas below the graph? I don't have strict requirements as to how the current "in-between" areas ought to be coloured. Either - or both, meeting at a mid-point - will do.

Adding interpolate=True improves the situation slightly in some ways, but in other ways it looks more messy: Plot with interpolation

I've looked at the step parameter, but that doesn't seem promising to my eyes.

1 Answers

Since your requirements are simple, the best way is to probably decide your "default" colour and use that as the fill_between for the entire curve without specifying any condition. On top of this, you can add different colors for different conditions. Something like:

fig, ax = plt.subplots()

ax.fill_between(x, y, color="blue")
ax.fill_between(x, y, where=y<=5, color="red")

Which gives the following output:

enter image description here

Related