0
0
Matplotlibdata~30 mins

Discrete colorbars in Matplotlib - Mini Project: Build & Apply

Choose your learning style9 modes available
Discrete colorbars
📖 Scenario: You are working on a data visualization project where you want to show different categories with distinct colors. Instead of a smooth gradient, you want a colorbar with clear, separate color blocks.
🎯 Goal: Create a discrete colorbar using matplotlib that shows exactly 4 distinct colors representing 4 categories.
📋 What You'll Learn
Create a list called colors with exactly 4 color names or hex codes.
Create a ListedColormap from the colors list and assign it to cmap.
Create a BoundaryNorm with boundaries [0, 1, 2, 3, 4] and assign it to norm.
Use matplotlib.pyplot to create a figure and axis.
Add a colorbar to the axis using matplotlib.colorbar.ColorbarBase with the cmap and norm.
Display the plot.
💡 Why This Matters
🌍 Real World
Discrete colorbars are useful when you want to show categories or groups clearly in data visualizations, such as different risk levels, types of land use, or survey responses.
💼 Career
Data scientists and analysts often need to create clear and understandable visualizations. Knowing how to make discrete colorbars helps communicate categorical data effectively.
Progress0 / 4 steps
1
Create a list of 4 colors
Create a list called colors with these exact colors: 'red', 'green', 'blue', and 'yellow'.
Matplotlib
Need a hint?

Use square brackets and separate colors with commas.

2
Create a ListedColormap and BoundaryNorm
Import ListedColormap and BoundaryNorm from matplotlib.colors. Then create a ListedColormap called cmap from the colors list. Also create a BoundaryNorm called norm with boundaries [0, 1, 2, 3, 4] and number of colors equal to the length of colors.
Matplotlib
Need a hint?

Use ListedColormap(colors) and BoundaryNorm([0, 1, 2, 3, 4], ncolors=len(colors)).

3
Create figure and axis, add discrete colorbar
Import matplotlib.pyplot as plt. Create a figure and axis using plt.subplots(). Then import ColorbarBase from matplotlib.colorbar and create a colorbar on the axis using ColorbarBase with the cmap and norm. Use orientation='vertical' for the colorbar.
Matplotlib
Need a hint?

Use plt.subplots() and ColorbarBase with the correct arguments.

4
Display the plot
Use plt.show() to display the figure with the discrete colorbar.
Matplotlib
Need a hint?

Use plt.show() to see the colorbar.