gpt4 book ai didi

python - 用 pyplot 画一个圆

转载 作者:IT老高 更新时间:2023-10-28 12:32:03 26 4
gpt4 key购买 nike

令人惊讶的是,我没有找到关于如何使用 matplotlib.pyplot(请不要使用 pylab)作为输入中心(x,y)和半径 r 绘制圆的直接描述。我尝试了一些变体:

import matplotlib.pyplot as plt
circle=plt.Circle((0,0),2)
# here must be something like circle.plot() or not?
plt.show()

...但仍然无法正常工作。

最佳答案

您需要将其添加到坐标区。一个 CirclePatch 的子类, axesadd_patch方法。 (您也可以使用add_artist,但不推荐。)

这是一个这样做的例子:

import matplotlib.pyplot as plt

circle1 = plt.Circle((0, 0), 0.2, color='r')
circle2 = plt.Circle((0.5, 0.5), 0.2, color='blue')
circle3 = plt.Circle((1, 1), 0.2, color='g', clip_on=False)

fig, ax = plt.subplots() # note we must use plt.subplots, not plt.subplot
# (or if you have an existing figure)
# fig = plt.gcf()
# ax = fig.gca()

ax.add_patch(circle1)
ax.add_patch(circle2)
ax.add_patch(circle3)

fig.savefig('plotcircles.png')

结果如下图:

第一个圆位于原点,但默认情况下 clip_onTrue,因此当圆超出 axes。第三个(绿色)圆圈显示当您不剪辑 Artist 时会发生什么。它超出坐标轴(但不超出图形,即图形大小不会自动调整以绘制所有艺术家)。

默认情况下,x、y 和半径的单位对应于数据单位。在这种情况下,我没有在我的轴上绘制任何东西(fig.gca() 返回当前轴),并且由于从未设置过限制,它们默认为 x 和 y 范围0 到 1。

下面是示例的延续,展示了单位的重要性:

circle1 = plt.Circle((0, 0), 2, color='r')
# now make a circle with no fill, which is good for hi-lighting key results
circle2 = plt.Circle((5, 5), 0.5, color='b', fill=False)
circle3 = plt.Circle((10, 10), 2, color='g', clip_on=False)

ax = plt.gca()
ax.cla() # clear things for fresh plot

# change default range so that new circles will work
ax.set_xlim((0, 10))
ax.set_ylim((0, 10))
# some data
ax.plot(range(11), 'o', color='black')
# key data point that we are encircling
ax.plot((5), (5), 'o', color='y')

ax.add_patch(circle1)
ax.add_patch(circle2)
ax.add_patch(circle3)
fig.savefig('plotcircles2.png')

导致:

您可以看到我如何将第二个圆圈的填充设置为 False,这对于包围关键结果(如我的黄色数据点)很有用。

关于python - 用 pyplot 画一个圆,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/9215658/

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