Discrete colorbars help show clear steps of colors instead of smooth gradients. This makes it easier to see distinct groups or categories in data.
Discrete colorbars in Matplotlib
Introduction
Syntax
Matplotlib
import matplotlib.pyplot as plt import numpy as np import matplotlib.colors as mcolors # Define discrete colors and boundaries cmap = mcolors.ListedColormap(['blue', 'green', 'yellow', 'red']) bounds = [0, 10, 20, 30, 40] norm = mcolors.BoundaryNorm(bounds, cmap.N) # Create colorbar with discrete steps fig, ax = plt.subplots(figsize=(6, 1)) fig.colorbar(plt.cm.ScalarMappable(norm=norm, cmap=cmap), cax=ax, orientation='horizontal') plt.show()
Use ListedColormap to set specific colors for each step.
BoundaryNorm defines the edges of each color step.
Examples
Matplotlib
import matplotlib.pyplot as plt import matplotlib.colors as mcolors cmap = mcolors.ListedColormap(['red', 'yellow', 'green']) bounds = [0, 5, 10, 15] norm = mcolors.BoundaryNorm(bounds, cmap.N) fig, ax = plt.subplots(figsize=(5, 1)) fig.colorbar(plt.cm.ScalarMappable(norm=norm, cmap=cmap), cax=ax, orientation='horizontal') plt.show()
Matplotlib
import matplotlib.pyplot as plt import numpy as np import matplotlib.colors as mcolors cmap = mcolors.ListedColormap(['navy', 'cyan', 'lime', 'orange']) bounds = [0, 25, 50, 75, 100] norm = mcolors.BoundaryNorm(bounds, cmap.N) fig, ax = plt.subplots(figsize=(6, 1)) fig.colorbar(plt.cm.ScalarMappable(norm=norm, cmap=cmap), cax=ax, orientation='horizontal') plt.show()
Sample Program
This program creates a horizontal discrete colorbar with four color steps representing value ranges 0-10, 10-20, 20-30, and 30-40.
Matplotlib
import matplotlib.pyplot as plt import numpy as np import matplotlib.colors as mcolors # Data values values = np.array([5, 12, 18, 27, 33]) # Define discrete colormap and boundaries colors = ['blue', 'green', 'yellow', 'red'] cmap = mcolors.ListedColormap(colors) bounds = [0, 10, 20, 30, 40] norm = mcolors.BoundaryNorm(bounds, cmap.N) # Create a figure and axis fig, ax = plt.subplots(figsize=(6, 1)) # Create a ScalarMappable for the colorbar sm = plt.cm.ScalarMappable(cmap=cmap, norm=norm) sm.set_array([]) # Needed for colorbar # Add discrete colorbar cbar = fig.colorbar(sm, cax=ax, orientation='horizontal') cbar.set_label('Value ranges') plt.show()
Important Notes
Make sure the number of colors matches the number of intervals defined by bounds minus one.
Use set_array([]) on ScalarMappable to avoid warnings when creating colorbars without data.
Summary
Discrete colorbars show clear color steps for distinct data ranges.
Use ListedColormap and BoundaryNorm to create discrete colorbars.
They help make legends easier to read when data has categories or fixed ranges.
Practice
1. What is the main purpose of using a discrete colorbar in a matplotlib plot?
easy
Solution
Step 1: Understand colorbar types
Continuous colorbars show smooth color changes, while discrete colorbars use fixed color steps.Step 2: Identify the purpose of discrete colorbars
Discrete colorbars help separate data into clear categories using distinct colors.Final Answer:
To show data with distinct color steps for clear category separation -> Option DQuick Check:
Discrete colorbar = distinct color steps [OK]
Hint: Discrete colorbars separate categories with fixed colors [OK]
Common Mistakes:
- Confusing discrete with continuous colorbars
- Thinking colorbars change plot size
- Mixing colorbar purpose with axis labeling
2. Which of the following code snippets correctly creates a discrete colorbar with 3 color steps using matplotlib?
easy
Solution
Step 1: Identify correct colormap for discrete colors
ListedColormap is used for discrete colors, LinearSegmentedColormap is for continuous gradients.Step 2: Check normalization method
BoundaryNorm with boundaries defines discrete steps; Normalize is for continuous scaling.Final Answer:
cmap = ListedColormap(['red', 'green', 'blue'])\nnorm = BoundaryNorm([0, 1, 2, 3], cmap.N) -> Option CQuick Check:
ListedColormap + BoundaryNorm = discrete colorbar [OK]
Hint: Use ListedColormap + BoundaryNorm for discrete colorbars [OK]
Common Mistakes:
- Using Normalize instead of BoundaryNorm
- Using LinearSegmentedColormap for discrete colors
- Incorrect boundary list length
3. What will be the output color for a value of 1.5 in this discrete colorbar setup?
import matplotlib.pyplot as plt from matplotlib.colors import ListedColormap, BoundaryNorm cmap = ListedColormap(['yellow', 'orange', 'red']) norm = BoundaryNorm([0, 1, 2, 3], cmap.N) color = cmap(norm(1.5)) print(color)
medium
Solution
Step 1: Understand BoundaryNorm mapping
BoundaryNorm maps values 0-1 to first color (yellow), 1-2 to second (orange), 2-3 to third (red).Step 2: Find color for value 1.5
1.5 lies between 1 and 2, so it maps to the second color: orange (RGB approx (1.0, 0.647, 0.0, 1.0)).Final Answer:
(1.0, 0.647, 0.0, 1.0) # orange color -> Option BQuick Check:
Value 1.5 in 1-2 range = orange [OK]
Hint: Check which boundary interval the value falls into [OK]
Common Mistakes:
- Choosing first or third color incorrectly
- Confusing Normalize with BoundaryNorm behavior
- Misreading boundary intervals
4. Identify the error in this code that tries to create a discrete colorbar with 4 colors:
import matplotlib.pyplot as plt from matplotlib.colors import ListedColormap, BoundaryNorm cmap = ListedColormap(['blue', 'green', 'yellow', 'red']) norm = BoundaryNorm([0, 1, 2, 3], cmap.N) plt.colorbar(plt.cm.ScalarMappable(norm=norm, cmap=cmap)) plt.show()
medium
Solution
Step 1: Check boundary list length
BoundaryNorm boundaries must have length = number of colors + 1 to define intervals correctly.Step 2: Compare boundaries and colors
Here, 4 colors but only 4 boundaries given; should be 5 boundaries like [0,1,2,3,4].Final Answer:
Boundary list length should be one more than number of colors -> Option AQuick Check:
Boundaries = colors + 1 [OK]
Hint: Boundaries count = colors count + 1 for discrete colorbars [OK]
Common Mistakes:
- Using equal boundaries and colors length
- Thinking ScalarMappable is incompatible
- Believing ListedColormap limits colors
5. You have data with 5 categories labeled 0 to 4. You want a discrete colorbar with distinct colors for each category and labels shown on the colorbar ticks. Which approach correctly achieves this in matplotlib?
hard
Solution
Step 1: Set colormap and boundaries for 5 categories
ListedColormap with 5 colors matches 5 categories; BoundaryNorm boundaries must be length 6 for 5 intervals.Step 2: Position ticks between boundaries
Ticks at midpoints like 0.5,1.5,... label categories clearly on discrete colorbar.Final Answer:
Use ListedColormap with 5 colors, BoundaryNorm with boundaries [0,1,2,3,4,5], and set colorbar ticks at [0.5,1.5,2.5,3.5,4.5] with labels ['0','1','2','3','4'] -> Option AQuick Check:
Boundaries + mid-ticks label discrete categories [OK]
Hint: Use boundaries + midpoints for ticks to label categories [OK]
Common Mistakes:
- Using continuous colormap for discrete data
- Setting ticks at boundaries instead of midpoints
- Mismatching number of colors and boundaries
Recommended
Ready to prove it?
Pass the test and this pattern moves unknown
10 questions ~5 mineasy hard
