Matplotlib Image Grid Colorbars

PythonPythonBeginner
Practice Now

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

Introduction

This lab is about creating image grids with colorbars using Matplotlib. The example code provided shows how to use one common colorbar for each row or column of an image grid.

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/BasicConceptsGroup -.-> python/variables_data_types("`Variables and Data Types`") python/BasicConceptsGroup -.-> python/booleans("`Booleans`") 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/FunctionsGroup -.-> python/function_definition("`Function Definition`") python/ModulesandPackagesGroup -.-> python/importing_modules("`Importing Modules`") python/ModulesandPackagesGroup -.-> python/using_packages("`Using Packages`") python/PythonStandardLibraryGroup -.-> python/data_collections("`Data Collections`") python/DataScienceandMachineLearningGroup -.-> python/data_visualization("`Data Visualization`") python/FunctionsGroup -.-> python/build_in_functions("`Build-in Functions`") subgraph Lab Skills python/comments -.-> lab-48674{{"`Matplotlib Image Grid Colorbars`"}} matplotlib/importing_matplotlib -.-> lab-48674{{"`Matplotlib Image Grid Colorbars`"}} matplotlib/figures_axes -.-> lab-48674{{"`Matplotlib Image Grid Colorbars`"}} matplotlib/heatmaps -.-> lab-48674{{"`Matplotlib Image Grid Colorbars`"}} python/variables_data_types -.-> lab-48674{{"`Matplotlib Image Grid Colorbars`"}} python/booleans -.-> lab-48674{{"`Matplotlib Image Grid Colorbars`"}} python/conditional_statements -.-> lab-48674{{"`Matplotlib Image Grid Colorbars`"}} python/for_loops -.-> lab-48674{{"`Matplotlib Image Grid Colorbars`"}} python/lists -.-> lab-48674{{"`Matplotlib Image Grid Colorbars`"}} python/tuples -.-> lab-48674{{"`Matplotlib Image Grid Colorbars`"}} python/function_definition -.-> lab-48674{{"`Matplotlib Image Grid Colorbars`"}} python/importing_modules -.-> lab-48674{{"`Matplotlib Image Grid Colorbars`"}} python/using_packages -.-> lab-48674{{"`Matplotlib Image Grid Colorbars`"}} python/data_collections -.-> lab-48674{{"`Matplotlib Image Grid Colorbars`"}} python/data_visualization -.-> lab-48674{{"`Matplotlib Image Grid Colorbars`"}} python/build_in_functions -.-> lab-48674{{"`Matplotlib Image Grid Colorbars`"}} end

Import Libraries

First, we need to import the necessary libraries to create the image grid with colorbars.

import matplotlib.pyplot as plt
from matplotlib import cbook
from mpl_toolkits.axes_grid1 import AxesGrid

Define Image Data

We define a function that returns a sample image data and its extent.

def get_demo_image():
    z = cbook.get_sample_data("axes_grid/bivariate_normal.npy")  ## 15x15 array
    return z, (-3, 4, -4, 3)

Create a Grid with Bottom Colorbar

We create a grid of 2x2 images with a colorbar for each column.

def demo_bottom_cbar(fig):
    grid = AxesGrid(fig, 121,  ## similar to subplot(121)
                    nrows_ncols=(2, 2),
                    axes_pad=0.10,
                    share_all=True,
                    label_mode="1",
                    cbar_location="bottom",
                    cbar_mode="edge",
                    cbar_pad=0.25,
                    cbar_size="15%",
                    direction="column"
                    )

    Z, extent = get_demo_image()
    cmaps = ["autumn", "summer"]
    for i in range(4):
        im = grid[i].imshow(Z, extent=extent, cmap=cmaps[i//2])
        if i % 2:
            grid.cbar_axes[i//2].colorbar(im)

    for cax in grid.cbar_axes:
        cax.axis[cax.orientation].set_label("Bar")

    ## This affects all axes as share_all = True.
    grid.axes_llc.set_xticks([-2, 0, 2])
    grid.axes_llc.set_yticks([-2, 0, 2])

Create a Grid with Right Colorbar

We create a grid of 2x2 images with a colorbar for each row.

def demo_right_cbar(fig):
    grid = AxesGrid(fig, 122,  ## similar to subplot(122)
                    nrows_ncols=(2, 2),
                    axes_pad=0.10,
                    label_mode="1",
                    share_all=True,
                    cbar_location="right",
                    cbar_mode="edge",
                    cbar_size="7%",
                    cbar_pad="2%",
                    )
    Z, extent = get_demo_image()
    cmaps = ["spring", "winter"]
    for i in range(4):
        im = grid[i].imshow(Z, extent=extent, cmap=cmaps[i//2])
        if i % 2:
            grid.cbar_axes[i//2].colorbar(im)

    for cax in grid.cbar_axes:
        cax.axis[cax.orientation].set_label('Foo')

    ## This affects all axes because we set share_all = True.
    grid.axes_llc.set_xticks([-2, 0, 2])
    grid.axes_llc.set_yticks([-2, 0, 2])

Create the Figure and Call the Functions

Finally, we create the figure and call the functions to create the image grids with colorbars.

fig = plt.figure()

demo_bottom_cbar(fig)
demo_right_cbar(fig)

plt.show()

Summary

Matplotlib provides a simple way to create image grids with colorbars using the AxesGrid toolkit. This lab demonstrated how to create a grid of 2x2 images with a colorbar for each column and a grid of 2x2 images with a colorbar for each row. By following these steps, you can create image grids with colorbars for your own datasets.

Other Python Tutorials you may like