如何按顺序绘制和连接点?
How to plot and connect points in order?
我有一个按特定顺序排列的坐标列表。
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()
根据图像,我可以看出点没有按顺序连接,图形的形状也没有闭合。最后两个坐标点线将允许关闭图形。
它通过分成 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()
给出:
您可以使用 zip
和 do
将元组列表解压缩为 x
和 y
数据
x, y = zip(*shortest_route)
plt.plot(x, y, '-o')
我有一个按特定顺序排列的坐标列表。
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()
根据图像,我可以看出点没有按顺序连接,图形的形状也没有闭合。最后两个坐标点线将允许关闭图形。
它通过分成 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()
给出:
您可以使用 zip
和 do
x
和 y
数据
x, y = zip(*shortest_route)
plt.plot(x, y, '-o')