Bird
Raised Fist0
Matplotlibdata~20 mins

Image colormaps in Matplotlib - Practice Problems & Coding Challenges

Choose your learning style10 modes available

Start learning this pattern below

Jump into concepts and practice - no test required

or
Recommended
Test this pattern10 questions across easy, medium, and hard to know if this pattern is strong
Challenge - 5 Problems
🎖️
Colormap Mastery
Get all challenges correct to earn this badge!
Test your skills under time pressure!
Predict Output
intermediate
2:00remaining
Output of applying 'viridis' colormap to a grayscale image
What is the shape and data type of the output array after applying the 'viridis' colormap to a 2D grayscale image using matplotlib's cm.viridis?
Matplotlib
import numpy as np
import matplotlib.cm as cm

gray_image = np.array([[0, 128], [192, 255]], dtype=np.uint8)
colored_image = cm.viridis(gray_image / 255.0)
print(colored_image.shape, colored_image.dtype)
A(2, 2, 4) float32
B(2, 2, 4) float64
C(2, 2, 3) float32
D(2, 2) uint8
Attempts:
2 left
💡 Hint
Remember that matplotlib colormaps return RGBA values as floats between 0 and 1.
data_output
intermediate
1:30remaining
Number of unique colors after applying 'gray' colormap
Given a 1D numpy array with values [0, 0.5, 1.0], what is the number of unique colors in the output after applying the 'gray' colormap from matplotlib?
Matplotlib
import numpy as np
import matplotlib.cm as cm

values = np.array([0, 0.5, 1.0])
colors = cm.gray(values)
unique_colors = np.unique(colors, axis=0)
print(len(unique_colors))
A3
B2
C1
D4
Attempts:
2 left
💡 Hint
Check if the colormap maps different input values to distinct RGBA colors.
visualization
advanced
2:30remaining
Visualizing the effect of 'hot' colormap on a gradient image
Which option shows the correct matplotlib code to display a horizontal gradient image with the 'hot' colormap applied?
A
import numpy as np
import matplotlib.pyplot as plt
img = np.linspace(0, 1, 256).reshape(-1, 1)
plt.imshow(img, cmap='hot')
plt.axis('on')
plt.show()
B
import numpy as np
import matplotlib.pyplot as plt
img = np.linspace(0, 1, 256)
plt.imshow(img, cmap='hot')
plt.axis('off')
plt.show()
C
import numpy as np
import matplotlib.pyplot as plt
img = np.linspace(0, 1, 256).reshape(1, -1)
plt.imshow(img, cmap='hot')
plt.axis('on')
plt.show()
D
import numpy as np
import matplotlib.pyplot as plt
img = np.linspace(0, 1, 256).reshape(1, -1)
plt.imshow(img, cmap='hot', aspect='auto')
plt.axis('off')
plt.show()
Attempts:
2 left
💡 Hint
A horizontal gradient image should have shape (1, width) and axis turned off for clean display.
🔧 Debug
advanced
1:30remaining
Identify the error when applying colormap to integer image
What error will occur when running this code snippet?
import numpy as np
import matplotlib.cm as cm
img = np.array([[0, 255], [128, 64]], dtype=np.uint8)
colored = cm.plasma(img)
print(colored)
ATypeError: float argument required, not numpy.uint8
BValueError: Input values must be in the range 0 to 1
CNo error, prints RGBA array
DAttributeError: module 'matplotlib.cm' has no attribute 'plasma'
Attempts:
2 left
💡 Hint
Colormaps expect input values normalized between 0 and 1.
🚀 Application
expert
3:00remaining
Combining two colormaps to create a custom colormap
Which code correctly creates a new colormap by combining the first half of 'Blues' and the second half of 'Reds' colormaps?
A
import numpy as np
import matplotlib.pyplot as plt
from matplotlib.colors import LinearSegmentedColormap

blues = plt.cm.Blues(np.linspace(0, 1, 128))
reds = plt.cm.Reds(np.linspace(0, 1, 128))
newcolors = np.vstack((blues[:128], reds[128:]))
newcmp = LinearSegmentedColormap.from_list('BlueRed', newcolors)
print(newcmp(0.5))
B
import numpy as np
import matplotlib.pyplot as plt
from matplotlib.colors import LinearSegmentedColormap

blues = plt.cm.Blues(np.linspace(0, 1, 128))
reds = plt.cm.Reds(np.linspace(0, 1, 128))
newcolors = np.vstack((blues[:64], reds[64:]))
newcmp = LinearSegmentedColormap.from_list('BlueRed', newcolors)
print(newcmp(0.75))
C
import numpy as np
import matplotlib.pyplot as plt
from matplotlib.colors import LinearSegmentedColormap

blues = plt.cm.Blues(np.linspace(0, 1, 256))
reds = plt.cm.Reds(np.linspace(0, 1, 256))
newcolors = np.vstack((blues[:128], reds[128:]))
newcmp = LinearSegmentedColormap.from_list('BlueRed', newcolors)
print(newcmp(0.5))
D
import numpy as np
import matplotlib.pyplot as plt
from matplotlib.colors import LinearSegmentedColormap

blues = plt.cm.Blues(np.linspace(0, 1, 128))
reds = plt.cm.Reds(np.linspace(0, 1, 128))
newcolors = np.vstack((blues[:64], reds[64:]))
newcmp = LinearSegmentedColormap.from_list('BlueRed', newcolors)
print(newcmp(0.5))
Attempts:
2 left
💡 Hint
Ensure the slices cover half of the arrays and the arrays have matching sizes before stacking.

Practice

