I am plotting multiple lines on a single plot and I want them to run through the spectrum of a colormap, not just the same 6 or 7 colors. The code is akin to this:
for i in range(20):
for k in range(100):
y[k] = i*x[i]
plt.plot(x,y)
plt.show()
Both with colormap "jet" and another that I imported from seaborn, I get the same 7 colors repeated in the same order. I would like to be able to plot up to ~60 different lines, all with different colors.
The Matplotlib colormaps accept an argument (
0..1
, scalar or array) which you use to get colors from a colormap. For example:Gives you an array with (two) RGBA colors:
You can use that to create
N
different colors:If you are using continuous color pallets like brg, hsv, jet or the default one then you can do like this:
Now you can pass this color value to any API you want like this:
Bart's solution is nice and simple but has two shortcomings.
plt.colorbar()
won't work in a nice way because the line plots aren't mappable (compared to, e.g., an image)It can be slow for large numbers of lines due to the for loop (though this is maybe not a problem for most applications?)
These issues can be addressed by using
LineCollection
. However, this isn't too user-friendly in my (humble) opinion. There is an open suggestion on GitHub for adding a multicolor line plot function, similar to theplt.scatter(...)
function.Here is a working example I was able to hack together
Here is a very simple example:
Produces:
And something a little more sophisticated:
Produces:
Hope this helps!
An anternative to Bart's answer, in which you do not specify the color in each call to
plt.plot
is to define a new color cycle withset_prop_cycle
. His example can be translated into the following code (I've also changed the import of matplotlib to the recommended style):