pythonmatplotlibmeshvector-space

Using plt.quiver


How to use matplotlib arrow or quiver with a list like the following:

#X, Y, U, V
data = np.array([[1, 2, 0.5, 1],
                 [2, 3, 1, 1.5],
                 [3, 4, 1.5, 1.75],
                 [4, 5, 2, 2],
                 [5, 6, 2.5, 2.5],
                 [6, 8, 3, 3],
                 [7, 9, 3.5, 3.5],
                 [8, 20, 4, 4],
                 [9, 2, 4, 4.5]])

X = data[:, 0]
Y = data[:, 1]
U = data[:, 2]
V = data[:, 3]

The aim is to draw arrows from (X,Y) to (U,V) in the same frame with Xlim, Ylim = (30,30).

The examples I see on the internet, use a mesh grid for quiver. Any hints?


Solution

  • The examples you found don't use meshgrid as a grid, but for elementwise plotting. No matter which shape the arrays have, the elements at the same positions belong together.

    import matplotlib.pyplot as plt
    import numpy as np
    
    plt.figure()
    plt.title('Arrows scale with plot width, not view')
    
    #X, Y, U, V
    data = np.array([[1, 2, 0.5, 1],
                     [2, 3, 1, 1.5],
                     [3, 4, 1.5, 1.75],
                     [4, 5, 2, 2],
                     [5, 6, 2.5, 2.5],
                     [6, 8, 3, 3],
                     [7, 9, 3.5, 3.5],
                     [8, 20, 4, 4],
                     [9, 2, 4, 4.5]])
    
    X = data[:, 0]
    Y = data[:, 1]
    
    # If you want to plot vectors starting at X,Y with components U,V
    U = data[:, 2]
    V = data[:, 3]
    
    # If you want to plot vectors starting at X,Y and ending at U,V
    U = data[:, 2] - X
    V = data[:, 3] - Y
    
    Q = plt.quiver(X, Y, U, V, units='width')
    
    plt.xlim(0, 30)
    plt.ylim(0, 30)
    
    plt.show()
    

    Next time please provide your code in a usable format.