0
0
MatplotlibHow-ToBeginner ยท 3 min read

How to Set Color Cycle in Matplotlib for Custom Plot Colors

To set the color cycle in matplotlib, use plt.rcParams['axes.prop_cycle'] with a cycler object specifying your colors. This changes the default sequence of colors used for multiple plot lines automatically.
๐Ÿ“

Syntax

Use plt.rcParams['axes.prop_cycle'] = cycler(color=[list_of_colors]) to set the color cycle globally. The cycler function creates a cycle of colors that matplotlib uses for plotting multiple lines.

  • plt.rcParams: A dictionary to set default matplotlib settings.
  • axes.prop_cycle: The property controlling the color cycle.
  • cycler(color=[...]): Defines the list of colors to cycle through.
python
from matplotlib import pyplot as plt
from cycler import cycler

plt.rcParams['axes.prop_cycle'] = cycler(color=['red', 'green', 'blue'])
๐Ÿ’ป

Example

This example shows how to set a custom color cycle and plot multiple lines. Each line will use the next color in the cycle automatically.

python
from matplotlib import pyplot as plt
from cycler import cycler
import numpy as np

# Set custom color cycle
plt.rcParams['axes.prop_cycle'] = cycler(color=['#FF5733', '#33FF57', '#3357FF'])

x = np.linspace(0, 10, 100)

plt.plot(x, np.sin(x), label='sin(x)')
plt.plot(x, np.cos(x), label='cos(x)')
plt.plot(x, np.tan(x)/10, label='tan(x)/10')  # scaled to avoid large values

plt.legend()
plt.title('Plot with Custom Color Cycle')
plt.show()
Output
A plot window showing three lines: sin(x) in orange-red, cos(x) in bright green, and tan(x)/10 in bright blue, each with a legend label.
โš ๏ธ

Common Pitfalls

Common mistakes when setting color cycles include:

  • Not importing cycler from the cycler module.
  • Setting axes.prop_cycle incorrectly, such as assigning a list of colors directly instead of a cycler object.
  • Expecting the color cycle to apply retroactively to existing plots; it only affects plots created after the setting.

Always set the color cycle before plotting.

python
from matplotlib import pyplot as plt

# Wrong way: assigning list directly
plt.rcParams['axes.prop_cycle'] = ['red', 'green', 'blue']  # This will cause an error

# Right way:
from cycler import cycler
plt.rcParams['axes.prop_cycle'] = cycler(color=['red', 'green', 'blue'])
๐Ÿ“Š

Quick Reference

Summary tips for setting color cycle in matplotlib:

  • Import cycler from cycler module.
  • Set plt.rcParams['axes.prop_cycle'] = cycler(color=[...]) before plotting.
  • Use hex color codes or color names in the list.
  • The cycle applies to all subsequent plots until changed again.
โœ…

Key Takeaways

Use plt.rcParams['axes.prop_cycle'] with cycler(color=[...]) to set the color cycle.
Always import cycler from the cycler module before setting the color cycle.
Set the color cycle before creating plots to see the effect.
You can use color names or hex codes in the color list.
The color cycle applies globally until changed again.