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

hjw*_*ide 14 python matplotlib ellipse

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

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

谢谢你的建议!

max*_*x29 17

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)
Run Code Online (Sandbox Code Playgroud)

此代码部分基于此页面上的第一个代码框.请参阅Chris上面的回复,获取链接matplotlib.patches.Ellipse.

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

jea*_*nej 9

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

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()
Run Code Online (Sandbox Code Playgroud)

这使 : 带参数方程的x方向椭圆

椭圆可以通过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()
Run Code Online (Sandbox Code Playgroud)

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


Chr*_*ris 7

你看过matplotlib椭圆演示吗?他们在这里使用matplotlib.patches.Ellipse.