Master Matplotlib From Scratch

Learn Matplotlib fundamentals, figure anatomy, basic plotting, chart customization, subplots, statistical visualizations, color mapping, annotations, 3D plotting, animations, and interactive visualizations through structured practical lessons.

COURSE SYLLABUS
1. Introduction & Environment Setup
What is Matplotlib? Installation Environment Setup Imports and Conventions
2. Core Figure Anatomy & Structures
Figure vs Axes Creating Canvas Dimensions and Resolution Saving Visuals
3. Basic Plotting
Line Plots Scatter Plots Bar Charts Histograms
4. Basic Visual Formatting & Labels
Titles and Labels Text Customization Legends Grid Lines
5. Advanced Plot Customization
Format Strings Line and Marker Styling Color Systems Transparency
6. Axis Control, Ticks & Limits
Axis Limits Custom Ticks Tick Labels Axis Scaling
7. Multi-Plot Layouts & Subplots
Basic Subplots Indexing Subplots Layout Tuning Advanced Grids
8. Advanced Statistical & Data-Specific Plots
Pie Charts Box and Whisker Plots Violin Plots Error Bars
9. Color Mapping & 2D Data Visualizations
Colormaps Heatmaps and Images Colorbars Contour Plots
10. Annotations & Shapes
Basic Text Smart Annotations Drawing Shapes Shading Areas
11. Customizing Styles & Themes
Built-in Styles Custom Style Sheets Global Configurations
12. Object-Oriented API vs Pyplot
Pyplot vs Object-Oriented API Transitioning Methods Dual Axis Plots
13. Deep Integration with Pandas & Seaborn
Pandas Plotting Backend Seaborn Overlays Passing Axes
14. 3D Plotting
3D Setup 3D Lines and Scatter Surface and Wireframes Camera View
15. Dynamic & Live Plots
Interactive Mode Animation Module Real-time Updates Exporting Animations
16. Performance Optimization & Interactive Backends
Plotting Speed Interactive Backends Event Handling

Heatmaps and Images in Matplotlib

Learn how to create heatmaps and display images using Matplotlib. Understand imshow(), image dimensions, interpolation, origin, extent, aspect ratio and colour mapping with practical Python examples.

1. Learning Objectives

After completing this lesson, you will be able to:

  • Understand heatmaps and image visualisation.
  • Display two-dimensional numerical data using imshow().
  • Create heatmaps using NumPy arrays.
  • Apply different colormaps to heatmaps.
  • Display image files using Matplotlib.
  • Understand interpolation methods.
  • Control image origin and extent.
  • Adjust image aspect ratio and display dimensions.
  • Display colourbars and customise image visualisations.

2. Introduction to Heatmaps and Images

Matplotlib provides the imshow() function to display two-dimensional data and image files. It converts numerical array values into coloured pixels.

A heatmap is a graphical representation of data where different colours represent different numerical values. It helps users identify patterns, high values, low values and relationships in a dataset.

What is a Heatmap?

A heatmap represents numerical information using colours. For example, a student performance heatmap can use different colours to represent marks in different subjects.

Numerical Data
      |
      v
Two-Dimensional Array
      |
      v
imshow()
      |
      v
Colormap
      |
      v
Heatmap Visualisation
Heatmap Concept Numerical Data Colour Mapping Heatmap 10 20 30 40 50 60 imshow() Apply Colormap Numerical values become coloured cells in a heatmap.

Conceptual transformation of numerical data into a heatmap.

3. Understanding imshow()

The imshow() function displays an image or a two-dimensional array as a graphical representation. It is one of the most commonly used functions for heatmaps and image visualisation.

Basic Syntax

plt.imshow(data, cmap='viridis')

Example: Display a Two-Dimensional Array

import matplotlib.pyplot as plt
import numpy as np

data = np.array([
    [10, 20, 30],
    [40, 50, 60],
    [70, 80, 90]
])

