How to get N easily distinguishable colors with Matplotlib

Question:

I need to make different amounts of line plots with Matplotlib, but I have not been able to find a colormap that makes it easy to distinguish between the line plots.
I have used the brg colormap like this:

colors=brg(np.linspace(0,1,num_plots))

with

for i in range(num_plots):
    ax.step(x,y,c=colors[i])

With four plots, this could look like this:

Notice how hard it is to distinguish the colors of the top and bottom plots, which is especially bad if a legend is used.
I’ve tried a lot of different colormaps like rainbow and jet, but with this setup, brg seems to give the best result for num_plots between 1 and 12.

I did find this How to get 10 different colors that are easily recognizable and this Wiki page Help:Distinguishable colors, but I don’t know if this can be used in any way..

Is there an easy fix to this, or will I have to make do with this?

Asked By: Anders BB

||

Answers:

I would use the tab10 or tab20 colormaps. See Colormap reference

enter image description here

However, I believe you will always have trouble distinguishing hues when the number of lines becomes large (I would say >5 and certainly >10).
In this case, you should combine hues with other distinguishing features like different markers or linestyles.

colors = matplotlib.cm.tab20(range(20))
markers = matplotlib.lines.Line2D.markers.keys()
x = np.linspace(0,1,100)

fig, axs = plt.subplots(2,4, figsize=(4*4,4*2))
for nlines,ax0 in zip(np.arange(5,21,5), axs.T):
    ax0[0].set_title('{:d} lines'.format(nlines))
    for n,c,m in zip(range(nlines),colors,markers):
        y = x*np.random.random()+np.random.random()
        ax0[0].plot(x,y)
        ax0[1].plot(x,y, marker=m, markevery=10)
axs[0,0].set_ylabel('only hues', fontsize=16, fontweight='bold')
axs[1,0].set_ylabel('hues+markers', fontsize=16, fontweight='bold')
fig.tight_layout()

enter image description here

Answered By: Diziet Asahi
Categories: questions Tags: , , ,
Answers are sorted by their score. The answer accepted by the question owner as the best is marked with
at the top-right corner.