python - How to avoid gaps with matplotlib.fill_between and where -


i want fill area between 2 curves when lower curve >0. i'm using fill_between() in matplotlib where condition (to test curve greater) , numpy.maximum() (to test whether lower curve >0). there gaps in fill because lower curve crosses x-axis between integers while result of maximum hits x-axis at integer. how can fix this?

import numpy np import matplotlib.pyplot plt  x = np.arange(0, 10) = np.array([101, 102, 71, 56, 49, 15, 29, 31, 45, 41]) b = np.array([52, 39, 8, -7, -12, -45, -23, -9, 14, 19])  fig, ax = plt.subplots() ax.plot(x, a) ax.plot(x, b) ax.fill_between(x, a, np.maximum(b, 0), where=a >= b, alpha=0.25)  plt.axhline(0, color='black') 

enter image description here

(i want white triangles shaded well.)

by interpolating values using numpy.interp:

import numpy np import matplotlib.pyplot plt  x = np.arange(0, 10) = np.array([101, 102, 71, 56, 49, 15, 29, 31, 45, 41]) b = np.array([52, 39, 8, -7, -12, -45, -23, -9, 14, 19])  x2 = np.linspace(x[0], x[-1] + 1, len(x) * 100)  # <--- a2 = np.interp(x2, x, a)                         # <--- b2 = np.interp(x2, x, b)                         # <--- x, a, b = x2, a2, b2                             # <---  fig, ax = plt.subplots() ax.plot(x, a) ax.plot(x, b) ax.fill_between(x, a, np.maximum(0, b), where=a>b, alpha=0.25)  plt.axhline(0, color='black') 

output

update

x2 = np.linspace(x[0], x[-1] + 1, len(x) * 100) 

should replaced with:

x2 = np.linspace(x[0], x[-1], len(x) * 100) 

updated output


Comments