首页 > 解决方案 > matplotlib 图表中感兴趣的阴影区域

问题描述

给定一个像

import matplotlib
import matplotlib.pyplot as plt
import numpy as np
t = np.arange(0.0, 2.0, 0.01)
s = 1 + np.sin(2 * np.pi * t)
fig, ax = plt.subplots()
ax.plot(s)
ax.set(xlabel='time (s)', ylabel='voltage (mV)', title='sine')
ax.grid()
plt.show()

如何自动对图表的 y 值介于(例如)1.25 和 0.75 之间的图表的垂直切片(从底部到顶部)进行着色?

正弦在这里只是一个样本,绘图的实际值不太规则。

在 matplotlib 的两条垂直线之间看到了 FIll,它看起来类似于这个问题,但那里的答案在固定 x 值之间隐藏了一个区域。我希望阴影区域由 y 值确定。

标签: pythonnumpymatplotlib

解决方案


您可能正在寻找ax.fill_between,它非常灵活(请参阅链接文档)。

对于您的具体情况,如果我理解正确,这应该足够了:

fig, ax = plt.subplots()
ax.plot(s)
ax.set(xlabel='time (s)', ylabel='voltage (mV)', title='sine')
ax.fill_between(range(len(s)), min(s), max(s), where=(s < 1.25) & (s > 0.75), alpha=0.5)
ax.grid()

在此处输入图像描述


推荐阅读