Modifying Coordinate Formatter in Matplotlib

PythonPythonBeginner
Practice Now

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

Introduction

Matplotlib is a library used for data visualization in Python. It provides a wide range of tools for creating various types of plots, graphs, and charts. One of the useful features of Matplotlib is the ability to customize the coordinate formatter. In this lab, we will go through the steps of modifying the coordinate formatter in Matplotlib to report the image "z" value of the nearest pixel given x and y.

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`"]) matplotlib(("`Matplotlib`")) -.-> matplotlib/BasicConceptsGroup(["`Basic Concepts`"]) matplotlib(("`Matplotlib`")) -.-> matplotlib/PlottingDataGroup(["`Plotting Data`"]) 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`") matplotlib/BasicConceptsGroup -.-> matplotlib/importing_matplotlib("`Importing Matplotlib`") matplotlib/BasicConceptsGroup -.-> matplotlib/figures_axes("`Understanding Figures and Axes`") matplotlib/PlottingDataGroup -.-> matplotlib/heatmaps("`Heatmaps`") 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/FunctionsGroup -.-> python/function_definition("`Function Definition`") python/ModulesandPackagesGroup -.-> python/importing_modules("`Importing Modules`") python/ModulesandPackagesGroup -.-> python/standard_libraries("`Common Standard Libraries`") python/PythonStandardLibraryGroup -.-> python/math_random("`Math and Random`") 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-48785{{"`Modifying Coordinate Formatter in Matplotlib`"}} matplotlib/importing_matplotlib -.-> lab-48785{{"`Modifying Coordinate Formatter in Matplotlib`"}} matplotlib/figures_axes -.-> lab-48785{{"`Modifying Coordinate Formatter in Matplotlib`"}} matplotlib/heatmaps -.-> lab-48785{{"`Modifying Coordinate Formatter in Matplotlib`"}} python/conditional_statements -.-> lab-48785{{"`Modifying Coordinate Formatter in Matplotlib`"}} python/for_loops -.-> lab-48785{{"`Modifying Coordinate Formatter in Matplotlib`"}} python/lists -.-> lab-48785{{"`Modifying Coordinate Formatter in Matplotlib`"}} python/tuples -.-> lab-48785{{"`Modifying Coordinate Formatter in Matplotlib`"}} python/dictionaries -.-> lab-48785{{"`Modifying Coordinate Formatter in Matplotlib`"}} python/function_definition -.-> lab-48785{{"`Modifying Coordinate Formatter in Matplotlib`"}} python/importing_modules -.-> lab-48785{{"`Modifying Coordinate Formatter in Matplotlib`"}} python/standard_libraries -.-> lab-48785{{"`Modifying Coordinate Formatter in Matplotlib`"}} python/math_random -.-> lab-48785{{"`Modifying Coordinate Formatter in Matplotlib`"}} python/numerical_computing -.-> lab-48785{{"`Modifying Coordinate Formatter in Matplotlib`"}} python/data_visualization -.-> lab-48785{{"`Modifying Coordinate Formatter in Matplotlib`"}} python/build_in_functions -.-> lab-48785{{"`Modifying Coordinate Formatter in Matplotlib`"}} end

Import necessary modules

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

import matplotlib.pyplot as plt
import numpy as np

Create a random matrix

Next, we will create a random matrix using numpy. We will use the rand method to create a 5x3 matrix with random values between 0 and 1. We will also set a random seed to ensure reproducibility of the results.

## Fixing random state for reproducibility
np.random.seed(19680801)

X = 10*np.random.rand(5, 3)

Create a plot

Now, we will create a plot of the matrix using imshow method of the Matplotlib axes class.

fig, ax = plt.subplots()
ax.imshow(X)

Modify coordinate formatter

We will now modify the coordinate formatter to report the image "z" value of the nearest pixel given x and y. This can be achieved by customizing the ~.axes.Axes.format_coord function.

def format_coord(x, y):
    col = round(x)
    row = round(y)
    nrows, ncols = X.shape
    if 0 <= col < ncols and 0 <= row < nrows:
        z = X[row, col]
        return f'x={x:1.4f}, y={y:1.4f}, z={z:1.4f}'
    else:
        return f'x={x:1.4f}, y={y:1.4f}'

ax.format_coord = format_coord

Display the plot

Finally, we will display the plot using plt.show() method.

plt.show()

Summary

In this lab, we learned how to modify the coordinate formatter in Matplotlib to report the image "z" value of the nearest pixel given x and y. We also learned how to create a plot of a random matrix using imshow method and customize the ~.axes.Axes.format_coord function to modify the coordinate formatter.

Other Python Tutorials you may like