Bird
Raised Fist0
Matplotlibdata~10 mins

Color mapping with colorbar in Matplotlib - Step-by-Step Execution

Choose your learning style10 modes available
Concept Flow - Color mapping with colorbar
Create data values
↓
Choose colormap
↓
Map data to colors
↓
Plot data with colors
↓
Add colorbar to show scale
↓
Display plot
This flow shows how data values are linked to colors using a colormap, then plotted with a colorbar to explain the color scale.
Execution Sample
Matplotlib
import matplotlib.pyplot as plt
import numpy as np
from matplotlib.colors import Normalize

values = np.array([1, 2, 3, 4, 5])
colors = plt.cm.viridis(values / 5)

plt.scatter(values, values, color=colors)
plt.colorbar(plt.cm.ScalarMappable(cmap='viridis', norm=Normalize(0, 5)))
plt.show()
This code maps numeric values to colors using the 'viridis' colormap, plots them, and adds a colorbar to show the color scale.
Execution Table
StepActionData/VariableResult/Output
1Create data arrayvalues[1 2 3 4 5]
2Normalize values for colormapvalues / 5[0.2 0.4 0.6 0.8 1.0]
3Map normalized values to colorsplt.cm.viridis(values / 5)Array of RGBA colors
4Plot scatter points with colorsplt.scatterScatter plot with colored points
5Create ScalarMappable for colorbarScalarMappable(cmap='viridis', norm=Normalize(0, 5))Colorbar object linked to data range
6Add colorbar to plotplt.colorbarColorbar displayed alongside plot
7Show plotplt.show()Plot window appears with points and colorbar
8End-Execution complete
💡 All steps executed; plot with color-mapped points and colorbar displayed.
Variable Tracker
VariableStartAfter Step 1After Step 2After Step 3Final
values-[1 2 3 4 5][1 2 3 4 5][1 2 3 4 5][1 2 3 4 5]
normalized_values--[0.2 0.4 0.6 0.8 1.0][0.2 0.4 0.6 0.8 1.0][0.2 0.4 0.6 0.8 1.0]
colors---Array of RGBA colorsArray of RGBA colors
Key Moments - 3 Insights
Why do we divide values by 5 before applying the colormap?
Dividing by 5 normalizes the data to the range 0 to 1, which is required because colormaps expect input values between 0 and 1. See execution_table step 2.
What does the ScalarMappable do for the colorbar?
ScalarMappable links the colormap and normalization to the colorbar, so it knows how to map data values to colors. This is shown in execution_table step 5.
Why do the colors in the scatter plot match the colorbar scale?
Because both use the same colormap and normalization, the colors of points correspond exactly to the colorbar's color scale. See steps 3 and 6.
Visual Quiz - 3 Questions
Test your understanding
Look at the execution_table step 2, what is the normalized value for the original data value 3?
A0.6
B0.3
C3
D1.5
💡 Hint
Check the 'Data/Variable' column in step 2 showing values divided by 5.
At which step is the colorbar object created?
AStep 3
BStep 6
CStep 5
DStep 4
💡 Hint
Look at the 'Action' column describing ScalarMappable creation.
If we change the normalization range from (0,5) to (1,5), what happens to the color mapping?
AColors stay the same, no change
BColors shift to include lower values, changing the colorbar scale
CPlot will error due to invalid normalization
DColorbar disappears
💡 Hint
Normalization controls how data values map to colors; changing range affects colorbar and colors.
Concept Snapshot
Color mapping links data values to colors using a colormap.
Normalize data to 0-1 before mapping.
Plot data points with mapped colors.
Add a colorbar using ScalarMappable to show color scale.
Colorbar helps interpret colors in the plot.
Full Transcript
This visual execution shows how to map numeric data to colors using matplotlib's colormap. First, data values are created and normalized to a 0 to 1 range because colormaps expect inputs in this range. Then, these normalized values are converted to RGBA colors using a chosen colormap, here 'viridis'. The colored points are plotted using scatter. To explain the color meaning, a colorbar is added by creating a ScalarMappable object that links the colormap and normalization. Finally, the plot with colored points and the colorbar is displayed. Key moments include understanding normalization, the role of ScalarMappable, and how colors correspond between points and the colorbar.

