Bird
Raised Fist0
Matplotlibdata~20 mins

Colorbar formatting in Matplotlib - Practice Problems & Coding Challenges

Choose your learning style10 modes available
Challenge - 5 Problems
🎖️
Colorbar Formatting Master
Get all challenges correct to earn this badge!
Test your skills under time pressure!
❓ Predict Output
intermediate
2:00remaining
What is the output of this colorbar tick labels code?

Consider this code snippet that creates a colorbar with custom tick labels. What will be the printed list of tick labels?

Matplotlib
import matplotlib.pyplot as plt
import numpy as np

fig, ax = plt.subplots()
img = ax.imshow(np.random.rand(5,5), cmap='viridis')
cbar = fig.colorbar(img)
cbar.set_ticks([0.2, 0.5, 0.8])
ticks = cbar.ax.get_yticklabels()
labels = [tick.get_text() for tick in ticks]
print(labels)
A['0', '0.5', '1']
B['0.20', '0.50', '0.80']
C['', '', '']
D['0.2', '0.5', '0.8']
Attempts:
2 left
💡 Hint

Remember that get_yticklabels() returns label objects which may not have text set until drawn.

❓ data_output
intermediate
2:00remaining
How many ticks will this colorbar display?

This code creates a colorbar with a fixed number of ticks. How many ticks will appear on the colorbar?

Matplotlib
import matplotlib.pyplot as plt
import numpy as np

fig, ax = plt.subplots()
img = ax.imshow(np.random.rand(10,10), cmap='plasma')
cbar = fig.colorbar(img, ticks=np.linspace(0,1,5))
print(len(cbar.ax.get_yticks()))
A4
B6
C10
D5
Attempts:
2 left
💡 Hint

Check how many values are in np.linspace(0,1,5).

🔧 Debug
advanced
2:00remaining
Why does this colorbar label formatting code raise an error?

Look at this code that tries to format colorbar tick labels. What error does it raise?

Matplotlib
import matplotlib.pyplot as plt
import numpy as np

fig, ax = plt.subplots()
img = ax.imshow(np.random.rand(5,5), cmap='cool')
cbar = fig.colorbar(img)
cbar.ax.yaxis.set_major_formatter('{:.2f}')
ATypeError: 'str' object is not callable
BAttributeError: 'str' object has no attribute 'format'
CValueError: Invalid format string
DNo error, runs fine
Attempts:
2 left
💡 Hint

Check what type set_major_formatter expects as argument.

🚀 Application
advanced
3:00remaining
Which code correctly formats colorbar ticks as percentages?

You want to show colorbar tick labels as percentages (e.g., 20%, 50%). Which option correctly formats the colorbar ticks?

Matplotlib
import matplotlib.pyplot as plt
import numpy as np
from matplotlib.ticker import FuncFormatter

fig, ax = plt.subplots()
img = ax.imshow(np.random.rand(5,5), cmap='inferno')
cbar = fig.colorbar(img)
Acbar.ax.yaxis.set_major_formatter(FuncFormatter(lambda x, _: f'{int(x*100)}%'))
B
cbar.formatter = FuncFormatter(lambda x, _: f'{x*100}%')
cbar.update_ticks()
Ccbar.ax.yaxis.set_major_formatter('{:.0%}')
D
cbar.set_ticks([0, 0.5, 1])
cbar.ax.set_yticklabels(['0%', '50%', '100%'])
Attempts:
2 left
💡 Hint

Use FuncFormatter to create a custom label format function.

🧠 Conceptual
expert
2:00remaining
What is the effect of calling cbar.ax.invert_yaxis() on a vertical colorbar?

In matplotlib, what happens when you call invert_yaxis() on the colorbar's axis?

AThe colorbar disappears from the plot.
BThe colorbar colors are reversed vertically, so high values appear at the bottom.
CThe colorbar tick labels are rotated 180 degrees but colors stay the same.
DThe colorbar tick labels become bold but colors stay the same.
Attempts:
2 left
💡 Hint

Think about what inverting the y-axis means visually.

Practice

(1/5)
1. What is the main purpose of adding a colorbar to a matplotlib plot?
easy
A. To show the scale of colors representing data values
B. To add a title to the plot
C. To change the background color of the plot
D. To display the axis labels

Solution

  1. Step 1: Understand the role of color in plots

    Colors in a plot often represent data values or categories.
  2. Step 2: Purpose of colorbar

    A colorbar explains what each color means by showing a scale or legend.
  3. Final Answer:

    To show the scale of colors representing data values -> Option A
  4. Quick Check:

    Colorbar = color scale legend [OK]
Hint: Colorbar explains colors' meaning in data [OK]
Common Mistakes:
  • Confusing colorbar with plot title
  • Thinking colorbar changes plot background
  • Mixing colorbar with axis labels
2. Which of the following is the correct way to add a colorbar to a matplotlib plot stored in variable im?
easy
A. plt.colorbar()
B. plt.colorbar(im)
C. im.colorbar()
D. plt.add_colorbar(im)

Solution

  1. Step 1: Recall matplotlib colorbar syntax

    The function plt.colorbar() requires the image or mappable object as an argument.
  2. Step 2: Check each option

    plt.colorbar(im) correctly calls plt.colorbar(im). plt.colorbar() misses the argument. im.colorbar() is invalid method. plt.add_colorbar(im) is not a matplotlib function.
  3. Final Answer:

    plt.colorbar(im) -> Option B
  4. Quick Check:

    plt.colorbar(im) adds colorbar [OK]
