4. Identify the error in this code snippet that tries to add a colorbar:
import matplotlib.pyplot as plt
x = [1, 2, 3]
y = [4, 5, 6]
plt.scatter(x, y)
plt.colorbar()
plt.show()
medium
A. Error because plt.show() is missing
B. No error; code runs fine and shows colorbar
C. Error because plt.colorbar() must be called before scatter
D. Error because scatter plot has no color mapping (c parameter missing)
Solution
Step 1: Check scatter plot parameters
Scatter plot lacks c= parameter, so no color mapping exists.
Step 2: Understand colorbar requirement
Colorbar needs a mappable object with colors; without c=, colorbar cannot be created.
Final Answer:
Error because scatter plot has no color mapping (c parameter missing) -> Option D
Quick Check:
Colorbar needs color data = A [OK]
Hint: Colorbar requires color mapping (c=) in plot [OK]
Common Mistakes:
Calling colorbar before plotting
Forgetting plt.show() (though optional)
Assuming colorbar works without color data
5. You want to create a heatmap using imshow with a colorbar that shows values from 0 to 1. Which code snippet correctly sets the color limits and adds the colorbar?
hard
A. plt.imshow(data); plt.colorbar(vmin=0, vmax=1)
B. plt.imshow(data, vmin=0, vmax=1); plt.colorbar()
C. plt.imshow(data, colorbar=True, vmin=0, vmax=1)
D. plt.imshow(data); plt.colorbar(); plt.clim(0, 1)
Solution
Step 1: Set color limits in imshow
Use vmin=0 and vmax=1 in imshow to fix color scale range.
Step 2: Add colorbar without extra arguments
Call plt.colorbar() after plotting to add the colorbar matching the scale.
Final Answer:
plt.imshow(data, vmin=0, vmax=1); plt.colorbar() -> Option B
Quick Check:
Set vmin/vmax in imshow, then colorbar [OK]
Hint: Set vmin/vmax in imshow, then call plt.colorbar() [OK]
Common Mistakes:
Passing vmin/vmax to plt.colorbar() instead of imshow
Using colorbar=True inside imshow (not valid)
Calling plt.clim() after colorbar (wrong order)
Recommended
Ready to prove it?
Pass the test and this pattern moves unknownstrongwhile earning +1 Grip toward your certificate.