- Matplotlib Basics
- Matplotlib - Home
- Matplotlib - Introduction
- Matplotlib - Vs Seaborn
- Matplotlib - Environment Setup
- Matplotlib - Anaconda distribution
- Matplotlib - Jupyter Notebook
- Matplotlib - Pyplot API
- Matplotlib - Simple Plot
- Matplotlib - Saving Figures
- Matplotlib - Markers
- Matplotlib - Figures
- Matplotlib - Styles
- Matplotlib - Legends
- Matplotlib - Colors
- Matplotlib - Colormaps
- Matplotlib - Colormap Normalization
- Matplotlib - Choosing Colormaps
- Matplotlib - Colorbars
- Matplotlib - Text
- Matplotlib - Text properties
- Matplotlib - Subplot Titles
- Matplotlib - Images
- Matplotlib - Image Masking
- Matplotlib - Annotations
- Matplotlib - Arrows
- Matplotlib - Fonts
- Matplotlib - What are Fonts?
- Setting Font Properties Globally
- Matplotlib - Font Indexing
- Matplotlib - Font Properties
- Matplotlib - Scales
- Matplotlib - Linear and Logarthmic Scales
- Matplotlib - Symmetrical Logarithmic and Logit Scales
- Matplotlib - LaTeX
- Matplotlib - What is LaTeX?
- Matplotlib - LaTeX for Mathematical Expressions
- Matplotlib - LaTeX Text Formatting in Annotations
- Matplotlib - PostScript
- Enabling LaTex Rendering in Annotations
- Matplotlib - Mathematical Expressions
- Matplotlib - Animations
- Matplotlib - Artists
- Matplotlib - Styling with Cycler
- Matplotlib - Paths
- Matplotlib - Path Effects
- Matplotlib - Transforms
- Matplotlib - Ticks and Tick Labels
- Matplotlib - Radian Ticks
- Matplotlib - Dateticks
- Matplotlib - Tick Formatters
- Matplotlib - Tick Locators
- Matplotlib - Basic Units
- Matplotlib - Autoscaling
- Matplotlib - Reverse Axes
- Matplotlib - Logarithmic Axes
- Matplotlib - Symlog
- Matplotlib - Unit Handling
- Matplotlib - Ellipse with Units
- Matplotlib - Spines
- Matplotlib - Axis Ranges
- Matplotlib - Axis Scales
- Matplotlib - Axis Ticks
- Matplotlib - Formatting Axes
- Matplotlib - Axes Class
- Matplotlib - Twin Axes
- Matplotlib - Figure Class
- Matplotlib - Multiplots
- Matplotlib - Grids
- Matplotlib - Object-oriented Interface
- Matplotlib - PyLab module
- Matplotlib - Subplots() Function
- Matplotlib - Subplot2grid() Function
- Matplotlib - Anchored Artists
- Matplotlib - Manual Contour
- Matplotlib - Coords Report
- Matplotlib - AGG filter
- Matplotlib - Ribbon Box
- Matplotlib - Fill Spiral
- Matplotlib - Findobj Demo
- Matplotlib - Hyperlinks
- Matplotlib - Image Thumbnail
- Matplotlib - Plotting with Keywords
- Matplotlib - Create Logo
- Matplotlib - Multipage PDF
- Matplotlib - Multiprocessing
- Matplotlib - Print Stdout
- Matplotlib - Compound Path
- Matplotlib - Sankey Class
- Matplotlib - MRI with EEG
- Matplotlib - Stylesheets
- Matplotlib - Background Colors
- Matplotlib - Basemap
- Matplotlib Event Handling
- Matplotlib - Event Handling
- Matplotlib - Close Event
- Matplotlib - Mouse Move
- Matplotlib - Click Events
- Matplotlib - Scroll Event
- Matplotlib - Keypress Event
- Matplotlib - Pick Event
- Matplotlib - Looking Glass
- Matplotlib - Path Editor
- Matplotlib - Poly Editor
- Matplotlib - Timers
- Matplotlib - Viewlims
- Matplotlib - Zoom Window
- Matplotlib Plotting
- Matplotlib - Bar Graphs
- Matplotlib - Histogram
- Matplotlib - Pie Chart
- Matplotlib - Scatter Plot
- Matplotlib - Box Plot
- Matplotlib - Violin Plot
- Matplotlib - Contour Plot
- Matplotlib - 3D Plotting
- Matplotlib - 3D Contours
- Matplotlib - 3D Wireframe Plot
- Matplotlib - 3D Surface Plot
- Matplotlib - Quiver Plot
- Matplotlib Useful Resources
- Matplotlib - Quick Guide
- Matplotlib - Useful Resources
- Matplotlib - Discussion
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 −
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 −
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 −