Matplotlib Axis Transformation Techniques

PythonPythonBeginner
Practice Now

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

Introduction

Matplotlib is a Python library used for data visualization. It allows users to create a wide variety of charts, plots, and graphs. One of the key features of Matplotlib is its ability to apply scale transformations to axes. This allows for greater flexibility in presenting data, especially when dealing with very large or very small numbers. In this lab, we will learn how to apply various scale transformations to axes using Matplotlib.

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`"]) matplotlib(("`Matplotlib`")) -.-> matplotlib/PlotCustomizationGroup(["`Plot Customization`"]) 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/line_plots("`Line Plots`") matplotlib/PlotCustomizationGroup -.-> matplotlib/titles_labels("`Adding Titles and Labels`") matplotlib/PlotCustomizationGroup -.-> matplotlib/grid_config("`Grid Configuration`") python/BasicConceptsGroup -.-> python/booleans("`Booleans`") python/ControlFlowGroup -.-> python/for_loops("`For Loops`") python/DataStructuresGroup -.-> python/lists("`Lists`") python/DataStructuresGroup -.-> python/tuples("`Tuples`") 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-48911{{"`Matplotlib Axis Transformation Techniques`"}} matplotlib/importing_matplotlib -.-> lab-48911{{"`Matplotlib Axis Transformation Techniques`"}} matplotlib/figures_axes -.-> lab-48911{{"`Matplotlib Axis Transformation Techniques`"}} matplotlib/line_plots -.-> lab-48911{{"`Matplotlib Axis Transformation Techniques`"}} matplotlib/titles_labels -.-> lab-48911{{"`Matplotlib Axis Transformation Techniques`"}} matplotlib/grid_config -.-> lab-48911{{"`Matplotlib Axis Transformation Techniques`"}} python/booleans -.-> lab-48911{{"`Matplotlib Axis Transformation Techniques`"}} python/for_loops -.-> lab-48911{{"`Matplotlib Axis Transformation Techniques`"}} python/lists -.-> lab-48911{{"`Matplotlib Axis Transformation Techniques`"}} python/tuples -.-> lab-48911{{"`Matplotlib Axis Transformation Techniques`"}} python/function_definition -.-> lab-48911{{"`Matplotlib Axis Transformation Techniques`"}} python/importing_modules -.-> lab-48911{{"`Matplotlib Axis Transformation Techniques`"}} python/standard_libraries -.-> lab-48911{{"`Matplotlib Axis Transformation Techniques`"}} python/math_random -.-> lab-48911{{"`Matplotlib Axis Transformation Techniques`"}} python/numerical_computing -.-> lab-48911{{"`Matplotlib Axis Transformation Techniques`"}} python/data_visualization -.-> lab-48911{{"`Matplotlib Axis Transformation Techniques`"}} python/build_in_functions -.-> lab-48911{{"`Matplotlib Axis Transformation Techniques`"}} end

Import Libraries and Generate Data

First, we need to import the necessary libraries and generate some data to plot. In this example, we will use a normal distribution to generate data for the y-axis.

import matplotlib.pyplot as plt
import numpy as np

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

## make up some data in the interval ]0, 1[
y = np.random.normal(loc=0.5, scale=0.4, size=1000)
y = y[(y > 0) & (y < 1)]
y.sort()
x = np.arange(len(y))

Create a Linear Scale Plot

The first type of scale transformation we will explore is linear. This is the default scale used in Matplotlib. To create a linear scale plot, we use the set_yscale() method and pass in the string 'linear'. We also add a title and grid to the plot.

## linear
plt.plot(x, y)
plt.yscale('linear')
plt.title('Linear Scale')
plt.grid(True)

Create a Logarithmic Scale Plot

The next type of scale transformation we will explore is logarithmic. To create a logarithmic scale plot, we use the set_yscale() method and pass in the string 'log'. We also add a title and grid to the plot.

## log
plt.plot(x, y)
plt.yscale('log')
plt.title('Logarithmic Scale')
plt.grid(True)

Create a Symmetrical Logarithmic Scale Plot

The third type of scale transformation we will explore is symmetrical logarithmic. This type of scale is useful when dealing with data that contains both positive and negative values. To create a symmetrical logarithmic scale plot, we use the set_yscale() method and pass in the string 'symlog'. We also set the linthresh parameter to 0.02 to specify the range of values around zero that will be linearly scaled. We also add a title and grid to the plot.

## symmetric log
plt.plot(x, y - y.mean())
plt.yscale('symlog', linthresh=0.02)
plt.title('Symmetrical Logarithmic Scale')
plt.grid(True)

Create a Logit Scale Plot

The fourth type of scale transformation we will explore is logit. This type of scale is useful when dealing with data that is bounded by 0 and 1. To create a logit scale plot, we use the set_yscale() method and pass in the string 'logit'. We also add a title and grid to the plot.

## logit
plt.plot(x, y)
plt.yscale('logit')
plt.title('Logit Scale')
plt.grid(True)

Create a Custom Scale Plot

The final type of scale transformation we will explore is custom. This allows us to define our own forward and inverse functions for the scale transformation. In this example, we will define a custom function to take the square root of the data. To create a custom scale plot, we use the set_yscale() method and pass in the string 'function'. We also define the forward() and inverse() functions and pass them as arguments to the functions parameter. We also add a title and grid to the plot.

## Function x**(1/2)
def forward(x):
    return x**(1/2)

def inverse(x):
    return x**2

plt.plot(x, y)
plt.yscale('function', functions=(forward, inverse))
plt.title('Custom Scale')
plt.grid(True)

Create a Mercator Transform Scale Plot

As a bonus, we will also create a plot using the Mercator transform function. This is not a built-in function in Matplotlib, but we can define our own forward and inverse functions to create a Mercator transform scale plot. In this example, we will define the forward() and inverse() functions for the Mercator transform. We also add a title and grid to the plot.

## Function Mercator transform
def forward(a):
    a = np.deg2rad(a)
    return np.rad2deg(np.log(np.abs(np.tan(a) + 1.0 / np.cos(a))))

def inverse(a):
    a = np.deg2rad(a)
    return np.rad2deg(np.arctan(np.sinh(a)))

t = np.arange(0, 170.0, 0.1)
s = t / 2.

plt.plot(t, s, '-', lw=2)
plt.yscale('function', functions=(forward, inverse))
plt.title('Mercator Transform Scale')
plt.grid(True)
plt.xlim([0, 180])

Summary

In this lab, we learned how to apply various scale transformations to axes using Matplotlib. We explored linear, logarithmic, symmetrical logarithmic, logit, custom, and Mercator transform scale transformations. By applying these scale transformations, we can better visualize data that contains very large or very small numbers, as well as data that contains both positive and negative values.

Other Python Tutorials you may like