![](/img/trans.png)
[英]How to control dashes of the edge in matplotlib fill_between function?
[英]matplotlib how to fill_between step function
我正在嘗試對輸入信號高(值 = 1)的繪圖區域進行着色。 該區域應保持陰影直到信號變低(值 = 0)。 我已經非常接近了,以下是一些示例:http ://matplotlib.org/examples/pylab_examples/axhspan_demo.html 在 matplotlib 圖中,我可以突出顯示特定的 x 值范圍嗎? 如何在 Python 中使用 Matplotlib 繪制階躍函數?
問題是現在它只在信號 = 1 的地方直接着色,而不是到信號 = 0 的下一個變化(階躍函數)。 例如,在下面的圖像/代碼中,我希望將繪圖填充在 20-40 和 50-60 之間(而不是 20-30,以及低於 40 的峰值)。 如何修改我的代碼以實現這一目標? 謝謝。
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)
在 ax.fill_between 中使用“step = 'pre'
ax.fill_between(x, ymin, ymax, where=s>0, facecolor='green',step='pre', alpha=0.5)
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.