Creating a Plot With Matplotlib

PythonPythonBeginner
Practice Now

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

Introduction

This lab will guide you through creating a plot with Python Matplotlib. Matplotlib is a plotting library for the Python programming language. In this lab, you will learn how to customize a plot's properties including colors, line widths, and more.

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 matplotlib(("`Matplotlib`")) -.-> matplotlib/BasicConceptsGroup(["`Basic Concepts`"]) matplotlib(("`Matplotlib`")) -.-> matplotlib/AdvancedTopicsGroup(["`Advanced Topics`"]) python(("`Python`")) -.-> python/BasicConceptsGroup(["`Basic Concepts`"]) python(("`Python`")) -.-> python/ControlFlowGroup(["`Control Flow`"]) python(("`Python`")) -.-> python/DataStructuresGroup(["`Data Structures`"]) python(("`Python`")) -.-> python/ModulesandPackagesGroup(["`Modules and Packages`"]) python(("`Python`")) -.-> python/DataScienceandMachineLearningGroup(["`Data Science and Machine Learning`"]) python(("`Python`")) -.-> python/FunctionsGroup(["`Functions`"]) matplotlib/BasicConceptsGroup -.-> matplotlib/importing_matplotlib("`Importing Matplotlib`") matplotlib/BasicConceptsGroup -.-> matplotlib/figures_axes("`Understanding Figures and Axes`") matplotlib/AdvancedTopicsGroup -.-> matplotlib/matplotlib_config("`Customizing Matplotlib Configurations`") python/BasicConceptsGroup -.-> python/booleans("`Booleans`") python/ControlFlowGroup -.-> python/conditional_statements("`Conditional Statements`") python/ControlFlowGroup -.-> python/for_loops("`For Loops`") python/DataStructuresGroup -.-> python/lists("`Lists`") python/DataStructuresGroup -.-> python/tuples("`Tuples`") python/DataStructuresGroup -.-> python/dictionaries("`Dictionaries`") python/ModulesandPackagesGroup -.-> python/importing_modules("`Importing Modules`") 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 matplotlib/importing_matplotlib -.-> lab-48606{{"`Creating a Plot With Matplotlib`"}} matplotlib/figures_axes -.-> lab-48606{{"`Creating a Plot With Matplotlib`"}} matplotlib/matplotlib_config -.-> lab-48606{{"`Creating a Plot With Matplotlib`"}} python/booleans -.-> lab-48606{{"`Creating a Plot With Matplotlib`"}} python/conditional_statements -.-> lab-48606{{"`Creating a Plot With Matplotlib`"}} python/for_loops -.-> lab-48606{{"`Creating a Plot With Matplotlib`"}} python/lists -.-> lab-48606{{"`Creating a Plot With Matplotlib`"}} python/tuples -.-> lab-48606{{"`Creating a Plot With Matplotlib`"}} python/dictionaries -.-> lab-48606{{"`Creating a Plot With Matplotlib`"}} python/importing_modules -.-> lab-48606{{"`Creating a Plot With Matplotlib`"}} python/numerical_computing -.-> lab-48606{{"`Creating a Plot With Matplotlib`"}} python/data_visualization -.-> lab-48606{{"`Creating a Plot With Matplotlib`"}} python/build_in_functions -.-> lab-48606{{"`Creating a Plot With Matplotlib`"}} end

Import necessary modules

First, we need to import the necessary modules. In this case, we need to import matplotlib.pyplot and numpy.

import matplotlib.pyplot as plt
import numpy as np

Define the property cycle and retrieve colors

Next, we need to define the property cycle and retrieve the colors from it.

prop_cycle = plt.rcParams['axes.prop_cycle']
colors = prop_cycle.by_key()['color']

Define line widths

Now, we define the line widths for our plot.

lwbase = plt.rcParams['lines.linewidth']
thin = lwbase / 2
thick = lwbase * 3

Create subplots

We create a 2x2 grid of subplots.

fig, axs = plt.subplots(nrows=2, ncols=2, sharex=True, sharey=True)

Add horizontal and vertical lines

Now, we add horizontal and vertical lines to each subplot using the colors from the property cycle.

for icol in range(2):
    if icol == 0:
        lwx, lwy = thin, lwbase
    else:
        lwx, lwy = lwbase, thick
    for irow in range(2):
        for i, color in enumerate(colors):
            axs[irow, icol].axhline(i, color=color, lw=lwx)
            axs[irow, icol].axvline(i, color=color, lw=lwy)

Customize subplots

We customize the subplots by setting the background color of the bottom subplots to black, setting the x-axis ticks, and adding a title to each subplot.

axs[1, icol].set_facecolor('k')
axs[1, icol].xaxis.set_ticks(np.arange(0, 10, 2))
axs[0, icol].set_title(f'line widths (pts): {lwx:g}, {lwy:g}',
                       fontsize='medium')

Customize y-axis ticks

We customize the y-axis ticks for the leftmost subplots.

for irow in range(2):
    axs[irow, 0].yaxis.set_ticks(np.arange(0, 10, 2))

Add title to plot

We add a title to the entire plot.

fig.suptitle('Colors in the default prop_cycle', fontsize='large')

Display the plot

Finally, we display the plot.

plt.show()

Summary

In this lab, we learned how to create a plot with Python Matplotlib. We customized the properties of the plot including colors and line widths. We also learned how to create subplots and customize their appearance.

Other Python Tutorials you may like