用matplotlib绘制圆形

1 投票
2 回答
33380 浏览
提问于 2025-04-18 00:38

我想在一个网格上画一个圆。我的代码如下:

import pyplot as plt
from pyplot import Figure, subplot

fig=plt.figure(1)
plt.axis([0,400,0,400])
ax=fig.add_subplot(1,1,1)
circ=plt.Circle((200,200), radius=10, color='g', fill=False)
ax.add_patch(circ)
plt.show()

现在,我希望这个圆的中心能在图的中心,也就是在这个例子中是(200,200)。如果有其他情况,我希望它能根据设置的大小自动选择中心。这样可以实现吗?

为了更清楚,我想获取x轴和y轴的范围,以便找到网格的中点。我该怎么做呢?

2 个回答

0

你可能需要用到 ax.transAxes,这里有一个关于坐标转换的 教程

ax.transAxes 是指坐标轴的坐标系统;在这个系统中,(0,0) 是坐标轴的左下角,而 (1,1) 是右上角。

fig=plt.figure(1)
plt.axis([0,400,0,400])
ax=fig.add_subplot(1,1,1)
circ=plt.Circle((0.5,0.5), radius=0.2, color='g', fill=False,transform=ax.transAxes)
ax.add_patch(circ)
plt.show()

注意,半径也会被转换成坐标轴的坐标。如果你指定的半径大于 sqrt(2)/2(大约是 0.7),你在图上将看不到任何东西。

如果你想画一组圆,使用 circles 函数会简单很多,具体可以参考 这里。对于这个问题,

fig=plt.figure(1)
plt.axis([0,400,0,400])
ax=fig.add_subplot(1,1,1)
circles(0.5, 0.5, 0.2, c='g', ax=ax, facecolor='none', transform=ax.transAxes)
plt.show()

再多说一点,如果你想在图中看到一个真正的圆(而不是椭圆),你应该使用

ax=fig.add_subplot(1,1,1, aspect='equal')

或者类似的东西。

4

你的x轴和y轴的范围就在你代码的这一部分:

plt.axis([0,400,0,400])

所以你只需要稍微调整一下,像这样:

x_min = 0
x_max = 400
y_min = 0
y_max = 400

circle_x = (x_max-x_min)/2.
circle_y = (y_max-y_min)/2.

circ=plt.Circle((circle_x,circle_y), radius=10, color='g', fill=False)

如果你想从命令行获取 x_min 等参数,可以使用 sys.argv 来读取。

撰写回答