Bird
Raised Fist0
Matplotlibdata~10 mins

Custom colormaps in Matplotlib - Step-by-Step Execution

Choose your learning style10 modes available
Concept Flow - Custom colormaps
Define colors or color list
↓
Create colormap object
↓
Use colormap in plot
↓
Display plot with custom colors
You start by choosing colors, then create a colormap object, use it in a plot, and finally display the plot with your custom colors.
Execution Sample
Matplotlib
import matplotlib.pyplot as plt
import numpy as np
from matplotlib.colors import LinearSegmentedColormap

colors = ['blue', 'white', 'red']
cm = LinearSegmentedColormap.from_list('my_cmap', colors)

x = np.linspace(0, 10, 100)
y = np.sin(x)
plt.scatter(x, y, c=y, cmap=cm)
plt.colorbar()
plt.show()
This code creates a custom colormap from blue to white to red and uses it to color points in a scatter plot based on their y-values.
Execution Table
StepActionInput/VariableOutput/Result
1Define colors listcolors = ['blue', 'white', 'red']colors list created
2Create colormapLinearSegmentedColormap.from_list('my_cmap', colors)cm = custom colormap object
3Generate datax = np.linspace(0,10,100), y = np.sin(x)x and y arrays created
4Plot scatterplt.scatter(x, y, c=y, cmap=cm)Scatter plot with colors from cm
5Add colorbarplt.colorbar()Colorbar shown with custom colors
6Show plotplt.show()Plot window opens with colored scatter
7EndNo more codeExecution stops
💡 All steps completed, plot displayed and execution ends
Variable Tracker
VariableStartAfter Step 1After Step 2After Step 3After Step 4Final
colorsundefined['blue', 'white', 'red']['blue', 'white', 'red']['blue', 'white', 'red']['blue', 'white', 'red']['blue', 'white', 'red']
cmundefinedundefinedcustom colormap objectcustom colormap objectcustom colormap objectcustom colormap object
xundefinedundefinedundefinedarray of 100 floats from 0 to 10array of 100 floats from 0 to 10array of 100 floats from 0 to 10
yundefinedundefinedundefinedarray of 100 sin valuesarray of 100 sin valuesarray of 100 sin values
Key Moments - 3 Insights
Why do we use LinearSegmentedColormap.from_list instead of just a list of colors?
Because matplotlib needs a colormap object to map numeric values to colors smoothly. The list alone is just colors, but from_list creates a colormap that interpolates between them, as shown in execution_table step 2.
How does the scatter plot know which color to use for each point?
The scatter plot uses the 'c' argument with y-values and the custom colormap 'cm' to map each y-value to a color. This mapping happens in execution_table step 4.
What does plt.colorbar() do with a custom colormap?
It shows a color scale that matches the custom colormap, helping us understand which colors correspond to which data values, as seen in execution_table step 5.
Visual Quiz - 3 Questions
Test your understanding
Look at the execution_table, what is the value of 'cm' after step 2?
AA list of colors
BA custom colormap object
CAn array of numbers
DUndefined
💡 Hint
Check the 'Output/Result' column for step 2 in execution_table.
At which step does the scatter plot get created with the custom colormap?
AStep 3
BStep 5
CStep 4
DStep 6
💡 Hint
Look for the action 'Plot scatter' in execution_table.
If you changed the colors list to ['green', 'yellow'], what would change in the variable_tracker?
AThe 'colors' variable after step 1 would be ['green', 'yellow']
BThe 'cm' variable would become undefined
CThe 'x' and 'y' variables would change
DNo variables would change
💡 Hint
Check how 'colors' is tracked in variable_tracker after step 1.
Concept Snapshot
Custom colormaps let you define your own color gradients.
Use matplotlib.colors.LinearSegmentedColormap.from_list(name, colors) to create one.
Pass this colormap to plotting functions with the cmap parameter.
Use plt.colorbar() to show the color scale.
This helps visualize data with colors you choose.
Full Transcript
This lesson shows how to create and use custom colormaps in matplotlib. First, you define a list of colors you want in your gradient. Then, you create a colormap object using LinearSegmentedColormap.from_list. Next, you generate some data and plot it using a scatter plot, applying your custom colormap to color the points based on their values. Adding plt.colorbar() displays the color scale. Finally, plt.show() opens the plot window. The execution table traces each step, showing how variables like colors, cm, x, and y change. Key moments clarify why a colormap object is needed, how colors map to data points, and the role of the colorbar. The quiz tests your understanding of these steps and variable changes. This visual trace helps beginners see exactly how custom colormaps work in practice.

Practice

(1/5)
1. What is the main purpose of creating a custom colormap in matplotlib?
easy
A. To speed up the plotting process
B. To automatically label axes
C. To choose colors that better represent your data and improve chart clarity
D. To change the plot size

Solution

  1. Step 1: Understand what colormaps do

    Colormaps assign colors to data values in a plot to help visualize differences.
  2. Step 2: Identify the benefit of custom colormaps

    Custom colormaps let you pick colors that fit your data and style, making charts clearer and more attractive.
  3. Final Answer:

    To choose colors that better represent your data and improve chart clarity -> Option C
  4. Quick Check:

    Custom colormaps improve data visualization clarity = B [OK]