plt.imshow(data)
plt.title('Simple Heatmap')
plt.show()
Expected Output:
A 3 x 3 heatmap is displayed.
Each cell represents one numerical value.
Different values are represented using different colours.

Understanding the Array

data = np.array([
    [10, 20, 30],
    [40, 50, 60],
    [70, 80, 90]
])

This array contains three rows and three columns. Each array element is represented as a cell in the heatmap.

Property Value
Number of rows 3
Number of columns 3
Total elements 9
Array dimension 2D
Tip: The imshow() function is commonly used with two-dimensional arrays for heatmaps and with image arrays for displaying pictures.

4. Creating Heatmaps

A heatmap can be created by passing a two-dimensional NumPy array to imshow(). You can select a colormap to control how numerical values are represented using colours.

Example: Heatmap with Viridis

import matplotlib.pyplot as plt
import numpy as np

data = np.random.randint(1, 100, (5, 5))

plt.imshow(data, cmap='viridis')

plt.title('Student Marks Heatmap')
plt.xlabel('Subjects')
plt.ylabel('Students')

plt.colorbar(label='Marks')
plt.show()
Expected Output:
A 5 x 5 heatmap is displayed with random numerical values.
The viridis colormap represents the values using colours.
A colourbar appears beside the heatmap to explain the value range.

Example: Heatmap with Different Colormaps

import matplotlib.pyplot as plt
import numpy as np

data = np.random.rand(10, 10)

colormaps = ['viridis', 'plasma', 'coolwarm', 'inferno']

fig, axes = plt.subplots(2, 2, figsize=(9, 7))

for ax, cmap_name in zip(axes.flat, colormaps):
    ax.imshow(data, cmap=cmap_name)
    ax.set_title(cmap_name)

plt.tight_layout()
plt.show()
Expected Output:
A figure containing four heatmaps is displayed.
Each heatmap uses a different colormap:
viridis, plasma, coolwarm and inferno.
The same numerical data is represented using different colours.

5. Adding Values Inside Heatmap Cells

Sometimes, displaying only colours is not enough. You may also want to display the actual numerical values inside each heatmap cell.

You can use nested loops and the plt.text() function to add values to individual cells.

Example: Heatmap with Numerical Labels

import matplotlib.pyplot as plt
import numpy as np

data = np.array([
    [85, 90, 75],
    [70, 80, 95],
    [60, 88, 92]
])

plt.imshow(data, cmap='YlGnBu')

for i in range(data.shape[0]):
    for j in range(data.shape[1]):
        plt.text(
            j,
            i,
            data[i, j],
            ha='center',
            va='center',
            color='black'
        )

plt.colorbar(label='Marks')
plt.title('Student Marks Heatmap')
plt.xlabel('Subjects')
plt.ylabel('Students')

plt.show()
Expected Output:
A 3 x 3 heatmap is displayed.
Each cell contains its corresponding numerical value.
The YlGnBu colormap represents the values using colours.
A colourbar is displayed beside the heatmap.
Tip: Use ha='center' and va='center' to position text in the centre of each heatmap cell.

6. Displaying Image Files

Matplotlib can also display existing image files. The plt.imread() function reads an image into an array, and plt.imshow() displays it.

Example: Read and Display an Image

import matplotlib.pyplot as plt

image = plt.imread('sample.png')

plt.imshow(image)
plt.title('My Image')
plt.axis('off')

plt.show()
Expected Output:
The sample.png image is loaded and displayed.
The image is shown inside a Matplotlib figure.
The axis is hidden using plt.axis('off').

Reading an Image with Matplotlib

import matplotlib.pyplot as plt

image = plt.imread('sample.png')

print(image.shape)
print(image.dtype)
Expected Output:
(400, 600, 3)
float32

The output above is an example. Actual image dimensions and data type depend on the image file being loaded.

