Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

How to connect two points of two different plots using pyplot?

I have the following code to plot two plots:

x = range(mov_x_1.shape[0])
plt.plot(x,mov_x_1)
plt.plot(x, mov_x_2)
plt.show()

getting the following result

enter image description here

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

Now I have a variable

path = [(0, 0), (1, 1), (2, 1), (3, 1), (4, 2), (5, 3), (6, 4), (6, 5), (6, 6), (6, 7), (6, 8), (7, 9), (8, 9), (9, 9), (10, 10), (11, 11), (12, 12), (13, 13), (14, 14), (15, 15), (16, 16), (17, 17), (18, 18), (19, 19)]

that contains tuple of indices. The first element is the index for mov_x_1 the second for mov_x_2.

No I want to connect each index-pair in the graph, so from one point of mov_x_1 to another point of mov_x_2. How would I do that?

>Solution :

You can use a LineCollection:

import matplotlib.pyplot as plt
from matplotlib.collections import LineCollection
import numpy as np

np.random.seed(0)
mov_x_1 = np.random.rand(20) * .1 + .5
mov_x_2 = np.random.rand(20) * .1 + .4
path = [(0, 0), (1, 1), (2, 1), (3, 1), (4, 2), (5, 3), (6, 4), (6, 5), (6, 6), (6, 7), (6, 8), (7, 9), (8, 9), (9, 9), (10, 10), (11, 11), (12, 12), (13, 13), (14, 14), (15, 15), (16, 16), (17, 17), (18, 18), (19, 19)]

x = range(mov_x_1.shape[0])
plt.plot(x,mov_x_1)
plt.plot(x, mov_x_2)

lines = [((i, mov_x_1[i]), (j, mov_x_2[j])) for (i, j) in path]
plt.gca().add_collection(LineCollection(lines, colors='k', linewidths=.5))

enter image description here

Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading