Python 和 Matplot:如何按点绘制简单的形状?

cqc*_*991 5 python matplotlib

我只想按点绘制简单的形状,如下所示:

import matplotlib.pyplot as plt

rectangle = [(0,0),(0,1),(1,1),(1,0)]
hexagon = [(0,0),(0,1),(1,2),(2,1),(2,0),(1,-1)]
l_shape = [(0,0),(0,3),(1,3),(1,1),(3,1),(3,0)]
concave = [(0,0),(0,3),(1,3),(1,1),(2,1),(2,3),(3,3),(3,0)]

for points in [rectangle, hexagon, l_shape, concave]:
    # 1. Can I get rid of the zip? plot directly by points 
    # 2. How can I make the shape complete?
    xs, ys = zip(*points)
    plt.plot(xs, ys, 'o')
    plt.plot(xs, ys, '-')

    automin, automax = plt.xlim()
    plt.xlim(automin-0.5, automax+0.5)
    automin, automax = plt.ylim()
    plt.ylim(automin-0.5, automax+0.5)
    # Can I display the shapes 2 in 1 line?
    plt.show()
Run Code Online (Sandbox Code Playgroud)

我的问题是 在此处输入图片说明

  1. 我怎样才能摆脱*zip?我的意思是,直接按点绘制,而不是 2 个数组。
  2. 如何制作这些形状complete?由于我循环遍历所有点,第一个和最后一个无法连接在一起,我该怎么办?
  3. 我可以在不给出特定点顺序的情况下绘制形状吗?(类似于convex hull?)

Ali*_*lik 1

下面的代码不使用临时变量xsys,而是直接元组解包。我还添加了points列表中的第一点以使形状完整。

rectangle = [(0,0),(0,1),(1,1),(1,0)]
hexagon = [(0,0),(0,1),(1,2),(2,1),(2,0),(1,-1)]
l_shape = [(0,0),(0,3),(1,3),(1,1),(3,1),(3,0)]
concave = [(0,0),(0,3),(1,3),(1,1),(2,1),(2,3),(3,3),(3,0)]

for points in [rectangle, hexagon, l_shape, concave]:
    plt.plot(*zip(*(points+points[:1])), marker='o')

    automin, automax = plt.xlim()
    plt.xlim(automin-0.5, automax+0.5)
    automin, automax = plt.ylim()
    plt.ylim(automin-0.5, automax+0.5)

    plt.show()
Run Code Online (Sandbox Code Playgroud)

提供此答案作为替代 leekaiinthesky 的帖子