步骤一:导包
import matplotlib.pyplot as plt
from dtw import dtw # python的内置dtw库
第二步:准备两组输入数据,在图像中显示为趋势相似
a = [0.0, 0.042, 0.167, 0.583, 0.208, 0.542, 0.292, 0.042, 0.083, 0.042, 0.208, 0.25, 0.208, 0.333, 0.125, 0.0]
b = [0.0, 0.058, 0.078, 0.351, 0.357, 0.604, 0.24, 0.143, 0.227, 0.188, 0.312, 0.338, 0.286, 0.37, 0.182, 0.065]
第三步:计算dtw,后面需要用到cost_matrix和path
manhattan_distance = lambda x, y: np.abs(x - y)
d, cost_matrix, acc_cost_matrix, path = dtw(a, b, dist=manhattan_distance)
查看path形状为2行19列
path = np.array(path)
path.shape #(2, 19)
第四步:将a或b其中一个数据向上平移,用做图像连接,在这里我们将a进行向上平移得到
c = [1.0, 1.042, 1.167, 1.583, 1.208, 1.542, 1.292, 1.042, 1.083, 1.042, 1.208, 1.25, 1.208, 1.333, 1.125, 1.0]
然后我们得到这样的两条线,接下来使用path为其加入连接线
第五步:使用列表的连接方式
例如有列表a=[[0, 1], [2, 3]],b=[[3, 4], [5, 6]]
那么在matplotlib中会显示坐标【0, 3】与坐标【1, 4】相连,坐标【2, 5】与坐标【3, 6】相连,我们利用这种方式进行连线,首先构造这两个列表,代码如下:
# 用于绘制连接线
xa = []
yb = []
# 连接线的连接方式, (xa[0][0], yb[0][0])连接(xa[0][1], yb[0][1])
for i in range(path.shape[1]):
xa.append([path[0][i], path[1][i]])
yb.append([c[path[0][i]], b[path[1][i]]])
第六步:绘制连接线
plt.figure(figsize=(16, 8))
plt.plot(range(16), c)
plt.plot(range(16), b)
for i in range(path.shape[1]):
plt.plot(xa[i], yb[i], 'g')
plt.scatter(xa[i], yb[i], color='g')
plt.xticks(range(0, 16))
plt.xlabel("时序", fontsize=16)
plt.ylabel("对应连接线", fontsize=16)
plt.show()
效果如下:将以上代码按顺序复制粘贴即可