Bird
Raised Fist0
Matplotlibdata~20 mins

Discrete colorbars in Matplotlib - Practice Problems & Coding Challenges

Choose your learning style10 modes available
Challenge - 5 Problems
🎖️
Discrete Colorbar Master
Get all challenges correct to earn this badge!
Test your skills under time pressure!
❓ Predict Output
intermediate
1:30remaining
Output of discrete colorbar with 3 colors
What will be the number of color segments in the colorbar produced by this code?
Matplotlib
import matplotlib.pyplot as plt
import numpy as np
from matplotlib.colors import BoundaryNorm

cmap = plt.get_cmap('viridis', 3)
bounds = [0, 1, 2, 3]
norm = BoundaryNorm(bounds, cmap.N)

fig, ax = plt.subplots(figsize=(4, 1))
fig.subplots_adjust(bottom=0.5)
cb = plt.colorbar(plt.cm.ScalarMappable(norm=norm, cmap=cmap), cax=ax, boundaries=bounds, ticks=bounds)
plt.show()
A3
B4
C2
D1
Attempts:
2 left
💡 Hint
Count the number of intervals defined by the bounds.
❓ data_output
intermediate
1:30remaining
Values mapped to colors using BoundaryNorm
Given the following code, what is the color index assigned to the value 2.5?
Matplotlib
import matplotlib.pyplot as plt
from matplotlib.colors import BoundaryNorm

bounds = [0, 1, 2, 3, 4]
cmap = plt.get_cmap('plasma', 4)
norm = BoundaryNorm(bounds, cmap.N)

value = 2.5
color_index = norm(value)
print(color_index)
A0
B2
C3
D1
Attempts:
2 left
💡 Hint
Check which interval 2.5 falls into between the bounds.
❓ visualization
advanced
2:00remaining
Identify the correct discrete colorbar visualization
Which option shows the correct discrete colorbar with 5 colors and boundaries at [0, 10, 20, 30, 40, 50]?
Matplotlib
import matplotlib.pyplot as plt
import numpy as np
from matplotlib.colors import BoundaryNorm

cmap = plt.get_cmap('coolwarm', 5)
bounds = [0, 10, 20, 30, 40, 50]
norm = BoundaryNorm(bounds, cmap.N)

fig, ax = plt.subplots(figsize=(6, 1))
fig.subplots_adjust(bottom=0.5)
cb = plt.colorbar(plt.cm.ScalarMappable(norm=norm, cmap=cmap), cax=ax, boundaries=bounds, ticks=bounds)
plt.show()
AColorbar with 6 color blocks and boundaries at 0, 8, 16, 24, 32, 40, 48
BColorbar with smooth gradient blending colors continuously from 0 to 50
CColorbar with 4 color blocks and boundaries at 0, 12, 24, 36, 48
DColorbar with 5 distinct color blocks separated by clear boundaries at 0,10,20,30,40,50
Attempts:
2 left
💡 Hint
Discrete colorbars show distinct color blocks matching the number of intervals.
🔧 Debug
advanced
1:30remaining
Error raised by incorrect BoundaryNorm usage
What error will this code raise?
Matplotlib
import matplotlib.pyplot as plt
from matplotlib.colors import BoundaryNorm

bounds = [0, 1, 2]
cmap = plt.get_cmap('viridis', 3)
norm = BoundaryNorm(bounds, 4)

value = 1.5
color_index = norm(value)
print(color_index)
AValueError: Number of colors, N, must be one less than number of boundaries
BTypeError: 'BoundaryNorm' object is not callable
CIndexError: color index out of range
DNo error, prints 1
Attempts:
2 left
💡 Hint
Check the relationship between cmap.N and the length of bounds.
🚀 Application
expert
3:00remaining
Creating a discrete colorbar for categorical data
You have 4 categories labeled 'A', 'B', 'C', 'D' and want a discrete colorbar with colors red, green, blue, and yellow respectively. Which code snippet correctly creates this discrete colorbar?
A
import matplotlib.pyplot as plt
from matplotlib.colors import ListedColormap

colors = ['red', 'green', 'blue', 'yellow']
cmap = ListedColormap(colors)

fig, ax = plt.subplots(figsize=(6, 1))
fig.subplots_adjust(bottom=0.5)
cb = plt.colorbar(plt.cm.ScalarMappable(cmap=cmap), cax=ax)
cb.set_ticks([0,1,2,3])
cb.ax.set_xticklabels(['A', 'B', 'C', 'D'])
plt.show()
B
import matplotlib.pyplot as plt
from matplotlib.colors import BoundaryNorm

colors = ['red', 'green', 'blue', 'yellow']
cmap = plt.get_cmap('tab10', 4)
bounds = [0, 1, 2, 3, 4]
norm = BoundaryNorm(bounds, cmap.N)

fig, ax = plt.subplots(figsize=(6, 1))
fig.subplots_adjust(bottom=0.5)
cb = plt.colorbar(plt.cm.ScalarMappable(norm=norm, cmap=cmap), cax=ax, boundaries=bounds, ticks=bounds)
plt.show()
C
import matplotlib.pyplot as plt
from matplotlib.colors import ListedColormap, BoundaryNorm