Hint: Always pass the image object to plt.colorbar() [OK]
Common Mistakes:
  • Calling plt.colorbar() without argument
  • Using non-existent methods like im.colorbar()
  • Trying plt.add_colorbar() which doesn't exist
3. What will be the effect of this code snippet on the colorbar ticks?
import matplotlib.pyplot as plt
import numpy as np

img = plt.imshow(np.random.rand(5,5))
cbar = plt.colorbar(img)
cbar.set_ticks([0, 0.5, 1])
cbar.set_ticklabels(['Low', 'Medium', 'High'])
plt.show()
medium
A. Colorbar will have no ticks displayed
B. Colorbar will show default ticks ignoring set_ticks and set_ticklabels
C. Code will raise an error because set_ticklabels is invalid
D. Colorbar will show ticks at 0, 0.5, 1 labeled as Low, Medium, High

Solution

  1. Step 1: Understand set_ticks and set_ticklabels

    set_ticks sets positions of ticks; set_ticklabels sets their text labels.
  2. Step 2: Analyze the code

    The code sets ticks at 0, 0.5, 1 and labels them as Low, Medium, High respectively.
  3. Final Answer:

    Colorbar will show ticks at 0, 0.5, 1 labeled as Low, Medium, High -> Option D
  4. Quick Check:

    set_ticks + set_ticklabels changes tick positions and labels [OK]
Hint: Use set_ticks and set_ticklabels to customize colorbar ticks [OK]
Common Mistakes:
  • Assuming set_ticklabels is invalid
  • Expecting default ticks despite setting new ones
  • Thinking ticks will disappear
4. Identify the error in this code that tries to format the colorbar ticks:
import matplotlib.pyplot as plt
import numpy as np

img = plt.imshow(np.random.rand(5,5))
cbar = plt.colorbar(img)
cbar.set_ticks([0, 0.5, 1])
cbar.set_ticklabels('Low', 'Medium', 'High')
plt.show()
medium
A. plt.colorbar() cannot be assigned to a variable
B. set_ticks must be called after set_ticklabels
C. set_ticklabels expects a list, not separate string arguments
D. imshow requires integer data, not float

Solution

  1. Step 1: Check set_ticklabels usage

    set_ticklabels requires a single list or iterable of labels, not separate arguments.
  2. Step 2: Identify the error in code

    The code passes separate strings instead of a list, causing a TypeError.
  3. Final Answer:

    set_ticklabels expects a list, not separate string arguments -> Option C
  4. Quick Check:

    set_ticklabels(['Low', 'Medium', 'High']) correct [OK]
Hint: Pass labels as a list to set_ticklabels [OK]
Common Mistakes:
  • Passing multiple strings instead of a list
  • Calling set_ticks after set_ticklabels (order doesn't matter)
  • Misunderstanding plt.colorbar() return value
  • Thinking imshow needs integers only
5. You want to format a colorbar to show percentage ticks from 0% to 100% with steps of 25%. Which code snippet correctly formats the colorbar ticks and labels?
hard
A. cbar.set_ticks([0, 0.25, 0.5, 0.75, 1]) cbar.set_ticklabels(['0%', '25%', '50%', '75%', '100%'])
B. cbar.set_ticks(['0%', '25%', '50%', '75%', '100%']) cbar.set_ticklabels([0, 0.25, 0.5, 0.75, 1])
C. cbar.set_ticks([0, 25, 50, 75, 100]) cbar.set_ticklabels(['0%', '25%', '50%', '75%', '100%'])
D. cbar.set_ticks([0, 0.25, 0.5, 0.75, 1]) cbar.set_ticklabels([0, 25, 50, 75, 100])

Solution

  1. Step 1: Understand colorbar data range

    Colorbar values range from 0 to 1 for normalized data.
  2. Step 2: Set ticks and labels correctly

    Ticks must be numeric positions (0 to 1), labels are strings with % signs.
  3. Step 3: Analyze options

    cbar.set_ticks([0, 0.25, 0.5, 0.75, 1]) cbar.set_ticklabels(['0%', '25%', '50%', '75%', '100%']) correctly sets numeric ticks and string labels. cbar.set_ticks(['0%', '25%', '50%', '75%', '100%']) cbar.set_ticklabels([0, 0.25, 0.5, 0.75, 1]) swaps types incorrectly. cbar.set_ticks([0, 25, 50, 75, 100]) cbar.set_ticklabels(['0%', '25%', '50%', '75%', '100%']) uses ticks outside 0-1 range. cbar.set_ticks([0, 0.25, 0.5, 0.75, 1]) cbar.set_ticklabels([0, 25, 50, 75, 100]) sets numeric ticks but labels as numbers without %.
  4. Final Answer:

    cbar.set_ticks([0, 0.25, 0.5, 0.75, 1]) cbar.set_ticklabels(['0%', '25%', '50%', '75%', '100%']) -> Option A
  5. Quick Check:

    Ticks numeric, labels string with % [OK]
Hint: Ticks numeric 0-1; labels as strings with % [OK]
Common Mistakes:
  • Using tick positions as strings
  • Setting ticks outside 0-1 range
  • Labeling ticks with numbers missing % sign
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