使用matplotlib.pyplot绘制椭圆。

33

如果这是一个愚蠢的问题,我很抱歉,但是在Python中使用matplotlib.pyplot绘制椭圆有没有简单的方法?我希望有类似于matplotlib.pyplot.arrow的东西,但我找不到任何东西。

唯一的方法是使用matplotlib.patchesdraw_artist或类似的东西吗?我希望有更简单的方法,但文档并没有提供太多帮助。


完全同意。对于如此简单的事情来说,这不是一个合理的抽象层级。 - Zackkenyon
3个回答

41
如果您不想使用补丁,可以使用椭圆的参数方程式:
x = u + a cos(t) ; y = v + b sin(t)
import numpy as np
from matplotlib import pyplot as plt
from math import pi

u=1.     #x-position of the center
v=0.5    #y-position of the center
a=2.     #radius on the x-axis
b=1.5    #radius on the y-axis

t = np.linspace(0, 2*pi, 100)
plt.plot( u+a*np.cos(t) , v+b*np.sin(t) )
plt.grid(color='lightgray',linestyle='--')
plt.show()

这给出了一个椭圆,其参数方程为:

x-oriented ellipse with parametric equation

通过二维旋转矩阵,可以旋转椭圆:

import numpy as np
from matplotlib import pyplot as plt
from math import pi, cos, sin

u=1.       #x-position of the center
v=0.5      #y-position of the center
a=2.       #radius on the x-axis
b=1.5      #radius on the y-axis
t_rot=pi/4 #rotation angle

t = np.linspace(0, 2*pi, 100)
Ell = np.array([a*np.cos(t) , b*np.sin(t)])  
     #u,v removed to keep the same center location
R_rot = np.array([[cos(t_rot) , -sin(t_rot)],[sin(t_rot) , cos(t_rot)]])  
     #2-D rotation matrix

Ell_rot = np.zeros((2,Ell.shape[1]))
for i in range(Ell.shape[1]):
    Ell_rot[:,i] = np.dot(R_rot,Ell[:,i])

plt.plot( u+Ell[0,:] , v+Ell[1,:] )     #initial ellipse
plt.plot( u+Ell_rot[0,:] , v+Ell_rot[1,:],'darkorange' )    #rotated ellipse
plt.grid(color='lightgray',linestyle='--')
plt.show()

返回值: 带参数方程的旋转椭圆

41

Matplotlib椭圆演示很好。但是我没有使用for循环就无法在我的代码中实现它。我遇到了轴图形错误。相反,这是我所做的,当然,xy中心是我的自己坐标,宽度和高度基于我绘制椭圆的图像。

from matplotlib.patches import Ellipse

plt.figure()
ax = plt.gca()

ellipse = Ellipse(xy=(157.18, 68.4705), width=0.036, height=0.012, 
                        edgecolor='r', fc='None', lw=2)
ax.add_patch(ellipse)

这段代码部分基于此页面上的第一个代码框。有关matplotlib.patches.Ellipse的链接,请参见上面Chris的回复。


2
这对于快速绘图特别有用(当您更愿意使用plt.plot/scatter等而不是创建子图轴时)。请注意,除非您设置xlim/ylim,否则很难找到演示的椭圆形;) - so860
2
亲爱的读者们:请注意,当导出到矢量格式(pdf、pgf、svg等)时,此方法(matplotlib.patches.Ellipse)会产生非常高效的代码。使用np.linspace进行暴力绘图可能会产生非常大的文件大小,这可能会减慢某些应用程序甚至触发Latex编译器中的错误。 - C-3PO

15

我本来希望能更接近标准的绘图方法,但下次我会再看看这个。谢谢! - hjweide
刚刚注意到您在寻找matplotlib.pyplot中的某些内容。很抱歉一开始没有注意到。对matplotlib.pyplot API文档进行搜索并未发现任何内容,所以恐怕您只能使用matplotlib.patches.Ellipse了。 - Chris
谢谢,看来这就是我必须要做的。我本来以为pyplot会包含一些基本的形状绘制功能,但我想人总是不能得到所有想要的东西! - hjweide
@Casper 如果你知道椭圆的起源和主/次轴,你可以简单地在轨迹上生成点。根本不需要使用补丁。 - nye17
经过仔细研究matplotlib.patches,我意识到它是最简单的解决方案。这个演示非常有帮助。 - hjweide
更新了椭圆文档的链接:http://matplotlib.org/api/patches_api.html#matplotlib.patches.Ellipse - mmdeas

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接