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
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.
Step 2: Position ticks between boundaries
Ticks at midpoints like 0.5,1.5,... label categories clearly on discrete colorbar.
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