Search code examples
pythonmatplotlibcolors

matplotlib: specify default colors explicitly


When I do

ax.plot(...)
ax.plot(...)
...

the color of each successive plot is in the default color cycle (blue, orange, green &c).

Alas, sometimes I need to specify the colors explicitly in each call to ax.plot because each logical plot is generated by several such calls.

So, suppose I need to plot num_plots curves, and I want the color selection to be identical to the default one.

How do I get the list of colors that matplotlib would use if I call ax.plot exactly num_plots times?

I tried

import matplotlib.cm as colormaps
colors = colormaps.get_cmap(None, num_plots)(np.linspace(0,1,num_plots))

(and various names like "Accent" and "winter" instead of None that appear in the error message when I use random junk instead of None).


Solution

  • I am not sure if I understand your question correclty, but it seems like you are asking for the default color cycle which can be found here. You say that

    @JodyKlymak: but then if I have many plots, some of them will be in the same color. I don't think this happens when I do not specify the color explicitly.

    This is not a correct assumption. It is a color cycle, so the colors will repeat.

    import matplotlib.pyplot as plt
    
    num_plots = 20
    for i in range(num_plots):
        plt.plot([0,1], [(i+1)/num_plots, (i+1)/num_plots])
    
    plt.show()
    

    enter image description here

    If you want to cycle through the colors manually, just get the list of default colors and use the modulo operator as follows.

    import matplotlib.pyplot as plt
    
    prop_cycle = plt.rcParams['axes.prop_cycle']
    colors = prop_cycle.by_key()['color']
    
    num_plots = 20
    
    for i in range(num_plots):
        plt.plot([0,1], [(i+1)/num_plots, (i+1)/num_plots], color=colors[i % len(colors)])
    
    plt.show()