# 5 Best Ways to Plot a 2D Matrix in Python with Colorbar Using Matplotlib

Rate this post

π‘ Problem Formulation: In data visualization, a common task is plotting a 2D matrix as a heatmap in Python to explore data patterns. Users need an effective method to represent varying data magnitudes with a colorbar for scale reference. We aim to show how to take a two-dimensional array, such as `[[1, 2], [3, 4]]`, and produce a color-coded heatmap with a colorbar indicating the scale.

## Method 1: Using `imshow()` Function

An accessible way to plot a 2D matrix in matplotlib is with the `matplotlib.pyplot.imshow()` function. It visualizes the matrix data as a color-coded image and is highly configurable, allowing for custom color maps, interpolation, and more.

Here’s an example:

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

# Create a 2D matrix
matrix = np.array([[1, 2], [3, 4]])

# Plot the matrix
plt.imshow(matrix, cmap='viridis')
plt.show()```

The output is a heatmap where different shades of the ‘viridis’ color map correspond to different values in the matrix, accompanied by a colorbar to show the value scale.

The `plt.imshow()` function creates an image object from the 2D array ‘matrix’ and uses the ‘viridis’ color map to encode values. The `plt.colorbar()` function then adds a color scale bar on the side, providing a visual indication of the value corresponding to each color.

## Method 2: Customizing the Colorbar with `imshow()`

Customizing the colorbar when plotting a 2D matrix can enhance readability. The customization can include aspects such as the colorbar’s location and orientation. Matplotlib provides the flexibility to tailor the colorbar according to specific visualization requirements.

Here’s an example:

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

matrix = np.array([[5, 10], [15, 20]])

# Plot the matrix with customization
plt.imshow(matrix, cmap='coolwarm')
cbar = plt.colorbar()
cbar.set_label('Values')
plt.show()```

In this output, the colorbar has the label “Values” to indicate what the colors represent, using the ‘coolwarm’ colormap for visual distinction.

The customization in this snippet includes setting the label on the colorbar to clearly indicate its purpose. The `cbar.set_label()` method is used to add a descriptive label to the colorbar.

## Method 3: Using `pcolormesh()` for Large Matrices

For larger matrices, `pcolormesh()` is a suitable method. It is specifically optimized for large datasets, and it works by creating a pseudocolor plot with a non-regular rectangular grid. This can be quite effective for larger datasets or those with varying resolution.

Here’s an example:

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

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

# Larger matrix with pcolormesh
plt.pcolormesh(matrix, cmap='plasma')
plt.colorbar()
plt.show()```

This example generates a colorful plot with a spectrum represented by the ‘plasma’ colormap, suited for larger matrices.

`pcolormesh()` creates a pseudocolor plot which can handle large datasets effectively. The ‘plasma’ colormap in this case is used to provide a visually distinct color spectrum for the matrix values.

## Method 4: Advanced Colorbar Customization

Advanced customization of a colorbar can involve modifying aspects like tick marks, tick labels, and positioning of the colorbar. This approach provides granular control over the appearance of the color scale, affording clarity and enhanced aesthetic appeal.

Here’s an example:

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

matrix = np.array([[0, 1], [2, 3]])

plt.imshow(matrix, cmap='inferno')
cbar = plt.colorbar()
cbar.set_ticks([0, 1, 2, 3])
cbar.set_ticklabels(['Low', 'Medium', 'High', 'Very High'])
plt.show()```

The output includes a colorbar with custom tick marks and labels that provide qualitative information about the matrix values, using the ‘inferno’ colormap for a striking appearance.

This code snippet demonstrates how to set specific tick positions and custom labels on the colorbar, allowing for non-numeric or qualitative scales to be represented.

## Bonus One-Liner Method 5: Quick Plot with `matshow()`

If you’re looking for a concise way to visualize a 2D matrix, `matshow()` is an excellent one-liner option. It’s a wrapper around `imshow()`, specifically tailored for displaying a matrix in a simple and quick manner.

Here’s an example:

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

matrix = np.eye(3)

# Quick plot with matshow
plt.matshow(matrix, cmap='cividis')
plt.show()```

This produces a colormap plot of the identity matrix with the ‘cividis’ colormap, focusing on simplicity and quick rendering.

The `plt.matshow()` function is specialized for matrix display, providing an immediate visual representation with minimal setup and default options for aspect ratio and interpolation tailored for matrices.

## Summary/Discussion

• Method 1: `imshow()`. This method is straightforward and highly flexible for generating heatmaps. However, for very large datasets, performance could be a drawback.
• Method 2: Customized Colorbar with `imshow()`. It provides enhanced readability through customization. Customization, though, may require additional code and consideration of aesthetic design.
• Method 3: `pcolormesh()`. Optimized for large matrices and varying grid resolutions. It can be more complex to set up and might not be necessary for small or simple datasets.
• Method 4: Advanced Colorbar Customization. Offers detailed control over the colorbar appearance. Understanding and implementing these customizations can be more complex and time-consuming.
• Method 5: Quick Plot with `matshow()`. Ideal for rapid and simple matrix plotting, especially when default settings suffice. The simplicity may not satisfy all detailed visualization needs.