Image Array Shape Meaning
(height, width) Grayscale image.
(height, width, 3) RGB image.
(height, width, 4) RGBA image with an alpha channel.
Important: Make sure the image file exists at the specified path. Otherwise, Python will raise a file-related error.

7. Displaying Grayscale Images

A grayscale image contains shades of grey instead of multiple colours. Each pixel represents an intensity value, usually ranging from black to white.

Example: Display Grayscale Image

import matplotlib.pyplot as plt
import numpy as np

image = np.random.randint(0, 256, (100, 100))

plt.imshow(image, cmap='gray')
plt.title('Grayscale Image')
plt.colorbar(label='Pixel Intensity')

plt.show()
Expected Output:
A 100 x 100 grayscale image is displayed.
Lower intensity values appear darker.
Higher intensity values appear lighter.
A colourbar shows the pixel intensity range.

Common Grayscale Colormaps

  • gray
  • Greys
  • binary
  • bone

8. Understanding Interpolation

Interpolation controls how Matplotlib displays pixels when an image is resized or scaled. It determines how missing display pixels are calculated between original image pixels.

Different interpolation methods produce different visual results. Some methods preserve sharp pixel boundaries, while others create smoother images.

Common Interpolation Methods

Method Description
nearest Uses the nearest pixel value. Preserves sharp pixel boundaries.
bilinear Uses linear interpolation in two dimensions.
bicubic Uses cubic interpolation for smoother results.
lanczos Uses a high-quality resampling filter.
none Displays the image without interpolation where supported by the backend.

Example: Comparing Interpolation Methods

import matplotlib.pyplot as plt
import numpy as np

data = np.random.rand(10, 10)

methods = ['nearest', 'bilinear', 'bicubic']

fig, axes = plt.subplots(1, 3, figsize=(12, 4))

for ax, method in zip(axes, methods):
    ax.imshow(data, interpolation=method)
    ax.set_title(method)

plt.tight_layout()
plt.show()
Expected Output:
Three image panels are displayed.
The first uses nearest interpolation.
The second uses bilinear interpolation.
The third uses bicubic interpolation.
The images show different smoothing and pixel transition effects.
Tip: Use nearest when you want to preserve individual pixels, especially for pixel-based data. Use smoother interpolation methods when visual smoothness is important.

9. Understanding Image Origin

The origin parameter controls where the first row of an image is placed in the plot.

Matplotlib supports two common origin settings: upper and lower.

Origin Upper

When origin='upper' is used, the first row of the array appears at the top of the image. This is the default setting for imshow().

Origin Lower

When origin='lower' is used, the first row of the array appears at the bottom of the image.

Example: Comparing Image Origins

import matplotlib.pyplot as plt
import numpy as np

data = np.array([
    [1, 2, 3],
    [4, 5, 6],
    [7, 8, 9]
])

fig, axes = plt.subplots(1, 2, figsize=(8, 4))

axes[0].imshow(data, origin='upper', cmap='viridis')
axes[0].set_title('Origin Upper')

axes[1].imshow(data, origin='lower', cmap='viridis')
axes[1].set_title('Origin Lower')

plt.tight_layout()
plt.show()
Expected Output:
Two heatmaps are displayed side by side.
The first uses origin='upper'.
The second uses origin='lower'.
The row positions appear vertically reversed between the two plots.
origin='upper' origin='lower' 1 2 3 4 5 6 First row starts at top First row starts at bottom

Conceptual comparison of upper and lower image origins.

10. Understanding Extent

The extent parameter defines the boundaries of an image in data coordinates. It controls where the image appears along the X and Y axes.

The extent parameter accepts four values: [left, right, bottom, top].

Example: Using Extent

import matplotlib.pyplot as plt
import numpy as np

data = np.random.rand(10, 10)

plt.imshow(
    data,
    extent=[0, 100, 0, 50],
    origin='lower',
    cmap='viridis'
)

