Issue
I am trying to shade regions of a plot where an input signal is high (value = 1). The region should remain shaded until the signal goes low (value = 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? How do I plot a step function with Matplotlib in Python?
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). 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). 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()
Solution
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)
Answered By - M4rtini
0 comments:
Post a Comment
Note: Only a member of this blog may post a comment.