How to cycle through both colours and linestyles on a matplotlib figure?

To cycle through both colors and linestyles on a matplotlib figure, you can use the cycler module to combine multiple style properties. This creates automatic cycling through different combinations of colors and line styles for each plot.

Steps

  • Import matplotlib and the cycler module

  • Set up figure parameters using rcParams

  • Configure the property cycle with cycler() for colors and linestyles

  • Plot multiple data series using plot() method

  • Display the figure using show() method

Example

import matplotlib.pyplot as plt
from cycler import cycler

# Set the figure size
plt.rcParams["figure.figsize"] = [7.00, 3.50]
plt.rcParams["figure.autolayout"] = True

# Set the rcParams with color and linestyle cycling
plt.rc('axes', prop_cycle=(cycler('color', ['r', 'g', 'b', 'y']) +
                          cycler('linestyle', [':', '-.', '-', '--'])))

# Plot multiple data series
plt.plot([0, 5, 2, 1], label='Series 1')
plt.plot([2, 6, 3, 1], label='Series 2') 
plt.plot([3, 8, 5, 1], label='Series 3')
plt.plot([4, 9, 0, 3], label='Series 4')

plt.legend()
plt.title('Cycling Through Colors and Linestyles')
plt.show()

How It Works

The cycler function creates a cycle object that automatically rotates through specified values. When you add two cyclers with +, matplotlib combines them to create all possible combinations. In this example:

  • Series 1: red (:) dotted line

  • Series 2: green (-.) dash-dot line

  • Series 3: blue (-) solid line

  • Series 4: yellow (--) dashed line

Alternative Approach

You can also cycle through combinations by multiplying cyclers instead of adding them ?

import matplotlib.pyplot as plt
from cycler import cycler

plt.rcParams["figure.figsize"] = [8.00, 4.00]

# Multiply cyclers to get all combinations
colors = ['red', 'blue', 'green']
styles = ['-', '--', ':']
plt.rc('axes', prop_cycle=(cycler('color', colors) * cycler('linestyle', styles)))

# Plot multiple series to see all combinations
for i in range(6):
    plt.plot([0, 1, 2, 3], [i, i+1, i+0.5, i+2], label=f'Line {i+1}')

plt.legend()
plt.title('All Color-Linestyle Combinations')
plt.show()

Conclusion

Use cycler with + to cycle through properties sequentially, or * to create all possible combinations. This provides automatic styling for multiple plot series without manual specification.

---
Updated on: 2026-03-26T14:57:57+05:30

2K+ Views

Kickstart Your Career

Get certified by completing the course

Get Started
Advertisements