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
cyclerfrom thecyclermodule. - Setting
axes.prop_cycleincorrectly, such as assigning a list of colors directly instead of acyclerobject. - 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
cyclerfromcyclermodule. - 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.