python - matplotlib 如何填充_between 步骤函数

标签 python matplotlib

我正在尝试遮蔽输入信号较高(值 = 1)的绘图区域。该区域应保持阴影,直到信号变低(值 = 0)。我已经非常接近了,下面是一些例子: http://matplotlib.org/examples/pylab_examples/axhspan_demo.html In a matplotlib plot, can I highlight specific x-value ranges? How do I plot a step function with Matplotlib in Python?

问题是现在它只是直接在 signal = 1 下着色,而不是 next 更改为 signal = 0(步进函数)。例如,在下面的图像/代码中,我希望绘图填充在 20-40 和 50-60 之间(而不是 20-30,峰值低于 40)。我怎样才能修改我的代码来实现这个目标?谢谢。 output plot showing incorrect shading

import numpy as np
import matplotlib.pyplot as plt

x = np.array([0,10,20,30,40,50,60])
s = np.array([0,0,1,1,0,1,0])
t = np.array([25,24,25,25,24,25,24])

fig, ax = plt.subplots()

ax.plot(x,t)
ax.step(x,s,where='post')

# xmin xmax ymin ymax
plt.axis([0,60,0,30])

ymin, ymax = plt.ylim()
# want this to fill until the next "step"
# i.e. should be filled between 20-40; 50-60
ax.fill_between(x, ymin, ymax, where=s>0, facecolor='green', alpha=0.5)

plt.show()

最佳答案

定义一个生成器,给出要填充的间隔。

def customFilter(s):
    foundStart = False
    for i, val in enumerate(s):
        if not foundStart and val == 1:
            foundStart = True
            start = i
        if foundStart and val == 0:
            end = i
            yield (start, end+1)
            foundStart = False
    if foundStart:
        yield (start, len(s))  

使用它来获取要填充的间隔。

for start, end in customFilter(s):
    print 1
    mask = np.zeros_like(s)
    mask[start: end] = 1
    ax.fill_between(x, ymin, ymax, where=mask, facecolor='green', alpha=0.5)

关于python - matplotlib 如何填充_between 步骤函数,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/20913347/

相关文章:

python - 与 uwsgi 和 websockets 紧密联系

使用 Glade 的 Python GTK ListView

python - 如何使用水平投影清理二进制图像?

python - 如何在 Python Matplotlib 中绘制具有不同时间间隔的两个数据集并让它们共享轴

python - 在 matplotlib 中显示张量图像

python - 如何为 2D 直方图选择自定义 bin 大小?

python - 在Python中的图形上创建框

python - Boost.Python 因静态库而失败

python - 使用 Django ORM 从相关表中获取数据

python - 帮助使大的子图看起来更好更清晰