LarrySnyder610
LarrySnyder610

Reputation: 2397

How to avoid gaps with matplotlib.fill_between and where

I want to fill the area between two curves but only when the lower curve is >0. I'm using fill_between() in matplotlib with a where condition (to test which curve is greater) and numpy.maximum() (to test whether the lower curve is >0). But there are gaps in the fill because the lower curve crosses the x-axis between integers while the result of the maximum hits the x-axis at an integer. How can I fix this?

import numpy as np
import matplotlib.pyplot as plt

x = np.arange(0, 10)
a = 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 the white triangles to be shaded as well.)

Upvotes: 2

Views: 1995

Answers (1)

falsetru
falsetru

Reputation: 369094

By interpolating values using numpy.interp:

import numpy as np
import matplotlib.pyplot as plt

x = np.arange(0, 10)
a = 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 be replaced with:

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

updated output

Upvotes: 3

Related Questions