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.

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