plt.title('Image with Custom Extent')
plt.xlabel('X Coordinates')
plt.ylabel('Y Coordinates')

plt.colorbar()
plt.show()
Expected Output:
A heatmap is displayed with custom coordinate boundaries.
The X-axis ranges from 0 to 100.
The Y-axis ranges from 0 to 50.
The image is positioned using the specified extent.

Extent Parameters

Value Meaning
left Left boundary of the image.
right Right boundary of the image.
bottom Bottom boundary of the image.
top Top boundary of the image.

11. Understanding Aspect Ratio

The aspect parameter controls the relationship between the displayed size of a pixel along the X-axis and the displayed size along the Y-axis.

It helps control the shape of the displayed image. Common values include equal and auto.

Aspect Equal

With aspect='equal', the X-axis and Y-axis use the same scale. Each pixel has equal width and height in data-coordinate units.

Aspect Auto

With aspect='auto', Matplotlib adjusts the displayed image to fit the available axes area.

Example: Comparing Aspect Ratios

import matplotlib.pyplot as plt
import numpy as np

data = np.random.rand(10, 20)

fig, axes = plt.subplots(1, 2, figsize=(9, 4))

axes[0].imshow(data, aspect='equal')
axes[0].set_title('Aspect Equal')

axes[1].imshow(data, aspect='auto')
axes[1].set_title('Aspect Auto')

plt.tight_layout()
plt.show()
Expected Output:
Two images are displayed side by side.
The first uses equal scaling for both axes.
The second adjusts the image to fit the available axes area.

12. Controlling Image Colour Range

Matplotlib uses normalization to map numerical image values to colours. You can control this process with vmin, vmax and normalization objects.

Example: Fixed Colour Range

import matplotlib.pyplot as plt
import numpy as np

data = np.random.randint(0, 100, (10, 10))

plt.imshow(
    data,
    cmap='plasma',
    vmin=0,
    vmax=100
)

plt.colorbar(label='Values')
plt.title('Fixed Colour Range')

plt.show()
Expected Output:
A heatmap is displayed using the plasma colormap.
The colour scale is fixed between 0 and 100.
The colourbar represents this numerical range.

Example: Using Normalize

import matplotlib.pyplot as plt
import matplotlib.colors as colors
import numpy as np

data = np.random.randint(10, 100, (10, 10))

norm = colors.Normalize(
    vmin=10,
    vmax=100
)

plt.imshow(
    data,
    cmap='viridis',
    norm=norm
)

plt.colorbar()
plt.title('Heatmap with Normalize')

plt.show()
Expected Output:
A heatmap is displayed using normalized values.
The colour mapping uses the range from 10 to 100.
A colourbar explains the numerical values.
Tip: Use the same colour range when comparing multiple heatmaps. Otherwise, the same colour may represent different numerical values in different plots.

13. Important imshow() Parameters

The imshow() function provides several parameters for controlling how images and heatmaps are displayed.

Parameter Description
X Image data or two-dimensional array.
cmap Specifies the colormap.
interpolation Controls interpolation between pixels.
origin Controls the position of the first row.
extent Defines image boundaries in data coordinates.
aspect Controls image aspect ratio.
vmin Sets the lower colour limit.
vmax Sets the upper colour limit.
alpha Controls image transparency.

14. Complete Practical Example

In this example, we create a student performance heatmap. Each row represents a student, and each column represents a subject. The cell colours represent student marks.

import matplotlib.pyplot as plt
import numpy as np

marks = np.array([
    [85, 90, 78, 88],
    [70, 75, 80, 72],
    [95, 92, 98, 94],
    [60, 65, 70, 68],
    [88, 85, 90, 92]
])

students = [
    'Student 1',
    'Student 2',
    'Student 3',
    'Student 4',
    'Student 5'
]

subjects = [
    'Java',
    'Python',
    'DBMS',
    'Matplotlib'
]

plt.figure(figsize=(9, 5))

