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.
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.
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')
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')
You can also create your own colormaps, see e.g. here.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With