matplotlib图表中的阴影区域

时间:2018-06-06 14:12:13

标签: python numpy 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之间自动遮蔽图表的垂直切片(从下到上)?

正弦只是这里的一个样本,情节的实际值不那么规律。

我看过FIll between two vertical lines in matplotlib,它看起来与这个问题相似,但是那里的答案会隐藏固定x值之间的区域。我希望阴影区域由y值决定。

2 个答案:

答案 0 :(得分:2)

您可能正在寻找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()

enter image description here

答案 1 :(得分:0)

你可以使用ax.axvspan,这显然是你想要的。为了获得更好的效果,请将alpha值设置为低于0.5,并可选择设置颜色和边缘颜色/宽度。

fig, ax = plt.subplots()
ax.plot(s)
ax.set(xlabel='time (s)', ylabel='voltage (mV)', title='sine')
ax.axvspan(0.75, 1.25, alpha=0.2)
ax.grid()
plt.show()

如果您希望阴影处于不同的方向(水平而不是垂直),还有ax.axhspan方法。

相关问题