Matplotlib: Simple Colorbar

PythonPythonBeginner
Practice Now

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

Introduction

In this lab, we will learn how to add a simple colorbar to a Matplotlib plot. A colorbar is a useful tool for visualizing the range of values represented by colors in a plot. We will use the imshow function to create a simple 2D plot and then add a colorbar to it.

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 libraries

To get started, we need to import the necessary libraries. We will use the numpy and matplotlib.pyplot libraries for this lab.

import matplotlib.pyplot as plt
import numpy as np

Create a 2D plot

Next, we will create a simple 2D plot using the imshow function.

## Create a 2D array
data = np.random.rand(10, 10)

## Plot the array
plt.imshow(data)

Add a colorbar

Now we can add a colorbar to the plot using the colorbar function.

## Add a colorbar to the plot
plt.colorbar()

Customize the colorbar

We can customize the appearance of the colorbar by using the cmap parameter. This parameter specifies the color map used to create the plot.

## Customize the colorbar
plt.colorbar(cmap='viridis')

Add a label to the colorbar

We can add a label to the colorbar using the label parameter.

## Add a label to the colorbar
plt.colorbar(cmap='viridis', label='Random Data')

Summary

In this lab, we learned how to add a simple colorbar to a Matplotlib plot. We used the imshow function to create a 2D plot and then added a colorbar using the colorbar function. We also customized the appearance of the colorbar and added a label to it. Colorbars are a useful tool for visualizing the range of values represented by colors in a plot.

Other Python Tutorials you may like