Plot Ellipse with matplotlib.pyplot (Python)

后端 未结 3 749
后悔当初
后悔当初 2021-02-01 19:02

Sorry if this is a stupid question, but is there an easy way to plot an ellipse with matplotlib.pyplot in Python? I was hoping there would be something similar to

3条回答
  •  太阳男子
    2021-02-01 19:31

    If you do not want to use a patch, you can use the parametric equation of an ellipse:

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

    Which gives:

    The ellipse can be rotated thanks to a 2D-rotation matrix :

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

    Returns:

提交回复
热议问题