Customizing Dashed Line Styles in Matplotlib

PythonPythonBeginner
Practice Now

This tutorial is from open-source community. Access the source code

Introduction

In this lab, we will learn how to customize the dashed line styles in Matplotlib. We will cover how to modify the dash sequence using .Line2D.set_dashes(), configure the dash style using a property_cycle, and set other attributes of the dash using relevant methods like ~.Line2D.set_dash_capstyle(), ~.Line2D.set_dash_joinstyle(), and ~.Line2D.set_gapcolor().

VM Tips

After the VM startup is done, click the top left corner to switch to the Notebook tab to access Jupyter Notebook for practice.

Sometimes, you may need to wait a few seconds for Jupyter Notebook to finish loading. The validation of operations cannot be automated because of limitations in Jupyter Notebook.

If you face issues during learning, feel free to ask Labby. Provide feedback after the session, and we will promptly resolve the problem for you.


Skills Graph

%%%%{init: {'theme':'neutral'}}%%%% flowchart RL python(("`Python`")) -.-> python/BasicConceptsGroup(["`Basic Concepts`"]) matplotlib(("`Matplotlib`")) -.-> matplotlib/BasicConceptsGroup(["`Basic Concepts`"]) matplotlib(("`Matplotlib`")) -.-> matplotlib/PlottingDataGroup(["`Plotting Data`"]) matplotlib(("`Matplotlib`")) -.-> matplotlib/PlotCustomizationGroup(["`Plot Customization`"]) python(("`Python`")) -.-> python/ControlFlowGroup(["`Control Flow`"]) python(("`Python`")) -.-> python/DataStructuresGroup(["`Data Structures`"]) python(("`Python`")) -.-> python/ModulesandPackagesGroup(["`Modules and Packages`"]) python(("`Python`")) -.-> python/PythonStandardLibraryGroup(["`Python Standard Library`"]) python(("`Python`")) -.-> python/DataScienceandMachineLearningGroup(["`Data Science and Machine Learning`"]) python/BasicConceptsGroup -.-> python/comments("`Comments`") matplotlib/BasicConceptsGroup -.-> matplotlib/importing_matplotlib("`Importing Matplotlib`") matplotlib/BasicConceptsGroup -.-> matplotlib/figures_axes("`Understanding Figures and Axes`") matplotlib/PlottingDataGroup -.-> matplotlib/line_plots("`Line Plots`") matplotlib/PlotCustomizationGroup -.-> matplotlib/legend_config("`Legend Configuration`") python/BasicConceptsGroup -.-> python/variables_data_types("`Variables and Data Types`") python/ControlFlowGroup -.-> python/break_continue("`Break and Continue`") python/DataStructuresGroup -.-> python/lists("`Lists`") python/DataStructuresGroup -.-> python/tuples("`Tuples`") python/ModulesandPackagesGroup -.-> python/importing_modules("`Importing Modules`") python/PythonStandardLibraryGroup -.-> python/data_collections("`Data Collections`") python/DataScienceandMachineLearningGroup -.-> python/numerical_computing("`Numerical Computing`") python/DataScienceandMachineLearningGroup -.-> python/data_visualization("`Data Visualization`") subgraph Lab Skills python/comments -.-> lab-48805{{"`Customizing Dashed Line Styles in Matplotlib`"}} matplotlib/importing_matplotlib -.-> lab-48805{{"`Customizing Dashed Line Styles in Matplotlib`"}} matplotlib/figures_axes -.-> lab-48805{{"`Customizing Dashed Line Styles in Matplotlib`"}} matplotlib/line_plots -.-> lab-48805{{"`Customizing Dashed Line Styles in Matplotlib`"}} matplotlib/legend_config -.-> lab-48805{{"`Customizing Dashed Line Styles in Matplotlib`"}} python/variables_data_types -.-> lab-48805{{"`Customizing Dashed Line Styles in Matplotlib`"}} python/break_continue -.-> lab-48805{{"`Customizing Dashed Line Styles in Matplotlib`"}} python/lists -.-> lab-48805{{"`Customizing Dashed Line Styles in Matplotlib`"}} python/tuples -.-> lab-48805{{"`Customizing Dashed Line Styles in Matplotlib`"}} python/importing_modules -.-> lab-48805{{"`Customizing Dashed Line Styles in Matplotlib`"}} python/data_collections -.-> lab-48805{{"`Customizing Dashed Line Styles in Matplotlib`"}} python/numerical_computing -.-> lab-48805{{"`Customizing Dashed Line Styles in Matplotlib`"}} python/data_visualization -.-> lab-48805{{"`Customizing Dashed Line Styles in Matplotlib`"}} end

