Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Different colours for arrows in quiver plot

I am plotting an arrow graph and my code uses an external file as follows:

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 :

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

Is there a way to plot this with different colours for the different arrow directions?

Ps.: I have got a lot more arrows in my data file in a not very logical sentence like the one I am using as example.

like image 505
Mac Avatar asked Oct 13 '16 16:10

Mac


1 Answers

This probably do 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's argument of plt.quiver is a color. colored arrows


UPD. If you want to control the colors, you have to use colormaps. Here are a couple of examples:

Use colormap with colors parameter:

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 fifth argument like in my first example (which works in a bit different way comparing with colors) and change default colormap to control the 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')

Paired colormap

You can also create your own colormaps, see e.g. here.

like image 108
Ilya V. Schurov Avatar answered Sep 19 '22 22:09

Ilya V. Schurov