简体   繁体   中英

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

在此处输入图片说明

(I want the white triangles to be shaded as well.)

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

产量

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)

更新输出

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM