Converting Units of Axis in Python

PythonPythonBeginner
Practice Now

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

Introduction

In data visualization, it is important to have the correct units of measurement on the axes of the plot. This tutorial demonstrates how to convert the units of the x and y axes 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.

Import the Required Libraries

First, import the required libraries. In this example, we will use Matplotlib and NumPy.

import matplotlib.pyplot as plt
import numpy as np

Define the Units

Next, define the units for the x and y axes. In this example, we will use centimeters and inches. We can use the basic_units library to define the units.

from basic_units import cm, inch

Create Data

Now, create some data to plot. In this example, we will use np.arange to create an array of values from 0 to 8 in increments of 2.

cms = cm * np.arange(0, 10, 2)

Create the Plot

Create a 2x2 grid of subplots using the subplots function. Then, use the plot function to plot the data on each subplot.

fig, axs = plt.subplots(2, 2, layout='constrained')

axs[0, 0].plot(cms, cms)

axs[0, 1].plot(cms, cms, xunits=cm, yunits=inch)

axs[1, 0].plot(cms, cms, xunits=inch, yunits=cm)
axs[1, 0].set_xlim(-1, 4)  ## scalars are interpreted in current units

axs[1, 1].plot(cms, cms, xunits=inch, yunits=inch)
axs[1, 1].set_xlim(3*cm, 6*cm)  ## cm are converted to inches

Display the Plot

Finally, display the plot using the show function.

plt.show()

Summary

This tutorial demonstrated how to convert the units of the x and y axes in Matplotlib using Python. By using the xunits and yunits parameters of the plot function, we can easily convert the units and display the correct values on the axes.

Other Python Tutorials you may like