absay absay - 1 year ago 86
Python Question

How to plot a point-to-point alignment between two sequences of datapoints?

I'm working on time series with Dynamic Time Warping. I need to plot the alignment between the datapoints of two sequences:


The length of both sequences may vary. I also have which points match, say:

[(1,1),(1,2), (2,2), (3,3), (4,3), (4,4)]

This is read as:

t[1] matches s[1]
t[1] matches s[2]
t[2] matches s[2]
t[4] matches s[4]

What I want to achieve is something like this:

enter image description here

Or even better, like this (i.e. nothing but the two sequences and their alignment):
enter image description here

I'm aware of the existence of the
pacakge though it doesn't seem to include a method to plot the alignment. I'm fairly new to plotting using Python so I'm still in the dark when it comes to matplotlib and numpy, or at least I'm not sure about the best approach to go about it using them.

Summarizing, I just need to know how to plot both sequences, one on top of the other (subplots might help, I believe?) and draw a line between each datapoint using Python.

Answer Source

You should be able to plot s and t with plt.plot. Doing the lines between them is a little trickier. I'm assuming that the x-axis corresponds to the xth element of both s and t. In that case, if the ith element of s and the jth element of t are paired, you could plot the line between them with plt.plot((i, j), (s[i], t[j]), color = 'black')

import matplotlib.pyplot as plt
#plot signals
plt.plot(y1, label = 'Signal 1')
plt.plot(y2, label = 'Signal 2')
#plot alignment
for i, j in matches:
    plt.plot((i, j), (y1[i], y2[j]), color = 'black')
Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download