Different colors for arrows on the quiver section

I am drawing a graph of arrows and my code is using an external file like this:

import numpy as np
import matplotlib.pyplot as plt
import matplotlib as mpl
from pylab import rcParams

data=np.loadtxt(r'data.dat')

x = data[:,0] 
y = data[:,1] 
u = data[:,2] 
v = data[:,3] 


plt.quiver(x, y, u, v, angles='xy', scale_units='xy', scale=1, pivot='mid',color='g')

      

The data file basically looks like this:

0 0 0 1
0 1 1 0
1 0 1 0
1 1 0 1

      

which generates a graph that looks like

enter image description here

Is there a way to plot this with different colors for different directions of the arrows?

Ps: I have a lot more arrows in my datafile in a not very logical sentence like the one I'm using as an example.

+2


source to share


1 answer


Perhaps this is the trick:

plt.quiver(x, y, u, v, np.arctan2(v, u), angles='xy', scale_units='xy', scale=1, pivot='mid',color='g')

      

Note that the fifth argument plt.quiver

is color. colored arrows


UPD. If you want to control colors you should use colormaps . Here are some examples:

Use colormap with parameter colors

:



import numpy as np
import matplotlib.pyplot as plt
import matplotlib.cm as cm
from matplotlib.colors import Normalize

%matplotlib inline

ph = np.linspace(0, 2*np.pi, 13)
x = np.cos(ph)
y = np.sin(ph)
u = np.cos(ph)
v = np.sin(ph)
colors = arctan2(u, v)

norm = Normalize()
norm.autoscale(colors)
# we need to normalize our colors array to match it colormap domain
# which is [0, 1]

colormap = cm.inferno
# pick your colormap here, refer to 
# http://matplotlib.org/examples/color/colormaps_reference.html
# and
# http://matplotlib.org/users/colormaps.html
# for details
plt.figure(figsize=(6, 6))
plt.xlim(-2, 2)
plt.ylim(-2, 2)
plt.quiver(x, y, u, v, color=colormap(norm(colors)),  angles='xy', 
           scale_units='xy', scale=1, pivot='mid')

      

different colormap

You can also stick with the fifth argument, like in my first example (which works differently from colors

), and change the default colormap to control colors.

plt.rcParams['image.cmap'] = 'Paired'

plt.figure(figsize=(6, 6))
plt.xlim(-2, 2)
plt.ylim(-2, 2)

plt.quiver(x, y, u, v, np.arctan2(v, u), angles='xy', scale_units='xy', scale=1, pivot='mid')

      

Password color palette

You can also create your own color maps, see for example here .

+7


source







All Articles