Drawing directions fields

后端 未结 3 1255
予麋鹿
予麋鹿 2021-02-04 06:23

Is there a way to draw direction fields in python?

My attempt is to modify http://www.compdigitec.com/labs/files/slopefields.py giving

#!/usr/bin/python
         


        
3条回答
  •  自闭症患者
    2021-02-04 06:24

    You can use this matplotlib code as a base. Modify it for your needs. I have updated the code to show same length arrows. The important option is to set the angles option of the quiver function, so that the arrows are correctly printed from (x,y) to (x+u,y+v) (instead of the default, which just takes into account of (u,v) when computing the angles).

    It is also possible to change the axis form "boxes" to "arrows". Let me know if you need that change and I could add it.

    import matplotlib.pyplot as plt
    from scipy.integrate import odeint
    import numpy as np
    
    fig = plt.figure()
    
    def vf(x, t):
        dx = np.zeros(2)
        dx[0] = 1.0
        dx[1] = x[0] ** 2 - x[0] - 2.0
        return dx
    
    
    # Solution curves
    t0 = 0.0
    tEnd = 10.0
    
    # Vector field
    X, Y = np.meshgrid(np.linspace(-5, 5, 20), np.linspace(-10, 10, 20))
    U = 1.0
    V = X ** 2 - X - 2
    # Normalize arrows
    N = np.sqrt(U ** 2 + V ** 2)
    U = U / N
    V = V / N
    plt.quiver(X, Y, U, V, angles="xy")
    
    t = np.linspace(t0, tEnd, 100)
    for y0 in np.linspace(-5.0, 0.0, 10):
        y_initial = [y0, -10.0]
        y = odeint(vf, y_initial, t)
        plt.plot(y[:, 0], y[:, 1], "-")
    
    plt.xlim([-5, 5])
    plt.ylim([-10, 10])
    plt.xlabel(r"$x$")
    plt.ylabel(r"$y$")
    

提交回复
热议问题