作为标题,我正在致力于时间序列对齐,而可视化的对齐结果是需要的。
为此,我想画线连接“锚点”所产生的对齐算法。
np.random.seed(5)
x = np.random.rand(10) # time-series 1
y = np.random.rand(20) # time-series 2
ap = np.array(([0, 4, 9], # the anchor points
[0, 9, 19]))
fig = plt.figure(figsize=(10,5))
ax1 = fig.add_subplot(211)
ax2 = fig.add_subplot(212)
ax1.plot(x, 'r')
ax2.plot(y, 'g')示例中的锚点ap指定两个时间序列的索引和y之间的一对一“映射”,即x[0]对应于y[0];x[4]对应于y[9];以及x[9]到y[19]。目标是在两个单独的图之间画线,以显示对齐的结果。
发布于 2017-05-18 10:48:11
要连接matplotlib中的两个子图,可以使用ConnectionPatch。
import numpy as np
import matplotlib.pyplot as plt
from matplotlib.patches import ConnectionPatch
np.random.seed(5)
x = np.random.rand(21) # time-series 1
y = np.random.rand(21) # time-series 2
ap = np.array(([0, 5, 10], # the anchor points
[0,10, 20]))
fig = plt.figure(figsize=(10,5))
ax1 = fig.add_subplot(211)
ax2 = fig.add_subplot(212)
ax1.plot(x, 'r')
ax2.plot(y, 'g')
ls = ["-","--"]
c = ["gold", "blue"]
for i, row in enumerate(ap):
for j, ind in enumerate(row):
px = (ind, x[ind])
py = (ind, y[ind])
con = ConnectionPatch(py,px, coordsA="data", coordsB="data",
axesA=ax2, axesB=ax1, linestyle=ls[i], color=c[i])
ax2.add_artist(con)
plt.show()

发布于 2017-05-19 03:42:35
由于@ImportanceOfBeingErnest,我识别了OP中的错误,并在两个不同长度的系列之间实现了连接索引:
np.random.seed(5)
x = np.random.rand(10)
y = np.random.rand(20)
ap = np.array(([0, 4, 9],
[0,9, 19]))
fig = plt.figure(figsize=(10,5))
ax1 = fig.add_subplot(211)
ax2 = fig.add_subplot(212, sharex=ax1)
ax1.plot(x, 'r')
ax2.plot(y, 'g')
plt.setp(ax1.get_xticklabels(), visible=False)
for j in ap.T:
ax1.axvline(x=j[0], linestyle='--', color='k')
ax2.axvline(x=j[1], linestyle='--', color='k')
x_ind = (j[0], ax1.get_ylim()[0])
y_ind = (j[1], ax2.get_ylim()[1])
con = ConnectionPatch(y_ind, x_ind, coordsA="data", coordsB="data",
axesA=ax2, axesB=ax1, linewidth='1.5')
ax2.add_artist(con)

我知道这不是话题,但如何进一步截断空白部分,使x轴的范围与信号长度相适应,同时保持两个信号长度的实际比值?虽然sharex=ax1显示了信号长度的比例,但顶部图形右侧的空白部分是令人讨厌的。
https://stackoverflow.com/questions/44045344
复制相似问题