如何避免与matplotlib.fill_between和哪里之间的差距 [英] How to avoid gaps with matplotlib.fill_between and where

查看:112
本文介绍了如何避免与matplotlib.fill_between和哪里之间的差距的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我只想填充两条曲线之间的区域,但仅当下部曲线> 0时才填充. 我正在matplotlib中的fill_between()中使用where条件(以测试哪个曲线较大)和numpy.maximum()(以测试下部曲线是否为> 0).但是填充中存在间隙,因为较低的曲线与整数之间的x轴相交,而maximum的结果在整数上与x轴相等.我该如何解决?

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

推荐答案

通过使用 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')

更新

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

应替换为:

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

这篇关于如何避免与matplotlib.fill_between和哪里之间的差距的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