Use a colourmap to change line colour
-
23-12-2019 - |
Question
I have a lot of different files (10-20) that I read in x and y data from, then plot as a line. At the moment I have the standard colors but I would like to use a colormap instead. I have looked at many different examples but can't get the adjustment for my code right. I would like the colour to change between each line (rather than along the line) using a colormap such as gist_rainbow i.e. a discrete colourmap The image below is what I can currently achieve.
This is what I have attempted:
import pylab as py
import numpy as np
import matplotlib.pyplot as plt
from matplotlib import rc, rcParams
numlines = 20
for i in np.linspace(0,1, numlines):
color1=plt.cm.RdYlBu(1)
color2=plt.cm.RdYlBu(2)
# Extract and plot data
data = np.genfromtxt('OUZ_QRZ_Lin_Disp_Curves')
OUZ_QRZ_per = data[:,1]
OUZ_QRZ_gvel = data[:,0]
plt.plot(OUZ_QRZ_per,OUZ_QRZ_gvel, '--', color=color1, label='OUZ-QRZ')
data = np.genfromtxt('PXZ_WCZ_Lin_Disp_Curves')
PXZ_WCZ_per = data[:,1]
PXZ_WCZ_gvel = data[:,0]
plt.plot(PXZ_WCZ_per,PXZ_WCZ_gvel, '--', color=color2, label='PXZ-WCZ')
# Lots more files will be plotted in the final code
py.grid(True)
plt.legend(loc="lower right",prop={'size':10})
plt.savefig('Test')
plt.show()
Solution
You could take a few different approaches. On your initial example you color each line specifically with a different color. That works fine if you are able to loop over the data/colors you want to plot. Manually assigning each color, like you do now, is a lot of work, even for 20 lines, but imagine if you have hundred or more. :)
Matplotlib also allows you to edit the default 'color cycle' with your own colors. Consider this example:
numlines = 10
data = np.random.randn(150, numlines).cumsum(axis=0)
plt.plot(data)
This gives the default behavior, and results in:
If you want to use a default Matplotlib colormap, you can use it to retrieve the colors values.
# pick a cmap
cmap = plt.cm.RdYlBu
# get the colors
# if you pass floats to a cmap, the range is from 0 to 1,
# if you pass integer, the range is from 0 to 255
rgba_colors = cmap(np.linspace(0,1,numlines))
# the colors need to be converted to hexadecimal format
hex_colors = [mpl.colors.rgb2hex(item[:3]) for item in rgba_colors.tolist()]
You can then assign the list of colors to the color cycle
setting from Matplotlib.
mpl.rcParams['axes.color_cycle'] = hex_colors
Any plot made after this change will automatically cycle through these colors:
plt.plot(data)