2012-06-08 114 views
9

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

使用matplotlib.patches与draw_artist或类似的东西来做到这一点的唯一方法是?我希望有一个更简单的方法,但文档不提供太多帮助。

感谢您的任何建议!

回答

7

你见过matplotlib ellipse demo?在这里他们使用matplotlib.patches.Ellipse

+0

我希望有更接近标准绘图方法的东西,但接下来我会研究它。谢谢! – casper

+0

只是注意到你正在寻找matplotlib.pyplot中的东西。对不起,没有注意到,开始。对'matplotlib.pyplot' API文档的搜索没有透露任何内容,所以恐怕你必须忍受使用'matplotlib.patches.Ellipse' – Chris

+0

谢谢,这似乎是我必须做的。我希望pyplot包含一些基本的形状绘图功能,但我想一个人不能拥有一切! – casper

10

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) 

此代码部分基于this page上的第一个代码框。请参阅Chris的上述回复链接至matplotlib.patches.Ellipse

0

如果你不想使用patche,你可以使用椭圆的参数方程:x = u + a.cos(t); Y = V + b.sin(吨)

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 椭圆可以旋转多亏了2D-旋转矩阵:

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() 

返回: rotated ellipse with parametric equation