Home » Matplotlib Colormaps Tutorial

Matplotlib Colormaps Tutorial

Oracle Java Certification
1 Year Subscription
Java SE 11 Developer (Upgrade) [1Z0-817]
Java SE 11 Programmer II [1Z0-816] Practice Tests
Java SE 11 Programmer I [1Z0-815] Practice Tests
Spring Framework Basics Video Course

Matplotlib Colormaps are essential tools for visualizing data, as they help translate numerical values into colors.

Colormaps are particularly useful in heatmaps, scatter plots, surface plots, and other visualizations where color helps represent a dimension of the data.

In this tutorial, we’ll cover various colormaps, how to apply them in different types of plots, and how to customize them in Matplotlib.

1. Importing Matplotlib

Before we start, make sure to import Matplotlib.

import matplotlib.pyplot as plt
import numpy as np
from matplotlib import cm

2. Types of Colormaps in Matplotlib

Matplotlib provides a variety of colormaps, which can be grouped into different categories:

  • Sequential: For data that ranges from low to high, e.g., viridis, plasma, Blues.
  • Diverging: For data that diverges around a central value, e.g., coolwarm, bwr, seismic.
  • Qualitative: For categorical data, e.g., Pastel1, Set3.
  • Cyclic: For data that wraps around a cycle, such as angular data, e.g., twilight, hsv.

3. Displaying Available Colormaps

To view all available colormaps, you can use the following code:

import matplotlib.cm as cm

# Print list of colormaps
print(cm.cmap_d.keys())

Or, visualize the colormaps with a heatmap example:

# Visualize all colormaps by category
from matplotlib.colors import ListedColormap
import matplotlib as mpl

# Sample data to show colormaps
gradient = np.linspace(0, 1, 256).reshape(1, -1)

def plot_colormaps(cmaps):
    n_maps = len(cmaps)
    fig, axs = plt.subplots(n_maps, 1, figsize=(6, n_maps * 0.25))

    for ax, cmap_name in zip(axs, cmaps):
        ax.imshow(gradient, aspect='auto', cmap=cm.get_cmap(cmap_name))
        ax.set_axis_off()
        ax.set_title(cmap_name, fontdict={'fontsize': 8, 'fontweight': 'bold'}, loc='left')

    plt.show()

# List of colormaps to display
colormap_list = ['viridis', 'plasma', 'inferno', 'magma', 'cividis', 'coolwarm', 'bwr', 'seismic', 'Pastel1', 'twilight']
plot_colormaps(colormap_list)

4. Using Colormaps in Different Types of Plots

4.1 Heatmaps

Heatmaps are a great way to visualize data matrices with a color gradient representing values.

# Generating sample data
data = np.random.rand(10, 10)

# Plotting a heatmap with a colormap
plt.imshow(data, cmap='viridis')
plt.colorbar()
plt.title("Heatmap with Viridis Colormap")
plt.show()

In this example, the viridis colormap is applied to the heatmap. The plt.colorbar() function adds a color scale legend to the plot.

4.2 Scatter Plots

In scatter plots, colormaps can represent a third variable through color.

# Generating sample data
x = np.random.rand(100)
y = np.random.rand(100)
colors = np.random.rand(100)  # Third variable

# Scatter plot with colormap
plt.scatter(x, y, c=colors, cmap='plasma')
plt.colorbar()
plt.title("Scatter Plot with Plasma Colormap")
plt.xlabel("X-axis")
plt.ylabel("Y-axis")
plt.show()

Here, the c parameter represents color based on a third variable, and cmap='plasma' applies the plasma colormap.

4.3 Line Plots with Colormaps

You can use colormaps to color line plots by segment, which is useful when you want to visualize changes in data over a gradient.

# Generating sample data
x = np.linspace(0, 10, 100)
y = np.sin(x) * x

# Using color based on x-values
colors = y  # Use y-values as color

# Scatter plot to show line color changes
plt.scatter(x, y, c=colors, cmap='coolwarm', edgecolor='k')
plt.colorbar()
plt.title("Line Plot with Coolwarm Colormap")
plt.xlabel("X-axis")
plt.ylabel("Y-axis")
plt.show()

In this plot, we use y values to assign colors with the coolwarm colormap.

5. Customizing Colormaps

5.1 Reversing a Colormap

Every colormap in Matplotlib has a reversed version available by appending _r to the colormap name.

# Generating sample data
data = np.random.rand(10, 10)

# Display the reversed colormap
plt.imshow(data, cmap='viridis_r')
plt.colorbar()
plt.title("Heatmap with Reversed Viridis Colormap")
plt.show()

