Matplotlib Line Styles

MatplotlibMatplotlibBeginner
Practice Now

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

Introduction

Matplotlib is a powerful data visualization tool for Python. One of its features is the ability to create custom line styles for plots. In this lab, we will learn how to create and use different line styles in Matplotlib.

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`"]) python(("`Python`")) -.-> python/FileHandlingGroup(["`File Handling`"]) 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/FunctionsGroup(["`Functions`"]) 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`") python/FileHandlingGroup -.-> python/with_statement("`Using with Statement`") 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/line_styles_colors("`Customizing Line Styles and Colors`") matplotlib/PlotCustomizationGroup -.-> matplotlib/text_annotations("`Text Annotations`") python/BasicConceptsGroup -.-> python/variables_data_types("`Variables and Data Types`") python/BasicConceptsGroup -.-> python/booleans("`Booleans`") python/ControlFlowGroup -.-> python/for_loops("`For Loops`") python/DataStructuresGroup -.-> python/lists("`Lists`") python/DataStructuresGroup -.-> python/tuples("`Tuples`") python/FunctionsGroup -.-> python/function_definition("`Function Definition`") 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`") python/FunctionsGroup -.-> python/build_in_functions("`Build-in Functions`") subgraph Lab Skills python/comments -.-> lab-48809{{"`Matplotlib Line Styles`"}} python/with_statement -.-> lab-48809{{"`Matplotlib Line Styles`"}} matplotlib/importing_matplotlib -.-> lab-48809{{"`Matplotlib Line Styles`"}} matplotlib/figures_axes -.-> lab-48809{{"`Matplotlib Line Styles`"}} matplotlib/line_plots -.-> lab-48809{{"`Matplotlib Line Styles`"}} matplotlib/line_styles_colors -.-> lab-48809{{"`Matplotlib Line Styles`"}} matplotlib/text_annotations -.-> lab-48809{{"`Matplotlib Line Styles`"}} python/variables_data_types -.-> lab-48809{{"`Matplotlib Line Styles`"}} python/booleans -.-> lab-48809{{"`Matplotlib Line Styles`"}} python/for_loops -.-> lab-48809{{"`Matplotlib Line Styles`"}} python/lists -.-> lab-48809{{"`Matplotlib Line Styles`"}} python/tuples -.-> lab-48809{{"`Matplotlib Line Styles`"}} python/function_definition -.-> lab-48809{{"`Matplotlib Line Styles`"}} python/importing_modules -.-> lab-48809{{"`Matplotlib Line Styles`"}} python/data_collections -.-> lab-48809{{"`Matplotlib Line Styles`"}} python/numerical_computing -.-> lab-48809{{"`Matplotlib Line Styles`"}} python/data_visualization -.-> lab-48809{{"`Matplotlib Line Styles`"}} python/build_in_functions -.-> lab-48809{{"`Matplotlib Line Styles`"}} end

Import the required libraries

To use Matplotlib, we first need to import the library. We will also import the NumPy library to generate some sample data for our plots.

import matplotlib.pyplot as plt
import numpy as np

Define line styles

There are different ways to define line styles in Matplotlib. We can use predefined styles such as 'solid', 'dashed', 'dotted', and 'dashdot'. We can also define custom line styles using a dash tuple.

linestyle_str = [
     ('solid', 'solid'),      ## Same as (0, ()) or '-'
     ('dotted', 'dotted'),    ## Same as (0, (1, 1)) or ':'
     ('dashed', 'dashed'),    ## Same as '--'
     ('dashdot', 'dashdot')]  ## Same as '-.'

linestyle_tuple = [
     ('loosely dotted',        (0, (1, 10))),
     ('dotted',                (0, (1, 1))),
     ('densely dotted',        (0, (1, 1))),
     ('long dash with offset', (5, (10, 3))),
     ('loosely dashed',        (0, (5, 10))),
     ('dashed',                (0, (5, 5))),
     ('densely dashed',        (0, (5, 1))),

     ('loosely dashdotted',    (0, (3, 10, 1, 10))),
     ('dashdotted',            (0, (3, 5, 1, 5))),
     ('densely dashdotted',    (0, (3, 1, 1, 1))),

     ('dashdotdotted',         (0, (3, 5, 1, 5, 1, 5))),
     ('loosely dashdotdotted', (0, (3, 10, 1, 10, 1, 10))),
     ('densely dashdotdotted', (0, (3, 1, 1, 1, 1, 1)))]

Create a function to plot line styles

We can create a function to plot the different line styles. The function takes an axis object, a list of line styles, and a title as input parameters.

def plot_linestyles(ax, linestyles, title):
    X, Y = np.linspace(0, 100, 10), np.zeros(10)
    yticklabels = []

    for i, (name, linestyle) in enumerate(linestyles):
        ax.plot(X, Y+i, linestyle=linestyle, linewidth=1.5, color='black')
        yticklabels.append(name)

    ax.set_title(title)
    ax.set(ylim=(-0.5, len(linestyles)-0.5),
           yticks=np.arange(len(linestyles)),
           yticklabels=yticklabels)
    ax.tick_params(left=False, bottom=False, labelbottom=False)
    ax.spines[:].set_visible(False)

    for i, (name, linestyle) in enumerate(linestyles):
        ax.annotate(repr(linestyle),
                    xy=(0.0, i), xycoords=ax.get_yaxis_transform(),
                    xytext=(-6, -12), textcoords='offset points',
                    color="blue", fontsize=8, ha="right", family="monospace")

Create the plot

We can create the plot by calling the plot_linestyles function for each set of line styles.

fig, (ax0, ax1) = plt.subplots(2, 1, figsize=(10, 8), height_ratios=[1, 3])

plot_linestyles(ax0, linestyle_str[::-1], title='Named linestyles')
plot_linestyles(ax1, linestyle_tuple[::-1], title='Parametrized linestyles')

plt.tight_layout()
plt.show()

Interpret the plot

The resulting plot shows the different line styles. The top plot shows named line styles while the bottom plot shows parametrized line styles. The annotations on the right side show the dash tuples used for each line style.

Summary

In this lab, we learned how to create and use different line styles in Matplotlib. We defined line styles using predefined styles and dash tuples. We also created a function to plot the different line styles and interpreted the resulting plot.

Other Matplotlib Tutorials you may like