"Continuous" colormap

If you want to cycle through N colors from a "continous" colormap, like e.g. the default viridis map, the solution by @Gerges works nicely.

import matplotlib.pyplot as plt

N = 6
plt.rcParams["axes.prop_cycle"] = plt.cycler("color", plt.cm.viridis(np.linspace(0,1,N)))

fig, ax = plt.subplots()
for i in range(N):
    ax.plot([0,1], [i, 2*i])

plt.show()

"Discrete" colormap

Matplotlib provides a few colormap that are "discrete" in the sense that they hold some low number of distinct colors for qualitative visuals, like the tab10 colormap. To cycle through such colormap, the solution might be to not use N but just port all colors of the map to the cycler.

import matplotlib.pyplot as plt

plt.rcParams["axes.prop_cycle"] = plt.cycler("color", plt.cm.tab20c.colors)

fig, ax = plt.subplots()
for i in range(15):
    ax.plot([0,1], [i, 2*i])

plt.show()

Note that only ListedColormaps have the .colors attribute, so this only works for those colormap, but not e.g. the jet map.

Combined solution

The following is a general purpose function that takes a colormap as input and outputs a corresponding cycler. I originally proposed this solution in this matplotlib issue.

from matplotlib.pyplot import cycler
import numpy as np
from matplotlib.colors import LinearSegmentedColormap, ListedColormap
import matplotlib.cm

def get_cycle(cmap, N=None, use_index="auto"):
    if isinstance(cmap, str):
        if use_index == "auto":
            if cmap in ['Pastel1', 'Pastel2', 'Paired', 'Accent',
                        'Dark2', 'Set1', 'Set2', 'Set3',
                        'tab10', 'tab20', 'tab20b', 'tab20c']:
                use_index=True
            else:
                use_index=False
        cmap = matplotlib.cm.get_cmap(cmap)
    if not N:
        N = cmap.N
    if use_index=="auto":
        if cmap.N > 100:
            use_index=False
        elif isinstance(cmap, LinearSegmentedColormap):
            use_index=False
        elif isinstance(cmap, ListedColormap):
            use_index=True
    if use_index:
        ind = np.arange(int(N)) % cmap.N
        return cycler("color",cmap(ind))
    else:
        colors = cmap(np.linspace(0,1,N))
        return cycler("color",colors)

Usage for the "continuous" case:

import matplotlib.pyplot as plt
N = 6
plt.rcParams["axes.prop_cycle"] = get_cycle("viridis", N)

fig, ax = plt.subplots()
for i in range(N):
    ax.plot([0,1], [i, 2*i])

plt.show()

Usage for the "discrete" case

import matplotlib.pyplot as plt

plt.rcParams["axes.prop_cycle"] = get_cycle("tab20c")

fig, ax = plt.subplots()
for i in range(15):
    ax.plot([0,1], [i, 2*i])