In this example, viridis_r reverses the colors of viridis.

5.2 Creating Custom Colormaps

If the built-in colormaps don’t fit your needs, you can create custom colormaps using ListedColormap or LinearSegmentedColormap.

from matplotlib.colors import ListedColormap

# Define a custom colormap with specific colors
custom_colors = ['#FF0000', '#00FF00', '#0000FF', '#FFFF00']
custom_cmap = ListedColormap(custom_colors)

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

# Display heatmap with custom colormap
plt.imshow(data, cmap=custom_cmap)
plt.colorbar()
plt.title("Heatmap with Custom Colormap")
plt.show()

6. Applying Colormaps to 3D Surface Plots

3D surface plots can leverage colormaps to represent data intensity or height.

from mpl_toolkits.mplot3d import Axes3D

# Sample data for 3D plot
x = np.linspace(-5, 5, 100)
y = np.linspace(-5, 5, 100)
x, y = np.meshgrid(x, y)
z = np.sin(np.sqrt(x**2 + y**2))

# 3D surface plot with colormap
fig = plt.figure()
ax = fig.add_subplot(111, projection='3d')
surface = ax.plot_surface(x, y, z, cmap='inferno')
fig.colorbar(surface)
plt.title("3D Surface Plot with Inferno Colormap")
plt.show()

In this example, plot_surface() creates a 3D surface plot, and cmap='inferno' applies the inferno colormap.

7. Normalizing Data for Colormaps

When working with colormaps, you may need to normalize data to scale it between 0 and 1. Matplotlib’s Normalize class helps standardize data.

from matplotlib.colors import Normalize

# Sample data
data = np.random.rand(10, 10) * 100  # Range from 0 to 100

# Normalize data
norm = Normalize(vmin=20, vmax=80)  # Values below 20 and above 80 will be clipped

# Display heatmap with normalization
plt.imshow(data, cmap='viridis', norm=norm)
plt.colorbar()
plt.title("Heatmap with Normalized Data")
plt.show()

8. Sequential vs. Diverging Colormaps

Choosing the right colormap depends on the nature of your data.

  • Sequential Colormaps (e.g., viridis, plasma) are ideal for representing data that progresses in one direction.
  • Diverging Colormaps (e.g., coolwarm, seismic) are best for data centered around a midpoint, like deviations or changes.

Example: Comparing Sequential and Diverging Colormaps

# Sample data centered around zero
data = np.random.randn(10, 10)

# Using sequential colormap
plt.subplot(1, 2, 1)
plt.imshow(data, cmap='Blues')
plt.colorbar()
plt.title("Sequential Colormap (Blues)")

# Using diverging colormap
plt.subplot(1, 2, 2)
plt.imshow(data, cmap='coolwarm')
plt.colorbar()
plt.title("Diverging Colormap (Coolwarm)")

plt.tight_layout()
plt.show()

9. Practical Example: Applying Colormaps in a Real-World Scenario

Imagine a scenario where you have temperature data for a city over a year and want to visualize it as a heatmap.

# Generate sample temperature data
np.random.seed(0)
days = np.arange(1, 366)
temperature = np.sin(2 * np.pi * days / 365) * 15 + 20 + np.random.randn(365)

# Reshape data to a monthly format (12 rows, ~30 days per month)
temperature_matrix = temperature.reshape(12, -1)

# Heatmap to show temperature variation
plt.imshow(temperature_matrix, cmap='coolwarm', aspect='auto')
plt.colorbar(label='Temperature (°

C)')
plt.title("Yearly Temperature Variation (Heatmap)")
plt.xlabel("Days in Month")
plt.ylabel("Month")
plt.show()

In this example, the coolwarm colormap is applied to represent temperature variations.

Summary of Colormap Usage

Task Colormap Recommendation Example
Heatmap Sequential, Diverging viridis, plasma
Scatter Plot (3rd variable) Sequential, Diverging coolwarm, plasma
3D Surface Plot Sequential, Diverging inferno, cividis
Categorical Data Qualitative Pastel1, Set3
Cyclic Data Cyclic hsv, twilight

Colormaps in Matplotlib provide a powerful way to add color dimensions to your data visualizations.

By understanding how to apply, customize, and choose appropriate colormaps, you can create informative and visually appealing plots tailored to your data’s needs.

You may also like

Leave a Comment

This website uses cookies to improve your experience. We'll assume you're ok with this, but you can opt-out if you wish. Accept Read More