matplotlib 如何使用pyplot连接两个不同图的两个点?

rsl1atfo  于 2023-02-23  发布在  其他
关注(0)|答案(1)|浏览(128)

我有以下代码来绘制两个地块:

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

得到以下结果

现在我有一个变量

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)]

它包含索引元组。第一个元素是mov_x_1的索引,第二个元素是mov_x_2的索引。
不,我想连接图中的每个索引对,从mov_x_1的一个点到mov_x_2的另一个点,我该怎么做?

abithluo

abithluo1#

您可以使用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))

相关问题