如何按顺序绘制和连接点?

时间:2020-05-13 19:53:03

标签: python list matplotlib graph coordinates

我有一个按特定顺序排列的坐标列表。

shortest_route = [(2, 8), (2, 8), (1, 3), (0, 2), (0, 0), (6, 1), (9, 3), (8, 4), (7, 4), (6, 4), (2, 8)]

我正在尝试绘制坐标点并按此顺序连接它们。我的想法是使用for循环遍历列表,然后逐个绘制坐标点,然后将它们与直线连接。

for g in shortest_route:
    print(g)
    plt.plot(x, y, '-o')
plt.show()

enter image description here

根据图像,我可以知道各点没有按顺序连接,并且图形的形状没有封闭。最后两个坐标点线将允许图形被关闭。

2 个答案:

答案 0 :(得分:2)

通过将x和y分开,它对我有用,见下文:

import matplotlib.pyplot as plt

shortest_route = [(2, 8), (2, 8), (1, 3), (0, 2), (0, 0), (6, 1), (9, 3), (8, 4), (7, 4), (6, 4), (2, 8)]

x = [point[0] for point in shortest_route]
y = [point[1] for point in shortest_route]

plt.plot(x, y)
plt.show()

给予:

enter image description here

答案 1 :(得分:1)

您可以使用x将元组列表解压缩为yzip数据,然后执行

x, y = zip(*shortest_route)

plt.plot(x, y, '-o')

enter image description here