Search code examples
pythonmatplotlibrgba

matplotlib quiver:Invalid RGBA argument


I wrote this code

from scipy.ndimage import gaussian_filter

U = gaussian_filter(optflow[1][:,:,0], sigma = 10)
V = gaussian_filter(optflow[1][:,:,1], sigma = 10)
U[abs(U) < 0.5] = 0
V[abs(V) < 0.5] = 0

plt.quiver(U[::7, ::7], V[::7, ::7], scale=0.4, scale_units = 'xy', headlength = 7)

#plt.axis('off')
plt.gca().invert_yaxis()
plt.savefig('/home/RR/TEST0.png')
matplotlib.pyplot.clf()

which plot an vectorfield of this form:

My question is: how can I change the color of the arrows according their module?

I tried this:

%matplotlib inline
%pylab
from scipy.ndimage import gaussian_filter

U = gaussian_filter(optflow[1][:,:,0], sigma = 10)
V = gaussian_filter(optflow[1][:,:,1], sigma = 10)
U[abs(U) < 0.5] = 0
V[abs(V) < 0.5] = 0

M = np.sqrt(U*U+V*V)

plt.quiver(U[::7, ::7], V[::7, ::7], color = cm.inferno(M), scale=0.4, scale_units = 'xy', headlength = 7)

#plt.axis('off')
plt.gca().invert_yaxis()
plt.savefig('/home/RR7g.png')
matplotlib.pyplot.clf()

but the following error comes up.

Invalid RGBA argument

Solution

  • %matplotlib inline
    %pylab
    from scipy.ndimage import gaussian_filter
    import matplotlib.pyplot as plt
    import matplotlib.colors as mcolors
    
    U = gaussian_filter(optflow[1][:,:,0], sigma = 10)
    V = gaussian_filter(optflow[1][:,:,1], sigma = 10)
    U[abs(U) < 0.5] = 0
    V[abs(V) < 0.5] = 0
    
    M = np.sqrt(U*U+V*V)
    # cmap = plt.cm.get_cmap("inferno", 7).colors
    # colors = list((mcolors.to_hex(x) for x in cmap))
    plt.quiver(U[::7, ::7], V[::7, ::7], C=M, cmap='inferno', scale=0.4, scale_units = 'xy', headlength = 7)
    
    #plt.axis('off')
    plt.gca().invert_yaxis()
    plt.savefig('/home/roberto/workspace/TEST/OUTPUT/CORRECTIONCLEAN/TEST0.png')
    matplotlib.pyplot.clf()
    

    EDIT omitted a bracket EDIT 2 altered generator to a list EDIT 3 attempting to set color to magnitude of arrow