gpt4 book ai didi

Python 和 Matplot : How can I draw a simple shape by points?

转载 作者:太空宇宙 更新时间:2023-11-03 15:08:16 25 4
gpt4 key购买 nike

我只想通过点来绘制简单的形状,像这样:

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. 如何使这些形状完整?由于我正在遍历所有点,第一个和最后一个不能连接在一起,我该怎么做?
  3. 我可以在不给出特定点顺序的情况下绘制形状吗?(类似于convex hull?)

最佳答案

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

# 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 的情况下完成它,它看起来像这样:

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

更新:

为了获得更好的多边形支持,请使用 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()

关于Python 和 Matplot : How can I draw a simple shape by points?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/30250509/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com