使用matplotlib.pyplot(Python)绘制椭圆

问题描述 投票:13回答:3

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

使用带有draw_artist或类似功能的matplotlib.patches是唯一的方法吗?我希望有一个更简单的方法,但文档没有提供太多帮助。

谢谢你的建议!

python matplotlib ellipse
3个回答
7
投票

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


15
投票

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的链接。


8
投票

如果您不想使用补丁,可以使用椭圆的参数方程:

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

由于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

© www.soinside.com 2019 - 2024. All rights reserved.