Import the necessary libraries

First, we need to import the necessary libraries. We will be using Matplotlib and NumPy in this lab.

import matplotlib.pyplot as plt
import numpy as np

Create data for plotting

Next, we need to create some data to plot. In this lab, we will be using the sine function to create our data. We will generate 500 evenly spaced points between 0 and 10 and calculate the sine of each point using the np.sin() function.

x = np.linspace(0, 10, 500)
y = np.sin(x)

Set the line width

We can set the line width for all the lines in the plot using the plt.rc() function. In this lab, we will be setting the line width to 2.5.

plt.rc('lines', linewidth=2.5)

Create the plot

Now, we can create the plot using the plt.subplots() function. We will also create three lines using the ax.plot() function.

fig, ax = plt.subplots()

## Using set_dashes() and set_capstyle() to modify dashing of an existing line.
line1, = ax.plot(x, y, label='Using set_dashes() and set_dash_capstyle()')
line1.set_dashes([2, 2, 10, 2])  ## 2pt line, 2pt break, 10pt line, 2pt break.
line1.set_dash_capstyle('round')

## Using plot(..., dashes=...) to set the dashing when creating a line.
line2, = ax.plot(x, y - 0.2, dashes=[6, 2], label='Using the dashes parameter')

## Using plot(..., dashes=..., gapcolor=...) to set the dashing and
## alternating color when creating a line.
line3, = ax.plot(x, y - 0.4, dashes=[4, 4], gapcolor='tab:pink',
                 label='Using the dashes and gapcolor parameters')

ax.legend(handlelength=4)
plt.show()

Modify the dash sequence using .Line2D.set_dashes()

We can modify the dash sequence using .Line2D.set_dashes(). In this example, we modify the dash sequence for line1 to create a dash pattern of 2pt line, 2pt break, 10pt line, and 2pt break. We also set the cap style to 'round' using line1.set_dash_capstyle().

line1, = ax.plot(x, y, label='Using set_dashes() and set_dash_capstyle()')
line1.set_dashes([2, 2, 10, 2])  ## 2pt line, 2pt break, 10pt line, 2pt break.
line1.set_dash_capstyle('round')

Set the dash style using a property_cycle

We can configure the dash style using a property_cycle. This can be done by passing a list of dash sequences using the keyword dashes to the cycler. In this example, we will not be using this method.

Set other attributes of the dash using relevant methods

Other attributes of the dash may also be set using relevant methods like ~.Line2D.set_dash_joinstyle(), ~.Line2D.set_dash_joinstyle(), and ~.Line2D.set_gapcolor(). In this example, we will be using the dashes and gapcolor parameters to set the dash sequence and alternating color for line3.

line3, = ax.plot(x, y - 0.4, dashes=[4, 4], gapcolor='tab:pink',
                 label='Using the dashes and gapcolor parameters')

Summary

In this lab, we learned how to customize dashed line styles in Matplotlib. We covered how to modify the dash sequence using .Line2D.set_dashes(), configure the dash style using a property_cycle, and set other attributes of the dash using relevant methods like ~.Line2D.set_dash_capstyle(), ~.Line2D.set_dash_joinstyle(), and ~.Line2D.set_gapcolor(). By following these steps, you can create customized dashed line styles for your plots in Matplotlib.

Other Python Tutorials you may like