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

标签 python matplotlib plot time-series sliding-window

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

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 个时间序列,但只考虑一个。)。谁能帮忙?

最佳答案

这是一个使用正弦函数来演示概念的示例。 axvspan 绘制垂直跨度。颜色可以从颜色图中设置。 color=0 会在 map 的左边,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

关于python - 如何突出显示图中的区域以指示 Python 中的滑动窗口?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/59665563/

相关文章:

python - 在 python 列表理解中解包元组(不能使用 *-operator)

python - 如何将 NumPy 数组标准化到一定范围内?

python - 在 Python 中按数字阈值排序的有效方法?

python - 将列表列表中的特定元素从字符串转换为整数

r - 在 purrr::map 函数中获取迭代名称

python - 如何在 python 中绘制半对数图?

python - 在 matplotlib 2.1.0 上绘制平均值和标准差

python用样条曲线关闭两条曲线

matlab - 从法线和点绘制 3D 表面

python - 高效的 Matplotlib 重绘