Matplotlib - Using 1-D arrays in streamplot()

前端 未结 1 1396
小蘑菇
小蘑菇 2021-01-28 16:19

So I have found two previous similar questions asked here:

How to use streamplot function when 1D data of x-coordinate, y-coordinate, x-velocity and y-velocity are avail

相关标签:
1条回答
  • 2021-01-28 16:39

    Use griddata (see also scipy.interpolate.griddata) to interpolate 1D data to a 2D grid.

    import numpy as np
    import matplotlib.pyplot as plt
    import scipy.interpolate as interpolate
    
    # lowercase variables are 1D arrays
    x = np.linspace(0, 2 * np.pi, 10)
    y = np.sin(x)
    u = np.cos(x)
    v = np.sin(x)
    
    # capitalized variables are 2D arrays
    xi = np.linspace(x.min(), x.max(), 100)
    yi = np.linspace(y.min(), y.max(), 100)
    X, Y = np.meshgrid(xi, yi)
    U = interpolate.griddata((x, y), u, (X, Y), method='cubic')
    V = interpolate.griddata((x, y), v, (X, Y), method='cubic')
    
    plt.figure()
    plt.quiver(x, y, u, v, scale_units='xy', angles='xy', scale=1.5)
    plt.streamplot(X, Y, U, V, color=U**2+V**2, linewidth=2, cmap=plt.cm.autumn)
    plt.show()
    


    import numpy as np
    import matplotlib.pyplot as plt
    import scipy.interpolate as interpolate
    
    # lowercase variables are 1D arrays
    x = np.array([1,2,3,4,5])
    y = np.array([3,1,5,1,3])
    u = np.array([1,1,0,-1,-1])
    v = np.array([-0.5,1,-1,1,-0.5])
    
    # capitalized variables are 2D arrays
    xi = np.linspace(x.min(), x.max(), 100)
    yi = np.linspace(y.min(), y.max(), 100)
    X, Y = np.meshgrid(xi, yi)
    U = interpolate.griddata((x, y), u, (X, Y), method='nearest')
    V = interpolate.griddata((x, y), v, (X, Y), method='nearest')
    
    plt.figure()
    plt.quiver(x, y, u, v, scale_units='xy', angles='xy', scale=1.5)
    plt.streamplot(X, Y, U, V, color=U**2+V**2, linewidth=2, cmap=plt.cm.autumn)
    plt.show()
    

    yields

    0 讨论(0)
提交回复
热议问题