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

2024-10-01 07:26:54 发布

您现在位置:Python中文网/ 问答频道 /正文

我只想用点来画简单的形状,像这样:

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?)在

Tags: theplotpltzippoints形状shapexs
2条回答

下面的代码不使用临时变量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()

提供这个答案作为另一个LeekaiInsky的帖子

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

# rectangle = [(0,0),(0,1),(1,1),(1,0)]
rectangle = [(0,0),(0,1),(1,1),(1,0),(0,0)]

plt.plot获取x坐标列表和y坐标列表。我想说,你现在的做法已经是“用点而不是2个数组”来做。因为如果您想不使用zip进行操作,它将如下所示:

^{pr2}$

更新:

为了更好地支持多边形,请使用patches模块[example]。这可能更符合你所寻找的。默认情况下(closed = True),它将为您关闭路径,还允许您直接向列表(而不是两个单独的列表)添加顶点:

import matplotlib.pyplot as plt
import matplotlib.patches as mpatches

rectangle = [(0,0),(0,1),(1,1),(1,0)]

fig, ax = plt.subplots()
ax.add_patch(mpatches.Polygon(rectangle))

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

相关问题 更多 >