2012-06-08 107 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