[英]matplotlib how to fill_between step function
I am trying to shade regions of a plot where an input signal is high (value = 1).我正在尝试对输入信号高(值 = 1)的绘图区域进行着色。 The region should remain shaded until the signal goes low (value = 0).
该区域应保持阴影直到信号变低(值 = 0)。 I have gotten pretty close, following a number of examples:http://matplotlib.org/examples/pylab_examples/axhspan_demo.html In a matplotlib plot, can I highlight specific x-value ranges?
我已经非常接近了,以下是一些示例:http ://matplotlib.org/examples/pylab_examples/axhspan_demo.html 在 matplotlib 图中,我可以突出显示特定的 x 值范围吗? How do I plot a step function with Matplotlib in Python?
如何在 Python 中使用 Matplotlib 绘制阶跃函数?
The problem is that right now it is only shading directly under where the signal = 1, rather than to the next change to signal = 0 (step function).问题是现在它只在信号 = 1 的地方直接着色,而不是到信号 = 0 的下一个变化(阶跃函数)。 For example, in the image / code below, I would like the plot to be filled between 20-40 and 50-60 (rather than 20-30, and a spike under 40).
例如,在下面的图像/代码中,我希望将绘图填充在 20-40 和 50-60 之间(而不是 20-30,以及低于 40 的峰值)。 How can I modify my code to achieve this?
如何修改我的代码以实现这一目标? Thanks.
谢谢。
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()
Define a generator giving the intervals to fill. 定义一个生成器,给出填充的间隔。
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))
The use this to get the intervals to fill in. 使用它来获取填写的间隔。
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)
Use "step = 'pre' in ax.fill_between在 ax.fill_between 中使用“step = 'pre'
ax.fill_between(x, ymin, ymax, where=s>0, facecolor='green',step='pre', alpha=0.5) ax.fill_between(x, ymin, ymax, where=s>0, facecolor='green',step='pre', alpha=0.5)
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.