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 lines on a single axis.

Importing the Cycler − To start using Cycler, you need to import it into your Python script.

from cycler import cycler

This enables you to create and manipulate Cyclers for styling your plots.

Creating a Cycler − The cycler function is used to create a new Cycler object. It can be called with a single positional argument, a pair of positional arguments, or a combination of keyword arguments.

# Creating a color Cycler
color_cycle = cycler(color=['r', 'g', 'b'])

The "color_cycle" is a Cycler object that cycles through the colors red, green, and blue. Once you have a Cycler, you can link it to the matplotlib’s plot attribute.

Cycling Through Multiple Properties

The Cycler package provides advanced operations for combining and manipulating multiple Cyclers to create complex style variations. It means that you can add cyclers together or multiply them to combine different properties.

Following are the different operations in cycler −

  • Cycler Addition − Multiple Cycler objects can be combined using the + operator. For example −
cycler(color=['r', 'g', 'b']) + cycler(linestyle=['-', '--', ':'])
  • Cycler Multiplication − Cyclers can be multiplied to create a wider range of unique styles. For example:
cycler(color=['r', 'g', 'b']) * cycler(linestyle=['-', '--', ':'])
  • Integer Multiplication − Cycler objects can be multiplied by integer values to increase their length. Both cycler * 2 and 2 * cycler yield the same result, repeating the elements. Here is the syntax:
color_cycle * 2
  • Cycler Concatenation − Cycler objects can be concatenated using the Cycler.concat() method or the top-level concat() function.

In this tutorial, we will explore two distinct approaches for customizing the style of plots in Matplotlib using the Cycler package.

  • Setting Default Property Cycle (rc parameter) − This is the global setting that ensures that every subsequent plot will be set to the specified style.
  • Setting Property Cycle for a Single Pair of Axes − This is the local setting that applies a custom property cycle exclusively to a particular set of axes.

Setting Default Property Cycle (rc parameter)

In matplotlib, specifying a default style for all future plots will be possible by using matplotlib.pyplot.rc() method, this will set the default cycler for lines in your plots and axes. This means every plot you make in the future will follow this color and linestyle cycle unless you override it.

Example 1

This is a basic example that demonstrates how to cycle through different line styles for multiple plots. Here the plt.rc() method is used to set the default linestyle for the plot.

import matplotlib.pyplot as plt 
from cycler import cycler 

# Set the property cycle for the linestyle of lines in the axes
linestyle_cycler = cycler('linestyle', ['-', ':', '-.']) 
plt.rc('axes', prop_cycle=linestyle_cycler) 

# Create multiple plots using a loop
for i in range(5): 
   x = range(i, i + 5)     
   plt.plot(range(5), x)

# Display the plot
plt.legend(['first', 'second', 'third', 'fourth', 'fifth'], loc='upper left', fancybox=True, shadow=True) 
plt.show()

Output

On executing the above code we will get the following output −

Basic Example 1

Let’s combine multiple (color and a linestyle) cyclers together by adding (+) symbol to them.

Example 2

This example demonstrates how to define a default style (cycle through both colors and linestyles) for your plots using Cycler, making it easy to visualize all plots with different colors ('r', 'g', 'b', 'y') and linestyles ('-', '--', ':', '-.').

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

# Generate sample data
x = np.linspace(0, 2 * np.pi, 50)
offsets = np.linspace(0, 2 * np.pi, 4, endpoint=False)
yy = np.transpose([np.sin(x + phi) for phi in offsets])

# Set default prop_cycle
default_cycler = (cycler(color=['r', 'g', 'b', 'y']) +
   cycler(linestyle=['-', '--', ':', '-.']))
plt.rc('lines', linewidth=4)
plt.rc('axes', prop_cycle=default_cycler)

# Plot with the default color cycle
plt.plot(yy)
plt.title('Set Default Color Cycle')
plt.show()

Output

On executing the above code we will get the following output −

Styling with Cycler Example 1

Setting Property Cycle for a Single Pair of Axes

Customize the style for a specific pair of axes within a figure without affecting others. you use the matplotlib.axes.Axes.set_prop_cycle() to apply this custom cycler. This means that only the plots on this particular set of axes will follow the specified color and linewidth cycle.

Example

In this example, the first set of plots on ax0 follows the default color and linestyle cycle. The second set of plots on ax1 uses a custom color and linewidth cycle defined specifically for this axis using the set_prop_cycle() method.

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

# Generate sample data 
x = np.linspace(0, 2 * np.pi, 50)
offsets = np.linspace(0, 2 * np.pi, 4, endpoint=False)
yy = np.transpose([np.sin(x + phi) for phi in offsets])

# Define a default cycler for colors and linestyles
default_cycler = (cycler(color=['r', 'g', 'b', 'y']) +
   cycler(linestyle=['-', '--', ':', '-.']))

# Set the default linewidth for lines in all plots
plt.rc('lines', linewidth=4)

# Set the default property cycle for axes to the default cycler
plt.rc('axes', prop_cycle=default_cycler)

# Create a figure and two axes
fig, (ax0, ax1) = plt.subplots(nrows=2, figsize=(7, 8))

# Plot on the first axis using the default color cycle
ax0.plot(yy)
ax0.set_title('Default Color Cycle: rgby')

# Define a custom cycler 
custom_cycler = (cycler(color=['c', 'm', 'y', 'k']) +
   cycler(lw=[1, 2, 3, 4]))

# Set the custom property cycle for the second axis
ax1.set_prop_cycle(custom_cycler)

# Plot on the second axis using the custom color and linewidth cycle
ax1.plot(yy)
ax1.set_title('Custom Color Cycle: cmyk')

# Add space between the two plots
fig.subplots_adjust(hspace=0.3)

# Show the plots
plt.show()

Output

On executing the above code we will get the following output −

styling_with_cycler_ex2
Advertisements