colors = ['red', 'green', 'blue', 'yellow']
cmap = ListedColormap(colors)
bounds = [0, 1, 2, 3, 4]
norm = BoundaryNorm(bounds, cmap.N)

fig, ax = plt.subplots(figsize=(6, 1))
fig.subplots_adjust(bottom=0.5)
cb = plt.colorbar(plt.cm.ScalarMappable(norm=norm, cmap=cmap), cax=ax, boundaries=bounds, ticks=[0.5,1.5,2.5,3.5])
cb.ax.set_xticklabels(['A', 'B', 'C', 'D'])
plt.show()
D
import matplotlib.pyplot as plt
from matplotlib.colors import ListedColormap, BoundaryNorm

colors = ['red', 'green', 'blue', 'yellow']
cmap = ListedColormap(colors)
bounds = [0, 1, 2, 3, 4]
norm = BoundaryNorm(bounds, cmap.N)

fig, ax = plt.subplots(figsize=(6, 1))
fig.subplots_adjust(bottom=0.5)
cb = plt.colorbar(plt.cm.ScalarMappable(norm=norm, cmap=cmap), cax=ax, boundaries=bounds, ticks=bounds)
cb.ax.set_xticklabels(['A', 'B', 'C', 'D'])
plt.show()
Attempts:
2 left
💡 Hint
Use ListedColormap with BoundaryNorm and set ticks at midpoints for labels.

Practice

(1/5)
1. What is the main purpose of using a discrete colorbar in a matplotlib plot?
easy
A. To increase the size of the plot figure
B. To create a continuous gradient of colors for smooth data
C. To add labels to the x-axis of a plot
D. To show data with distinct color steps for clear category separation

Solution

  1. Step 1: Understand colorbar types

    Continuous colorbars show smooth color changes, while discrete colorbars use fixed color steps.
  2. Step 2: Identify the purpose of discrete colorbars

    Discrete colorbars help separate data into clear categories using distinct colors.
  3. Final Answer:

    To show data with distinct color steps for clear category separation -> Option D
  4. Quick 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
A. cmap = ListedColormap(['red', 'green', 'blue']) norm = Normalize(0, 3)
B. cmap = LinearSegmentedColormap(['red', 'green', 'blue']) norm = Normalize(0, 3)
C. cmap = ListedColormap(['red', 'green', 'blue']) norm = BoundaryNorm([0, 1, 2, 3], cmap.N)
D. cmap = LinearSegmentedColormap(['red', 'green', 'blue']) norm = BoundaryNorm([0, 1, 2, 3], cmap.N)

Solution

  1. Step 1: Identify correct colormap for discrete colors

    ListedColormap is used for discrete colors, LinearSegmentedColormap is for continuous gradients.
  2. Step 2: Check normalization method

    BoundaryNorm with boundaries defines discrete steps; Normalize is for continuous scaling.
  3. Final Answer:

    cmap = ListedColormap(['red', 'green', 'blue'])\nnorm = BoundaryNorm([0, 1, 2, 3], cmap.N) -> Option C
  4. Quick 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
A. (1.0, 1.0, 0.0, 1.0) # yellow color
B. (1.0, 0.647, 0.0, 1.0) # orange color
C. (1.0, 0.0, 0.0, 1.0) # red color
D. (0.5, 0.5, 0.5, 1.0) # gray color

Solution

  1. Step 1: Understand BoundaryNorm mapping

    BoundaryNorm maps values 0-1 to first color (yellow), 1-2 to second (orange), 2-3 to third (red).
  2. 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)).
  3. Final Answer:

    (1.0, 0.647, 0.0, 1.0) # orange color -> Option B
  4. Quick 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
A. Boundary list length should be one more than number of colors
B. ListedColormap cannot have more than 3 colors
C. plt.colorbar requires a continuous colormap
D. ScalarMappable is not compatible with BoundaryNorm

Solution

  1. Step 1: Check boundary list length

    BoundaryNorm boundaries must have length = number of colors + 1 to define intervals correctly.
  2. Step 2: Compare boundaries and colors

    Here, 4 colors but only 4 boundaries given; should be 5 boundaries like [0,1,2,3,4].
  3. Final Answer:

    Boundary list length should be one more than number of colors -> Option A
  4. Quick 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
A. 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']
B. Use LinearSegmentedColormap with 5 colors and Normalize from 0 to 4, then set colorbar ticks at [0,1,2,3,4]
C. Use ListedColormap with 4 colors, BoundaryNorm with boundaries [0,1,2,3,4], and set colorbar ticks at [0,1,2,3]
D. Use ListedColormap with 5 colors, Normalize from 0 to 5, and set colorbar ticks at [0,1,2,3,4]

Solution

  1. 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.
  2. Step 2: Position ticks between boundaries

    Ticks at midpoints like 0.5,1.5,... label categories clearly on discrete colorbar.
  3. 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 A
  4. Quick 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 strong while earning +1 Grip toward your certificate.

10 questions~5 mineasy hard