0
0
Matplotlibdata~10 mins

Discrete colorbars in Matplotlib - Interactive Code Practice

Choose your learning style9 modes available
Practice - 5 Tasks
Answer the questions below
1fill in blank
easy

Complete the code to create a discrete colorbar with 5 colors.

Matplotlib
import matplotlib.pyplot as plt
import numpy as np

cmap = plt.cm.get_cmap('viridis', [1])
fig, ax = plt.subplots()
fig.colorbar(plt.cm.ScalarMappable(cmap=cmap), ax=ax, ticks=range(6))
plt.show()
Drag options to blanks, or click blank then click option'
A5
B10
C3
D7
Attempts:
3 left
💡 Hint
Common Mistakes
Using a number that is too large or too small for the discrete colors.
Forgetting to pass the number of colors to get_cmap.
2fill in blank
medium

Complete the code to set the colorbar ticks correctly for 4 discrete colors.

Matplotlib
import matplotlib.pyplot as plt
import numpy as np

cmap = plt.cm.get_cmap('plasma', 4)
fig, ax = plt.subplots()
cb = fig.colorbar(plt.cm.ScalarMappable(cmap=cmap), ax=ax, ticks=[1])
plt.show()
Drag options to blanks, or click blank then click option'
A[0, 1, 2, 3, 4]
B[1, 2, 3, 4]
C[0.25, 0.5, 0.75, 1]
D[0, 1, 2, 3]
Attempts:
3 left
💡 Hint
Common Mistakes
Using only 4 ticks for 4 colors, which misses the last boundary.
Using fractional ticks that don't align with color boundaries.
3fill in blank
hard

Fix the error in the code to create a discrete colorbar with 3 colors.

Matplotlib
import matplotlib.pyplot as plt

cmap = plt.cm.get_cmap('coolwarm', 3)
fig, ax = plt.subplots()
cb = fig.colorbar(plt.cm.ScalarMappable(cmap=cmap), ax=ax, ticks=range([1]))
plt.show()
Drag options to blanks, or click blank then click option'
A2
B3
C4
D5
Attempts:
3 left
💡 Hint
Common Mistakes
Using ticks range(3) which only gives 3 ticks for 3 colors.
Not setting the number of colors in get_cmap.
4fill in blank
hard

Fill both blanks to create a discrete colorbar with 6 colors and ticks from 0 to 6.

Matplotlib
import matplotlib.pyplot as plt

cmap = plt.cm.get_cmap('[1]', [2])
fig, ax = plt.subplots()
fig.colorbar(plt.cm.ScalarMappable(cmap=cmap), ax=ax, ticks=range(7))
plt.show()
Drag options to blanks, or click blank then click option'
Atab10
B5
C6
Dviridis
Attempts:
3 left
💡 Hint
Common Mistakes
Using a continuous colormap name without specifying discrete colors.
Mismatch between number of colors and ticks.
5fill in blank
hard

Fill all three blanks to create a discrete colorbar with 4 colors, ticks from 0 to 4, and label the ticks with names.

Matplotlib
import matplotlib.pyplot as plt
import numpy as np

labels = ['Low', 'Medium', 'High', 'Very High']
cmap = plt.cm.get_cmap('[1]', [2])
fig, ax = plt.subplots()
cb = fig.colorbar(plt.cm.ScalarMappable(cmap=cmap), ax=ax, ticks=range([3]))
cb.ax.set_yticklabels(labels)
plt.show()
Drag options to blanks, or click blank then click option'
Acoolwarm
B4
C5
Dviridis
Attempts:
3 left
💡 Hint
Common Mistakes
Using wrong number of ticks for the number of colors.
Not matching labels count with colors.