How to connect two points of two different plots using pyplot?
Question:
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
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?
Answers:
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))
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
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?
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))