Create Customized Matplotlib Visualizations

PythonPythonBeginner
Practice Now

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

Introduction

In this tutorial, we will learn how to create and customize plots using Matplotlib. Matplotlib is a Python library that provides a wide range of tools for creating static, animated, and interactive visualizations in Python.

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/FileHandlingGroup(["`File Handling`"]) matplotlib(("`Matplotlib`")) -.-> matplotlib/BasicConceptsGroup(["`Basic Concepts`"]) matplotlib(("`Matplotlib`")) -.-> matplotlib/PlottingDataGroup(["`Plotting Data`"]) matplotlib(("`Matplotlib`")) -.-> matplotlib/PlotCustomizationGroup(["`Plot Customization`"]) 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/PythonStandardLibraryGroup(["`Python Standard Library`"]) python(("`Python`")) -.-> python/DataScienceandMachineLearningGroup(["`Data Science and Machine Learning`"]) python(("`Python`")) -.-> python/FunctionsGroup(["`Functions`"]) 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/grid_config("`Grid Configuration`") python/BasicConceptsGroup -.-> python/variables_data_types("`Variables and Data Types`") python/ControlFlowGroup -.-> python/for_loops("`For Loops`") python/DataStructuresGroup -.-> python/lists("`Lists`") python/DataStructuresGroup -.-> python/tuples("`Tuples`") python/DataStructuresGroup -.-> python/sets("`Sets`") 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/with_statement -.-> lab-48838{{"`Create Customized Matplotlib Visualizations`"}} matplotlib/importing_matplotlib -.-> lab-48838{{"`Create Customized Matplotlib Visualizations`"}} matplotlib/figures_axes -.-> lab-48838{{"`Create Customized Matplotlib Visualizations`"}} matplotlib/line_plots -.-> lab-48838{{"`Create Customized Matplotlib Visualizations`"}} matplotlib/grid_config -.-> lab-48838{{"`Create Customized Matplotlib Visualizations`"}} python/variables_data_types -.-> lab-48838{{"`Create Customized Matplotlib Visualizations`"}} python/for_loops -.-> lab-48838{{"`Create Customized Matplotlib Visualizations`"}} python/lists -.-> lab-48838{{"`Create Customized Matplotlib Visualizations`"}} python/tuples -.-> lab-48838{{"`Create Customized Matplotlib Visualizations`"}} python/sets -.-> lab-48838{{"`Create Customized Matplotlib Visualizations`"}} python/importing_modules -.-> lab-48838{{"`Create Customized Matplotlib Visualizations`"}} python/data_collections -.-> lab-48838{{"`Create Customized Matplotlib Visualizations`"}} python/numerical_computing -.-> lab-48838{{"`Create Customized Matplotlib Visualizations`"}} python/data_visualization -.-> lab-48838{{"`Create Customized Matplotlib Visualizations`"}} python/build_in_functions -.-> lab-48838{{"`Create Customized Matplotlib Visualizations`"}} end

Importing Matplotlib and NumPy Libraries

The first step is to import the libraries. We will be using the pyplot module from Matplotlib and the numpy library.

import matplotlib.pyplot as plt
import numpy as np

Creating a Figure and Subplots

The next step is to create a figure and subplots. We will create a figure with two subplots side by side using the subplots function.

fig, (ax0, ax1) = plt.subplots(ncols=2, figsize=(7, 4))

Setting the Aspect Ratio and Plotting Data

Now, we will set the aspect ratio of the first subplot to 1 using the set_aspect function and plot some data using the plot function.

ax0.set_aspect(1)
ax0.plot(np.arange(10))

Customizing Axis Labels

To customize the axis labels, we can use the set_xlabel and set_ylabel functions. We can also add newlines using the "\n" character.

ax0.set_xlabel('this is a xlabel\n(with newlines!)')
ax0.set_ylabel('this is vertical\ntest', multialignment='center')

Adding Text to the Plot

We can add text to the plot using the text function. We can specify the position, rotation, horizontal and vertical alignment, and multialignment of the text.

ax0.text(2, 7, 'this is\nyet another test',
         rotation=45,
         horizontalalignment='center',
         verticalalignment='top',
         multialignment='center')

Adding Gridlines

To add gridlines to the plot, we can use the grid function.

ax0.grid()

Adding Multiline Text to the Second Subplot

In the second subplot, we will add multiline text using the text function. We can specify the position, size, vertical and horizontal alignment, and bbox of the text.

ax1.text(0.29, 0.4, "Mat\nTTp\n123", size=18,
         va="baseline", ha="right", multialignment="left",
         bbox=dict(fc="none"))

ax1.text(0.34, 0.4, "Mag\nTTT\n123", size=18,
         va="baseline", ha="left", multialignment="left",
         bbox=dict(fc="none"))

ax1.text(0.95, 0.4, "Mag\nTTT$^{A^A}$\n123", size=18,
         va="baseline", ha="right", multialignment="left",
         bbox=dict(fc="none"))

Customizing the X-Axis Labels

To customize the x-axis labels, we can use the set_xticks function. We can specify the positions and labels of the ticks.

ax1.set_xticks([0.2, 0.4, 0.6, 0.8, 1.],
               labels=["Jan\n2009", "Feb\n2009", "Mar\n2009", "Apr\n2009",
                       "May\n2009"])

Adding a Horizontal Line and Title to the Second Subplot

To add a horizontal line to the second subplot, we can use the axhline function. We can also add a title to the subplot using the set_title function.

ax1.axhline(0.4)
ax1.set_title("test line spacing for multiline text")

Adjusting the Subplot Positions and Displaying the Plot

Finally, we can adjust the positions of the subplots using the subplots_adjust function and display the plot using the show function.

fig.subplots_adjust(bottom=0.25, top=0.75)
plt.show()

Summary

In this tutorial, we learned how to create and customize plots using Matplotlib. We covered how to create a figure and subplots, plot data, customize axis labels, add text to the plot, add gridlines, customize x-axis labels, add a horizontal line and title to the plot, and adjust the subplot positions. Matplotlib provides a wide range of tools for creating static, animated, and interactive visualizations in Python, making it a powerful library for data visualization.

Other Python Tutorials you may like