plt.show()
Answer from ImportanceOfBeingErnest on Stack Overflow
🌐
Matplotlib
matplotlib.org › stable › users › explain › artists › color_cycle.html
Styling with cycler — Matplotlib 3.11.2 documentation
Remember, a custom cycler can be set in your matplotlibrc file or a style file (style.mplstyle) under axes.prop_cycle, e.g.
🌐
Matplotlib
matplotlib.org › cycler
Composable cycles — cycler 0.12.1 documentation
January 18, 2024 - A single entry Cycler object can be used to easily cycle over a single style. To create the Cycler use the cycler() function to link a key/style/keyword argument to series of values.
🌐
GitHub
github.com › matplotlib › cycler
GitHub - matplotlib/cycler: cycler: composable cycles · GitHub
cycler: composable cycles. Contribute to matplotlib/cycler development by creating an account on GitHub.
🌐
Matplotlib
matplotlib.org › stable › gallery › color › color_cycle_default.html
Colors in the default property cycle — Matplotlib 3.11.2 documentation
matplotlib.colors.same_color · cycler.Cycler · Tags: styling: color purpose: reference plot-type: line level: beginner · Download Jupyter notebook: color_cycle_default.ipynb · Download Python source code: color_cycle_default.py · Download zipped: color_cycle_default.zip ·
🌐
Matplotlib
matplotlib.org › cycler › _modules › cycler.html
cycler — cycler 0.12.1 documentation
""" Cycler ====== Cycling through combinations of values, producing dictionaries.
Top answer
1 of 5
43

"Continuous" colormap

If you want to cycle through N colors from a "continous" colormap, like e.g. the default viridis map, the solution by @Gerges works nicely.

import matplotlib.pyplot as plt

N = 6
plt.rcParams["axes.prop_cycle"] = plt.cycler("color", plt.cm.viridis(np.linspace(0,1,N)))

fig, ax = plt.subplots()
for i in range(N):
    ax.plot([0,1], [i, 2*i])

plt.show()

"Discrete" colormap

Matplotlib provides a few colormap that are "discrete" in the sense that they hold some low number of distinct colors for qualitative visuals, like the tab10 colormap. To cycle through such colormap, the solution might be to not use N but just port all colors of the map to the cycler.

import matplotlib.pyplot as plt

plt.rcParams["axes.prop_cycle"] = plt.cycler("color", plt.cm.tab20c.colors)

fig, ax = plt.subplots()
for i in range(15):
    ax.plot([0,1], [i, 2*i])

plt.show()

Note that only ListedColormaps have the .colors attribute, so this only works for those colormap, but not e.g. the jet map.

Combined solution

The following is a general purpose function that takes a colormap as input and outputs a corresponding cycler. I originally proposed this solution in this matplotlib issue.

from matplotlib.pyplot import cycler
import numpy as np
from matplotlib.colors import LinearSegmentedColormap, ListedColormap
import matplotlib.cm

def get_cycle(cmap, N=None, use_index="auto"):
    if isinstance(cmap, str):
        if use_index == "auto":
            if cmap in ['Pastel1', 'Pastel2', 'Paired', 'Accent',
                        'Dark2', 'Set1', 'Set2', 'Set3',
                        'tab10', 'tab20', 'tab20b', 'tab20c']:
                use_index=True
            else:
                use_index=False
        cmap = matplotlib.cm.get_cmap(cmap)
    if not N:
        N = cmap.N
    if use_index=="auto":
        if cmap.N > 100:
            use_index=False
        elif isinstance(cmap, LinearSegmentedColormap):
            use_index=False
        elif isinstance(cmap, ListedColormap):
            use_index=True
    if use_index:
        ind = np.arange(int(N)) % cmap.N
        return cycler("color",cmap(ind))
    else:
        colors = cmap(np.linspace(0,1,N))
        return cycler("color",colors)

Usage for the "continuous" case:

import matplotlib.pyplot as plt
N = 6
plt.rcParams["axes.prop_cycle"] = get_cycle("viridis", N)

fig, ax = plt.subplots()
for i in range(N):
    ax.plot([0,1], [i, 2*i])

plt.show()

Usage for the "discrete" case

import matplotlib.pyplot as plt

plt.rcParams["axes.prop_cycle"] = get_cycle("tab20c")

fig, ax = plt.subplots()
for i in range(15):
    ax.plot([0,1], [i, 2*i])

plt.show()
2 of 5
35

For Matplotlib 2.2, using the cycler module will do the trick, without the need to convert to Hex values.

import cycler

n = 100
color = pyplot.cm.viridis(np.linspace(0, 1,n))
mpl.rcParams['axes.prop_cycle'] = cycler.cycler('color', color)
🌐
TutorialsPoint
tutorialspoint.com › matplotlib › matplotlib_styling_with_cycler.htm
Matplotlib - Styling with Cycler
Cycler is a separate package that is extracted from Matplotlib, and it is designed to control the style properties like color, marker, and linestyle of the plots. This tool allows you to easily cycle through different styles for plotting multiple
Find elsewhere
🌐
Matplotlib
matplotlib.org › 3.2.2 › gallery › color › color_cycler.html
Styling with cycler — Matplotlib 3.2.2 documentation
June 17, 2020 - This creates and sets # a cycler iterating simultaneously over all properties. ax1.set_prop_cycle(color=['c', 'm', 'y', 'k'], lw=[1, 2, 3, 4]) ax1.plot(yy) ax1.set_title('Set axes color cycle to cmyk') plt.show() The use of the following functions, methods, classes and modules is shown in this example: import matplotlib matplotlib.axes.Axes.plot matplotlib.axes.Axes.set_prop_cycle
🌐
Matplotlib
matplotlib.org › stable › tutorials › intermediate › color_cycle.html
Styling with cycler — Matplotlib 3.7.2 documentation
November 10, 2021 - Remember, a custom cycler can be set in your matplotlibrc file or a style file (style.mplstyle) under axes.prop_cycle:
🌐
Matplotlib
matplotlib.org › 2.1.2 › gallery › color › color_cycle.html
Styling with cycler — Matplotlib 2.1.2 documentation
Setting prop cycle on default rc parameter plt.rc('lines', linewidth=4) plt.rc('axes', prop_cycle=(cycler('color', ['r', 'g', 'b', 'y']) + cycler('linestyle', ['-', '--', ':', '-.']))) fig, (ax0, ax1) = plt.subplots(nrows=2) ax0.plot(yy) ax0.set_title('Set default color cycle to rgby') # 2. Define prop cycle for single set of axes ax1.set_prop_cycle(cycler('color', ['c', 'm', 'y', 'k']) + cycler('lw', [1, 2, 3, 4])) ax1.plot(yy) ax1.set_title('Set axes color cycle to cmyk') # Tweak spacing between subplots to prevent labels from overlapping fig.subplots_adjust(hspace=0.3) plt.show() Total running time of the script: ( 0 minutes 0.038 seconds) ... © Copyright 2002 - 2012 John Hunter, Darren Dale, Eric Firing, Michael Droettboom and the Matplotlib development team; 2012 - 2017 The Matplotlib development team.
🌐
TutorialsPoint
tutorialspoint.com › article › how-to-plot-with-multiple-color-cycle-using-cycler-property-in-matplotlib
How to plot with multiple color cycle using cycler property in Matplotlib
custom_cycler = cycler('color', ['g', 'blue', 'y', 'c']) + \ cycler('hatch', ['+*', 'xx', '+x', '+O.']) ax.set_prop_cycle(custom_cycler)
🌐
PyPI
pypi.org › project › cycler
cycler · PyPI
pip install cycler Copy PIP instructions · Docs: https://matplotlib.org/cycler/ homepage · repository · PyPI data · Data sourced directly from PyPI's database. Released: Oct 7, 2023 Latest release · PyPI data · Data sourced directly from PyPI's database.
🌐
Matplotlib
matplotlib.org › 3.5.0 › tutorials › intermediate › color_cycle.html
Styling with cycler — Matplotlib 3.5.0 documentation
November 10, 2021 - Remember, a custom cycler can be set in your matplotlibrc file or a style file (style.mplstyle) under axes.prop_cycle:
🌐
Matplotlib
matplotlib.org › 3.1.3 › gallery › color › color_cycler.html
Styling with cycler — Matplotlib 3.1.3 documentation
February 9, 2020 - This creates and sets # a cycler iterating simultaneously over all properties. ax1.set_prop_cycle(color=['c', 'm', 'y', 'k'], lw=[1, 2, 3, 4]) ax1.plot(yy) ax1.set_title('Set axes color cycle to cmyk') plt.show() The use of the following functions, methods, classes and modules is shown in this example: import matplotlib matplotlib.axes.Axes.plot matplotlib.axes.Axes.set_prop_cycle
🌐
Pythoncharts
pythoncharts.com › matplotlib › matplotlib-colors-colormaps
Python Charts - Colors and Color Maps in Matplotlib
Instead of manually specifying the color for every line, we can set a color cycler before we plot anything, and each axis will sequentially be given the next color.
Author: matplotlib
🌐
Chrisholdgraf
chrisholdgraf.com › blog › 2017 › 2017-01-04-matplotlib-cycles
Matplotlib Cyclers are Great - Welcome
cyc = plt.cycler(s=np.linspace(200, 50, 3), cmap=['viridis', 'magma', 'coolwarm'], alpha=[.25, .5, .75], lw=[0, .1, .5]) # You can print the cycler, or use nice jupyter notebook support print(cyc) cyc
🌐
GitHub
github.com › matplotlib › cycler › blob › main › test_cycler.py
cycler/test_cycler.py at main · matplotlib/cycler
cycler: composable cycles. Contribute to matplotlib/cycler development by creating an account on GitHub.
Author: matplotlib