(1/5)
1. What does the cmap parameter do in plt.imshow() when displaying an image?
easy
A. It changes how numbers map to colors in the image.
B. It changes the image size.
C. It adds a title to the image.
D. It saves the image to a file.

Solution

  1. Step 1: Understand the role of cmap in plt.imshow()

    The cmap parameter controls the colormap, which maps numeric values to colors in the image.
  2. Step 2: Identify what cmap affects visually

    Changing cmap changes the colors shown, helping interpret data better.
  3. Final Answer:

    It changes how numbers map to colors in the image. -> Option A
  4. Quick Check:

    Colormap = color mapping [OK]
Hint: Remember: cmap controls colors, not size or titles [OK]
Common Mistakes:
  • Thinking cmap changes image size
  • Confusing cmap with adding titles
  • Assuming cmap saves the image
2. Which of the following is the correct way to apply the 'viridis' colormap to an image using matplotlib?
easy
A. plt.imshow(image, color='viridis')
B. plt.imshow(image, cmap='viridis')
C. plt.imshow(image, cmap=viridis)
D. plt.imshow(image, colormap='viridis')

Solution

  1. Step 1: Recall the correct parameter name for colormap

    The parameter to set colormap in plt.imshow() is cmap, and it expects a string name.
  2. Step 2: Check the syntax for passing the colormap

    Passing cmap='viridis' is correct. Using color or colormap is incorrect, and omitting quotes causes an error.
  3. Final Answer:

    plt.imshow(image, cmap='viridis') -> Option B
  4. Quick Check:

    Use cmap='name' syntax [OK]
Hint: Use cmap='colormap_name' exactly [OK]
Common Mistakes:
  • Using color instead of cmap
  • Forgetting quotes around colormap name
  • Using colormap instead of cmap
3. What will the following code display?
import matplotlib.pyplot as plt
import numpy as np
image = np.array([[0, 1], [2, 3]])
plt.imshow(image, cmap='gray')
plt.colorbar()
plt.show()
medium
A. A 2x2 image with shades of gray from black (0) to white (3) and a colorbar showing values 0 to 3.
B. A 2x2 image with random colors and no colorbar.
C. A 2x2 image with rainbow colors and a colorbar showing values 0 to 1.
D. An error because 'gray' is not a valid colormap.

Solution

  1. Step 1: Understand the image data and colormap

    The image is a 2x2 array with values 0 to 3. The 'gray' colormap maps low values to black and high values to white.
  2. Step 2: Analyze the colorbar and display

    The colorbar shows the numeric range from 0 to 3, matching the image values. The image colors range from black (0) to white (3).
  3. Final Answer:

    A 2x2 image with shades of gray from black (0) to white (3) and a colorbar showing values 0 to 3. -> Option A
  4. Quick Check:

    Gray cmap maps 0-3 to black-white [OK]
Hint: Gray cmap means black to white shades [OK]
Common Mistakes:
  • Thinking 'gray' is invalid
  • Ignoring the colorbar range
  • Assuming rainbow colors with 'gray'
4. The code below is intended to show an image with the 'hot' colormap and a colorbar, but it raises an error. What is the problem?
import matplotlib.pyplot as plt
import numpy as np
image = np.random.rand(3,3)
plt.imshow(image, cmap=hot)
plt.colorbar()
plt.show()
medium
A. plt.colorbar() must be called before plt.imshow().
B. The image array shape is invalid for imshow.
C. The colormap name 'hot' should be a string: cmap='hot'.
D. np.random.rand() cannot be used for images.

Solution

  1. Step 1: Check the cmap parameter usage

    The colormap name must be a string. Here, hot is used without quotes, causing a NameError.
  2. Step 2: Verify other code parts

    The image shape is valid, and colorbar usage is correct. np.random.rand() is valid for image data.
  3. Final Answer:

    The colormap name 'hot' should be a string: cmap='hot'. -> Option C
  4. Quick Check:

    Colormap names need quotes [OK]
Hint: Always put colormap names in quotes [OK]
Common Mistakes:
  • Forgetting quotes around colormap name
  • Thinking image shape is wrong
  • Misordering colorbar and imshow
5. You have a 5x5 numpy array with values from 0 to 24. You want to display it using plt.imshow() with the 'coolwarm' colormap but only show colors for values between 5 and 20. Which code snippet correctly applies this?
hard
A. plt.imshow(data, cmap='coolwarm'); plt.colorbar(vmin=5, vmax=20)
B. plt.imshow(data, cmap='coolwarm', min=5, max=20); plt.colorbar()
C. plt.imshow(data, cmap='coolwarm', clip=(5,20)); plt.colorbar()
D. plt.imshow(data, cmap='coolwarm', vmin=5, vmax=20); plt.colorbar()

Solution

  1. Step 1: Understand how to limit color range in imshow

    Use vmin and vmax parameters to set the data range for colormap scaling.
  2. Step 2: Check each option for correct syntax

    plt.imshow(data, cmap='coolwarm', vmin=5, vmax=20); plt.colorbar() uses vmin=5 and vmax=20, which is correct. Other options use invalid parameters or place them incorrectly.
  3. Final Answer:

    plt.imshow(data, cmap='coolwarm', vmin=5, vmax=20); plt.colorbar() -> Option D
  4. Quick Check:

    Use vmin and vmax to clip colors [OK]
Hint: Use vmin and vmax to set color limits [OK]
Common Mistakes:
  • Using min/max instead of vmin/vmax
  • Trying to clip with non-existent parameters
  • Passing vmin/vmax to colorbar instead of imshow