Matplotlib Visualization Control in Python

PythonPythonBeginner
Practice Now

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

Introduction

Matplotlib is a data visualization library in Python that is used to create static, animated, and interactive visualizations in Python. It provides an object-oriented API for embedding plots into applications using general-purpose GUI toolkits like Tkinter, wxPython, Qt, or GTK. In this lab, we will learn how to control view limits and sticky edges in Matplotlib using 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/BasicConceptsGroup(["`Basic Concepts`"]) python(("`Python`")) -.-> python/FileHandlingGroup(["`File Handling`"]) matplotlib(("`Matplotlib`")) -.-> matplotlib/BasicConceptsGroup(["`Basic Concepts`"]) matplotlib(("`Matplotlib`")) -.-> matplotlib/PlottingDataGroup(["`Plotting Data`"]) matplotlib(("`Matplotlib`")) -.-> matplotlib/AdvancedPlottingGroup(["`Advanced Plotting`"]) 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/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/AdvancedPlottingGroup -.-> matplotlib/subplots("`Subplots`") python/BasicConceptsGroup -.-> python/booleans("`Booleans`") python/ControlFlowGroup -.-> python/for_loops("`For Loops`") python/DataStructuresGroup -.-> python/lists("`Lists`") python/DataStructuresGroup -.-> python/tuples("`Tuples`") python/DataStructuresGroup -.-> python/sets("`Sets`") python/FunctionsGroup -.-> python/function_definition("`Function Definition`") 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 python/comments -.-> lab-48563{{"`Matplotlib Visualization Control in Python`"}} python/with_statement -.-> lab-48563{{"`Matplotlib Visualization Control in Python`"}} matplotlib/importing_matplotlib -.-> lab-48563{{"`Matplotlib Visualization Control in Python`"}} matplotlib/figures_axes -.-> lab-48563{{"`Matplotlib Visualization Control in Python`"}} matplotlib/line_plots -.-> lab-48563{{"`Matplotlib Visualization Control in Python`"}} matplotlib/subplots -.-> lab-48563{{"`Matplotlib Visualization Control in Python`"}} python/booleans -.-> lab-48563{{"`Matplotlib Visualization Control in Python`"}} python/for_loops -.-> lab-48563{{"`Matplotlib Visualization Control in Python`"}} python/lists -.-> lab-48563{{"`Matplotlib Visualization Control in Python`"}} python/tuples -.-> lab-48563{{"`Matplotlib Visualization Control in Python`"}} python/sets -.-> lab-48563{{"`Matplotlib Visualization Control in Python`"}} python/function_definition -.-> lab-48563{{"`Matplotlib Visualization Control in Python`"}} python/importing_modules -.-> lab-48563{{"`Matplotlib Visualization Control in Python`"}} python/numerical_computing -.-> lab-48563{{"`Matplotlib Visualization Control in Python`"}} python/data_visualization -.-> lab-48563{{"`Matplotlib Visualization Control in Python`"}} python/build_in_functions -.-> lab-48563{{"`Matplotlib Visualization Control in Python`"}} end

Plotting with Margins

The margins() method in Matplotlib can be used to set margins in the plot instead of using set_xlim() and set_ylim() methods. In this step, we will learn how to zoom in and out of a plot using margins() method instead of set_xlim() and set_ylim() methods.

import matplotlib.pyplot as plt
import numpy as np

def f(t):
    return np.exp(-t) * np.cos(2*np.pi*t)

t1 = np.arange(0.0, 3.0, 0.01)

## create a subplot with margins
ax1 = plt.subplot(212)
ax1.margins(0.05) ## default margin is 0.05, value 0 means fit
ax1.plot(t1, f(t1))

## create a subplot with zoomed out margins
ax2 = plt.subplot(221)
ax2.margins(2, 2) ## values >0.0 zoom out
ax2.plot(t1, f(t1))
ax2.set_title('Zoomed out')

## create a subplot with zoomed in margins
ax3 = plt.subplot(222)
ax3.margins(x=0, y=-0.25) ## values in (-0.5, 0.0) zooms in to center
ax3.plot(t1, f(t1))
ax3.set_title('Zoomed in')

plt.show()

Sticky Edges

Some plotting functions in Matplotlib make the axis limits "sticky" or immune to the margins() method. For instance, imshow() and pcolor() expect the user to want the limits to be tight around the pixels shown in the plot. If this behavior is not desired, you need to set use_sticky_edges to False. In this step, we will learn how to work around sticky edges in Matplotlib.

## create a grid
y, x = np.mgrid[:5, 1:6]

## define polygon coordinates
poly_coords = [
    (0.25, 2.75), (3.25, 2.75),
    (2.25, 0.75), (0.25, 0.75)
]

## create subplots
fig, (ax1, ax2) = plt.subplots(ncols=2)

## use sticky edges for ax1 and turn off sticky edges for ax2
ax2.use_sticky_edges = False

## plot on both subplots
for ax, status in zip((ax1, ax2), ('Is', 'Is Not')):
    cells = ax.pcolor(x, y, x+y, cmap='inferno', shading='auto') ## sticky
    ax.add_patch(
        Polygon(poly_coords, color='forestgreen', alpha=0.5)
    ) ## not sticky
    ax.margins(x=0.1, y=0.05)
    ax.set_aspect('equal')
    ax.set_title(f'{status} Sticky')

plt.show()

Summary

In this lab, we learned how to control view limits and sticky edges in Matplotlib using Python. We learned how to zoom in and out of a plot using margins() method instead of set_xlim() and set_ylim() methods. We also learned how to work around sticky edges in Matplotlib using use_sticky_edges property.

Other Python Tutorials you may like