Hint: Custom colormaps improve how data colors show up [OK]
Common Mistakes:
  • Thinking colormaps speed up plotting
  • Confusing colormaps with axis labels
  • Assuming colormaps change plot size
2. Which of the following is the correct way to create a custom colormap from a list of colors in matplotlib?
easy
A. LinearSegmentedColormap.from_list('mycmap', ['red', 'green', 'blue'])
B. plt.colormap(['red', 'green', 'blue'])
C. color_map(['red', 'green', 'blue'])
D. create_colormap(['red', 'green', 'blue'])

Solution

  1. Step 1: Recall the correct function for custom colormaps

    Matplotlib uses LinearSegmentedColormap.from_list to create colormaps from color lists.
  2. Step 2: Check the syntax

    The correct syntax is LinearSegmentedColormap.from_list('mycmap', ['red', 'green', 'blue']). Other options are not valid matplotlib functions.
  3. Final Answer:

    LinearSegmentedColormap.from_list('mycmap', ['red', 'green', 'blue']) -> Option A
  4. Quick Check:

    Use LinearSegmentedColormap.from_list for custom colormaps = A [OK]
Hint: Use LinearSegmentedColormap.from_list with color list [OK]
Common Mistakes:
  • Using plt.colormap which does not exist
  • Trying to call create_colormap which is not a function
  • Confusing function names
3. What will be the output of this code snippet?
import matplotlib.pyplot as plt
from matplotlib.colors import LinearSegmentedColormap

colors = ['yellow', (1, 0.5, 0), 'red']
my_cmap = LinearSegmentedColormap.from_list('mycmap', colors)
print(my_cmap(0.5))
medium
A. Error: Invalid colormap
B. (0.5, 0.5, 0.5, 1.0)
C. (1.0, 0.0, 0.0, 1.0)
D. (1.0, 0.5, 0.0, 1.0)

Solution

  1. Step 1: Understand colormap interpolation

    The colormap is created from yellow, (1, 0.5, 0), and red. At 0.5 (middle), it should be the middle anchor color (1.0, 0.5, 0.0).
  2. Step 2: Check RGBA values for the middle color

    The middle color exactly corresponds to (1.0, 0.5, 0.0, 1.0) in RGBA format, which matches the output.
  3. Final Answer:

    (1.0, 0.5, 0.0, 1.0) -> Option D
  4. Quick Check:

    Middle color in colormap = orange RGBA = A [OK]
Hint: Middle of colormap returns middle color RGBA [OK]
Common Mistakes:
  • Assuming 0.5 returns gray
  • Confusing color order
  • Expecting an error from valid code
4. Identify the error in this code that tries to create a custom colormap:
from matplotlib.colors import LinearSegmentedColormap
colors = ['blue', 'white', 'green']
my_cmap = LinearSegmentedColormap(colors)
medium
A. LinearSegmentedColormap requires 'from_list' method to create from colors
B. Colors list must be strings of hex codes only
C. You must import pyplot to create colormaps
D. The colors list cannot have more than two colors

Solution

  1. Step 1: Check how to create colormaps from colors

    LinearSegmentedColormap is a class and cannot be called directly with a list. Instead, use the class method from_list.
  2. Step 2: Identify the correct usage

    The correct way is LinearSegmentedColormap.from_list('name', colors). The code misses from_list.
  3. Final Answer:

    LinearSegmentedColormap requires 'from_list' method to create from colors -> Option A
  4. Quick Check:

    Use from_list to create colormap from colors = D [OK]
Hint: Use from_list method to create colormap from colors [OK]
Common Mistakes:
  • Calling LinearSegmentedColormap directly
  • Thinking colors must be hex codes
  • Importing pyplot unnecessarily
5. You want to create a custom colormap that smoothly transitions from blue to white to red, but with the white color occupying the middle 40% of the range. Which approach correctly achieves this?
hard
A. Use LinearSegmentedColormap.from_list('bwr', ['blue', 'white', 'red'])
B. Use LinearSegmentedColormap.from_list('bwr', ['blue', 'white', 'white', 'red'], [0, 0.3, 0.7, 1])
C. Use LinearSegmentedColormap.from_list('bwr', ['blue', 'white', 'red'], [0, 0.5, 1])
D. Use LinearSegmentedColormap.from_list('bwr', ['blue', 'red']) and set midpoint to white separately

Solution

  1. Step 1: Understand color position control in colormaps

    To make white occupy the middle 40%, you need to specify positions for colors explicitly.
  2. Step 2: Analyze the options

    Use LinearSegmentedColormap.from_list('bwr', ['blue', 'white', 'white', 'red'], [0, 0.3, 0.7, 1]) uses four colors with positions [0, 0.3, 0.7, 1], placing white twice to stretch it over 40% (from 0.3 to 0.7). This creates a smooth transition with white in the middle range.
  3. Final Answer:

    Use LinearSegmentedColormap.from_list('bwr', ['blue', 'white', 'white', 'red'], [0, 0.3, 0.7, 1]) -> Option B
  4. Quick Check:

    Specify color positions to stretch middle color = C [OK]
Hint: Repeat middle color with positions to stretch it [OK]
Common Mistakes:
  • Not specifying positions, so white is evenly spread
  • Using only three colors without position list
  • Trying to set midpoint color separately
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