0
0
Matplotlibdata~5 mins

Color mapping with colorbar in Matplotlib

Choose your learning style9 modes available
Introduction

Color mapping helps show data values using colors. A colorbar explains what each color means.

When you want to show how numbers change across a grid or image.
When you plot heatmaps to see patterns in data.
When you want to add a legend for colors in scatter plots.
When you visualize data intensity or density.
When you want to make your plots easier to understand with colors.
Syntax
Matplotlib
import matplotlib.pyplot as plt
import numpy as np

# Create data
Z = np.random.rand(10,10)

# Plot with color mapping
img = plt.imshow(Z, cmap='viridis')

# Add colorbar
plt.colorbar(img)

plt.show()

imshow shows data as colors.

cmap sets the color style.

Examples
Use 'plasma' color style and add a colorbar.
Matplotlib
plt.imshow(data, cmap='plasma')
plt.colorbar()
Color points by values and add a colorbar for reference.
Matplotlib
scatter = plt.scatter(x, y, c=values, cmap='coolwarm')
plt.colorbar(scatter)
Show heatmap with horizontal colorbar.
Matplotlib
heatmap = plt.imshow(matrix, cmap='inferno')
plt.colorbar(heatmap, orientation='horizontal')
Sample Program

This program creates a grid of values from 0 to 1. It shows these values as colors using the 'viridis' color style. The colorbar on the side explains which colors match which values.

Matplotlib
import matplotlib.pyplot as plt
import numpy as np

# Create a 10x10 grid of values from 0 to 1
Z = np.linspace(0, 1, 100).reshape(10, 10)

# Show the grid as colors using 'viridis' colormap
img = plt.imshow(Z, cmap='viridis')

# Add a vertical colorbar to explain colors
plt.colorbar(img)

plt.title('Color mapping with colorbar example')
plt.show()
OutputSuccess
Important Notes

The colorbar helps people understand what the colors mean in your plot.

You can change the color style by using different cmap names like 'plasma', 'inferno', or 'coolwarm'.

Always add a colorbar when your plot uses colors to show data values.

Summary

Color mapping turns numbers into colors to show data visually.

A colorbar explains the meaning of these colors.

Use imshow or scatter with cmap and add plt.colorbar() to your plot.