Python 绘制圆-matplotlib
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/22755826/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
Plotting a circle-matplotlib
提问by Prakhar Mohan Srivastava
I am trying to plot a circle on a grid. The code that I have written is as follows:
我正在尝试在网格上绘制一个圆圈。我写的代码如下:
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()
Now, I want the center of the circle to be the center of the graph, that is, (200,200)in this example. In case of other cases I want it to automatically choose the centre depending on the size that us set. Can this be in some way?
现在,我希望圆的中心是图形的中心,即本例中的(200,200)。在其他情况下,我希望它根据我们设置的大小自动选择中心。这可以以某种方式吗?
To make it clearer I want to get the x-axis and the y-axis range so as to find the mid point of the grid. How do I proceed?
为了更清楚,我想获得 x 轴和 y 轴范围,以便找到网格的中点。我该如何进行?
回答by Prakhar Mohan Srivastava
Your x-axis and y-axis ranges are in your code right here:
您的 x 轴和 y 轴范围在您的代码中:
plt.axis([0,400,0,400])
So all you would need is leverage on this a bit like so:
所以你所需要的只是利用这个有点像这样:
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)
If you want to catch x_min
etc. from the command prompt then read out sys.argv
.
如果你想x_min
从命令提示符中捕捉等,然后读出sys.argv
.
回答by Syrtis Major
What you want may be ax.transAxes
, here's the tutorialfor coordinates transformation.
你想要的可能是ax.transAxes
,这里是坐标转换的教程。
ax.transAxes
means the coordinate system of the Axes; (0,0) is bottom left of the axes, and (1,1) is top right of the axes.
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()
Note that the radius is also transformed into Axes coordinate. If you specify a radius larger than sqrt(2)/2 (about 0.7) you will see nothing in the plot.
请注意,半径也转换为轴坐标。如果您指定的半径大于 sqrt(2)/2(大约 0.7),您将在图中看不到任何内容。
If you want to plot a set of circles, it would be much simpler if you use the function circles
here. For this problem,
如果要绘制一组圆,使用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()
A bit more, if you want see a real circle (instead of an ellipse) in your figure, you should use
多一点,如果你想在你的图中看到一个真正的圆(而不是一个椭圆),你应该使用
ax=fig.add_subplot(1,1,1, aspect='equal')
or something like that.
或类似的东西。