Practice

(1/5)
1. What is the main purpose of adding a colorbar in a matplotlib plot with color mapping?
easy
A. To show the scale of colors representing data values
B. To change the plot title
C. To add grid lines to the plot
D. To save the plot as an image file

Solution

  1. Step 1: Understand color mapping

    Color mapping assigns colors to data values to visualize differences.
  2. Step 2: Role of colorbar

    The colorbar shows which colors correspond to which data values, acting as a legend.
  3. Final Answer:

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

    Colorbar explains colors = B [OK]
Hint: Colorbar always explains color scale in plots [OK]
Common Mistakes:
  • Thinking colorbar changes plot title
  • Confusing colorbar with grid lines
  • Assuming colorbar saves the plot
2. Which of the following is the correct way to add a colorbar to a scatter plot in matplotlib?
easy
A. plt.scatter(x, y); plt.colorbar(c=z)
B. plt.colorbar(); plt.scatter(x, y, c=z)
C. plt.scatter(x, y, c=z); plt.colorbar()
D. plt.scatter(x, y, c=z, colorbar=True)

Solution

  1. Step 1: Plot with color mapping

    Use plt.scatter(x, y, c=z) to map colors to values z.
  2. Step 2: Add colorbar after plotting

    Call plt.colorbar() after the scatter plot to add the color scale.
  3. Final Answer:

    plt.scatter(x, y, c=z); plt.colorbar() -> Option C
  4. Quick Check:

    Plot first, then colorbar [OK]
Hint: Call plt.colorbar() after plotting with color data [OK]
Common Mistakes:
  • Calling plt.colorbar() before plotting
  • Passing colorbar as a parameter to scatter
  • Trying to pass c=z inside plt.colorbar()
3. What will the following code display?
import matplotlib.pyplot as plt
import numpy as np
x = np.arange(5)
y = np.arange(5)
z = x * y
plt.scatter(x, y, c=z)
plt.colorbar()
plt.show()
medium
A. A scatter plot with points colored from 0 to 16 and a colorbar showing this range
B. A scatter plot with all points in the same color and no colorbar
C. A line plot connecting points with a colorbar
D. An error because colorbar needs a colormap argument

Solution

  1. Step 1: Understand data and color mapping

    x and y are arrays 0 to 4, z is their product (0,1,4,9,16).
  2. Step 2: Scatter plot with color mapping and colorbar

    Points colored by z values, colorbar shows color scale from min to max z.
  3. Final Answer:

    A scatter plot with points colored from 0 to 16 and a colorbar showing this range -> Option A
  4. Quick Check:

    Color mapped scatter with colorbar = D [OK]
Hint: Colorbar shows range of c= values in scatter [OK]
Common Mistakes:
  • Thinking colorbar is missing
  • Expecting a line plot instead of scatter
  • Believing colorbar needs explicit colormap argument
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

  1. Step 1: Check scatter plot parameters

    Scatter plot lacks c= parameter, so no color mapping exists.
  2. Step 2: Understand colorbar requirement

    Colorbar needs a mappable object with colors; without c=, colorbar cannot be created.
  3. Final Answer:

    Error because scatter plot has no color mapping (c parameter missing) -> Option D
  4. 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

  1. Step 1: Set color limits in imshow

    Use vmin=0 and vmax=1 in imshow to fix color scale range.
  2. Step 2: Add colorbar without extra arguments

    Call plt.colorbar() after plotting to add the colorbar matching the scale.
  3. Final Answer:

    plt.imshow(data, vmin=0, vmax=1); plt.colorbar() -> Option B
  4. 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 unknown strong while earning +1 Grip toward your certificate.

10 questions~5 mineasy hard