如何突出显示图中的区域以指示Python中的滑动窗口?

问题描述 投票:1回答:1

我有一个包含极端事件的时间序列,我试图使用滑动窗口方法来获得这些极端事件的宽度。我使用了代码:

def moving_window(s, length, step =1):
       streams = it.tee(s, length)
       return zip(*[it.islice(stream, i, None, step*length) for stream, i in zip(streams, it.count(step=step))])
x_=list(moving_window(s, 15))
x_=np.asarray(x_) #windows
print(x_) 

并且我有一个时间序列的输出:Zoomed in time series containing one extreme event

[[  0   1   2   3   4   5   6   7   8   9  10  11  12  13  14]
 [ 15  16  17  18  19  20  21  22  23  24  25  26  27  28  29]
 [ 30  31  32  33  34  35  36  37  38  39  40  41  42  43  44]
 [ 45  46  47  48  49  50  51  52  53  54  55  56  57  58  59]
 [ 60  61  62  63  64  65  66  67  68  69  70  71  72  73  74]
 [ 75  76  77  78  79  80  81  82  83  84  85  86  87  88  89]
 [ 90  91  92  93  94  95  96  97  98  99 100 101 102 103 104]
 [105 106 107 108 109 110 111 112 113 114 115 116 117 118 119]
 [120 121 122 123 124 125 126 127 128 129 130 131 132 133 134]
 [135 136 137 138 139 140 141 142 143 144 145 146 147 148 149]
 [150 151 152 153 154 155 156 157 158 159 160 161 162 163 164]
 [165 166 167 168 169 170 171 172 173 174 175 176 177 178 179]
 [180 181 182 183 184 185 186 187 188 189 190 191 192 193 194]]

我想用色图突出显示滑动窗口。我想要的是下图所示的内容:This contains 20 images but just consider one image.

我想知道如何使用色图来执行此操作(图像中有20个时间序列,但仅考虑一个。)。谁能帮忙?

python matplotlib plot time-series sliding-window
1个回答
1
投票

这里是使用正弦函数演示该概念的示例。 axvspan绘制垂直跨度。可以从颜色图中设置颜色。 color=0位于地图的左侧,color=1完全位于右侧。这里使用“红色”。一些对alpha和索引的实验表明,alpha=0.6和索引0.75以及降低的颜色都与给定示例中的颜色相似。

import matplotlib.pyplot as plt
import numpy as np

x_min = 0
x_max = 120
x = np.linspace(x_min, x_max, 10000)
y = np.sin(x/3)

fig, ax = plt.subplots(figsize=(12,2))
ax.plot(x, y, color='royalblue')

cmap = plt.cm.Reds # e.g. plt.cm.plasma_r or plt.cm.YlOrRd also seem interesting
current_x = 105
x_step = 16
for i in range(8):
    ax.axvspan(current_x - (i + 1) * x_step, current_x - i * x_step,
               alpha=0.6, color=cmap(0.75 - i / 20))
ax.set_xlim(x_min, x_max)
plt.tight_layout()
plt.show()

example plot

或者,可以改变alpha而不是改变颜色。在只有红色的示例中,以下内容会导致类似的结果:

for i in range(8):
    ax.axvspan(current_x - (i + 1) * x_step, current_x - i * x_step,
               alpha=0.5 - i / 20, color='red')

当然,可以同时更改alpha和颜色以进行更精细的调整。需要进行一些实验,以找到足够不同且不会尖叫太多的颜色。

[这里有cmap = plt.cm.inferno_rax.axvspan(..., alpha=0.4, color=cmap(0.8 - i / 10))的示例:

another example plot

© www.soinside.com 2019 - 2024. All rights reserved.