image = plt.imshow(
    marks,
    cmap='YlGnBu',
    vmin=0,
    vmax=100,
    aspect='auto'
)

plt.xticks(
    range(len(subjects)),
    subjects
)

plt.yticks(
    range(len(students)),
    students
)

for i in range(marks.shape[0]):
    for j in range(marks.shape[1]):
        plt.text(
            j,
            i,
            marks[i, j],
            ha='center',
            va='center',
            color='black'
        )

plt.colorbar(image, label='Marks')

plt.title('Student Performance Heatmap')
plt.xlabel('Subjects')
plt.ylabel('Students')

plt.tight_layout()
plt.show()
Expected Output:
A student performance heatmap is displayed.
Five rows represent five students.
Four columns represent Java, Python, DBMS and Matplotlib.
Each cell displays the corresponding student marks.
The YlGnBu colormap represents the marks using colours.
A colourbar displays the mark range from 0 to 100.

What We Learned

We used NumPy to create a two-dimensional marks array. The imshow() function displayed the marks as a heatmap. The xticks() and yticks() functions added subject and student labels. The nested loops added numerical values inside each cell, and colorbar() explained the colour scale.

15. Common Mistakes and Solutions

Common Mistake Solution
Passing an incorrectly shaped array. Check the array shape using data.shape.
Using an invalid image file path. Verify that the image exists at the specified location.
Using an incorrect colormap name. Use an available Matplotlib colormap.
Image appears vertically reversed. Check the origin parameter.
Image looks stretched. Check the aspect parameter.
Image appears pixelated. Try a suitable interpolation method.
Heatmap colours are difficult to compare. Use consistent vmin and vmax values.
Heatmap values are not visible. Use plt.text() to display cell values.

16. Practical Activity

Activity 1: Create a Basic Heatmap

Create a 5 x 5 NumPy array and display it using imshow(). Apply the viridis colormap.

Activity 2: Add Numerical Labels

Display the values inside every heatmap cell using plt.text().

Activity 3: Compare Interpolation

Display the same image using nearest, bilinear and bicubic interpolation. Compare their appearance.

Activity 4: Display an Image

Read a PNG image using plt.imread() and display it using plt.imshow().

Activity 5: Student Performance Heatmap

Create a student marks array and display it with student names, subject names and a colourbar.

17. Practice Questions

  1. What is a heatmap in Matplotlib?
  2. What is the purpose of the imshow() function?
  3. How can you display a two-dimensional NumPy array?
  4. How can you add numerical values inside heatmap cells?
  5. What is the purpose of plt.imread()?
  6. What is the difference between RGB and grayscale images?
  7. What is image interpolation?
  8. What is the difference between nearest and bilinear interpolation?
  9. What is the purpose of the origin parameter?
  10. What does the extent parameter control?
  11. What is the difference between aspect='equal' and aspect='auto'?
  12. How can you control the colour range of a heatmap?

Summary

Heatmaps are graphical representations of numerical data in which different colours represent different values. Matplotlib provides the imshow() function to display two-dimensional arrays and image files.

NumPy arrays can be passed to imshow() to create heatmaps. Different colormaps such as viridis, plasma, inferno and coolwarm can be applied to represent numerical values through colours.

Numerical values can be displayed inside heatmap cells using plt.text(). The colorbar() function helps users understand the relationship between colours and values.

Matplotlib can read image files using plt.imread() and display them using imshow(). Images may contain grayscale, RGB or RGBA pixel data depending on their format.

Interpolation controls how pixels are displayed when an image is scaled. The origin parameter controls the placement of the first row, while extent defines the image boundaries in data coordinates.

The aspect parameter controls image scaling. Parameters such as cmap, vmin, vmax, alpha and norm provide additional control over heatmap and image visualisation.

Heatmaps and image visualisations are useful in scientific analysis, image processing, machine learning, statistical analysis and many other data visualisation applications.