Python& Matplot:我如何通过点绘制一个简单的形状?

时间:2015-05-15 02:20:53

标签: 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()

我的问题是 enter image description here

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

2 个答案:

答案 0 :(得分:3)

要关闭形状,只需在列表末尾再次添加第一个点:

load_from_file

load_from_stream获取x坐标列表和y坐标列表。我会说你现在这样做的方式已经是“通过点而不是2个数组”来实现它的方式。因为如果你想在没有# rectangle = [(0,0),(0,1),(1,1),(1,0)] rectangle = [(0,0),(0,1),(1,1),(1,0),(0,0)] 的情况下这样做,它将如下所示:

plt.plot

<强>更新

要获得更好的多边形支持,请使用patches模块[example]。这可能更符合您的要求。默认情况下(zip),它将为您关闭路径,它还允许您将顶点直接添加到列表(而不是两个单独的列表):

rectangleX = [0, 0, 1, 1, 0]
rectangleY = [0, 1, 1, 0, 0]
plt.plot(rectangleX, rectangleY, 'o')
plt.plot(rectangleX, rectangleY, '-')

答案 1 :(得分: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()

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