【问题标题】:How to plot and connect points in order?如何按顺序绘制和连接点?
【发布时间】:2020-08-30 04:16:27
【问题描述】:

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

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

根据图像,我可以看出点不是按顺序连接的,而且图形的形状也不是封闭的。最后两个坐标点线将允许关闭图形。

【问题讨论】:

    标签: python list matplotlib graph coordinates


    【解决方案1】:

    它通过分成 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()
    

    给予:

    【讨论】:

      【解决方案2】:

      您可以使用 zip 将元组列表解压缩为 xy 数据并执行

      x, y = zip(*shortest_route)
      
      plt.plot(x, y, '-o')
      

      【讨论】:

      • plt.plot(*zip(*shortest_route), '-o') ;-)
      • @JohanC :是的,甚至更短。我虽然更喜欢稍微明确的版本:)
      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 2022-01-09
      • 1970-01-01
      • 2021-12-09
      • 2015-08-21
      • 1970-01-01
      • 2021-10-06
      • 1970-01-01
      相关资源
      最近更新 更多