How to avoid line color repetition in matplotlib.pyplot?

Matplotlib has more than seven colors. You can specify your color in many ways (see http://matplotlib.sourceforge.net/api/colors_api.html).

For example, you can specify the color using an html hex string:

pyplot.plot(x, y, color='#112233')

I would also suggest the use of Seaborn. With this library it is very easy to generate sequential or qualitative colour palettes with the number of colours you need. There is also a tool to visualize the palettes. For example:

import seaborn as sns

colors = sns.color_palette("hls", 4)
sns.palplot(colors)
plt.savefig("pal1.png")
colors = sns.color_palette("hls", 8)
sns.palplot(colors)
plt.savefig("pal2.png")
colors = sns.color_palette("Set2", 8)
sns.palplot(colors)
plt.savefig("pal3.png")

These are the resulting palettes:

enter image description here

enter image description here

enter image description here


The best thing if you know how many plots you are going to plot is to define the colormap before:

import matplotlib.pyplot as plt
import numpy as np

fig1 = plt.figure()
ax1 = fig1.add_subplot(111)
number_of_plots=10
colormap = plt.cm.nipy_spectral #I suggest to use nipy_spectral, Set1,Paired
ax1.set_color_cycle([colormap(i) for i in np.linspace(0, 1,number_of_plots)])
for i in range(1,number_of_plots+1):
    ax1.plot(np.array([1,5])*i,label=i)

ax1.legend(loc=2)  

Using nipy_spectral

enter image description here

Using Set1 enter image description here


For Python 3, from the solutions above you can use:

colormap = plt.cm.nipy_spectral
colors = [colormap(i) for i in np.linspace(0, 1,number_of_plots)]
ax.set_prop_cycle('color', colors)

or:

import seaborn as sns

    colors = sns.color_palette("hls", number_of_plots)
    ax.set_prop_cycle('color', colors)