Bird
Raised Fist0
Matplotlibdata~10 mins

Secondary axes in Matplotlib - Step-by-Step Execution

Choose your learning style10 modes available
Concept Flow - Secondary axes
Create main plot
↓
Add secondary axis
↓
Define transform functions
↓
Plot data on secondary axis
↓
Show combined plot
First, create a main plot. Then add a secondary axis with transformation functions. Plot data on both axes and display the combined figure.
Execution Sample
Matplotlib
import matplotlib.pyplot as plt
fig, ax = plt.subplots()
ax.plot([0, 1, 2], [0, 1, 4])
secax = ax.secondary_yaxis('right', functions=(lambda x: x/2, lambda x: x*2))
secax.set_ylabel('Secondary axis')
plt.show()
This code plots data on the main y-axis and adds a secondary y-axis on the right with a scaling transform.
Execution Table
StepActionMain axis dataSecondary axis transformSecondary axis labelPlot shown
1Create figure and main axisEmptynullnullNo
2Plot data on main axis[0,1,4]nullnullNo
3Add secondary y-axis on right[0,1,4]Forward: x/2, Inverse: x*2nullNo
4Set label for secondary axis[0,1,4]Forward: x/2, Inverse: x*2Secondary axisNo
5Show plot with both axes[0,1,4]Forward: x/2, Inverse: x*2Secondary axisYes
💡 Plot displayed with main and secondary y-axes after step 5
Variable Tracker
VariableStartAfter Step 2After Step 3After Step 4After Step 5
fignullFigure object createdFigure object createdFigure object createdFigure object created
axnullAxes object createdAxes object createdAxes object createdAxes object created
secaxnullnullSecondaryAxis object createdSecondaryAxis object createdSecondaryAxis object created
main_datanull[0,1,4][0,1,4][0,1,4][0,1,4]
secax_labelnullnullnull'Secondary axis''Secondary axis'
Key Moments - 2 Insights
Why do we need two functions when adding a secondary axis?
The secondary axis needs a forward function to convert main axis values to secondary axis values, and an inverse function to convert back. This ensures correct scaling and interaction, as shown in step 3 of the execution_table.
Does plotting on the main axis automatically update the secondary axis?
No, the secondary axis is linked by the transform functions but does not plot data itself unless explicitly plotted. Step 2 shows main axis plotting, step 3 adds the secondary axis without plotting data on it.
Visual Quiz - 3 Questions
Test your understanding
Look at the execution_table at step 3, what is the inverse transform function for the secondary axis?
Ax / 2
Bx + 2
Cx * 2
Dx - 2
💡 Hint
Check the 'Secondary axis transform' column at step 3 in the execution_table.
At which step is the secondary axis label set?
AStep 4
BStep 2
CStep 3
DStep 5
💡 Hint
Look at the 'Secondary axis label' column in the execution_table.
If we remove the inverse function in step 3, what happens to the secondary axis?
AIt will work the same as before
BIt will not display correctly or may cause errors
CThe main axis data will change
DThe secondary axis label will disappear
💡 Hint
Inverse function is needed for proper scaling as explained in key_moments and shown in step 3.
Concept Snapshot
Secondary axes in matplotlib allow adding an extra axis sharing the same x or y axis.
Use ax.secondary_xaxis or ax.secondary_yaxis with two functions: forward and inverse transforms.
Plot main data on the original axis; secondary axis shows transformed scale.
Set labels on secondary axis for clarity.
Useful for showing data in different units or scales side-by-side.
Full Transcript
This visual execution shows how to add a secondary axis in matplotlib. First, a figure and main axis are created. Then data is plotted on the main axis. Next, a secondary y-axis is added on the right side with two transform functions: one to convert main axis values to secondary axis values, and one to convert back. The secondary axis label is set. Finally, the plot is displayed showing both axes. The key point is that the secondary axis uses transform functions to link scales correctly. The execution table tracks each step and variable changes. The quiz tests understanding of transform functions, labeling, and the role of inverse functions.

Practice

(1/5)
1. What is the main purpose of using secondary_xaxis or secondary_yaxis in matplotlib?
easy
A. To add a new axis with a different scale on the same plot
B. To create a separate figure window
C. To change the color of the existing axis
D. To remove the original axis from the plot

Solution

  1. Step 1: Understand the concept of secondary axes

    Secondary axes allow adding a new axis that shares the same plot but has a different scale or units.
  2. Step 2: Identify the purpose of secondary_xaxis or secondary_yaxis

    These functions add a secondary axis to the existing plot to compare data with different units clearly.
  3. Final Answer:

    To add a new axis with a different scale on the same plot -> Option A
  4. Quick Check:

    Secondary axes = different scale on same plot [OK]
Hint: Secondary axes add a new scale on the same plot [OK]
Common Mistakes:
  • Thinking it creates a new figure
  • Confusing axis color change with adding axes
  • Assuming it removes original axes
2. Which of the following is the correct way to add a secondary y-axis in matplotlib?
easy
A. ax.add_secondary_yaxis('right', functions=(forward, inverse))
B. ax.add_secondary_axis('right', functions=(forward, inverse))
C. ax.secondary_yaxis('right', functions=(forward, inverse))
D. ax.secondary_axis('right', functions=(forward, inverse))

Solution

  1. Step 1: Recall the matplotlib method for secondary y-axis

    The correct method is secondary_yaxis called on the axes object.
  2. Step 2: Match the exact syntax

    The method is ax.secondary_yaxis('right', functions=(forward, inverse)) where 'right' is the position and functions are conversion functions.
  3. Final Answer:

    ax.secondary_yaxis('right', functions=(forward, inverse)) -> Option C
  4. Quick Check:

    Correct method name = secondary_yaxis [OK]
Hint: Use ax.secondary_yaxis with conversion functions [OK]
Common Mistakes:
  • Using incorrect method names like add_secondary_axis
  • Missing the functions parameter
  • Using secondary_axis instead of secondary_yaxis
3. What will be the output of this code snippet?
import matplotlib.pyplot as plt
fig, ax = plt.subplots()
ax.plot([0, 1, 2], [0, 10, 20])

forward = lambda x: x / 10
inverse = lambda x: x * 10
secax = ax.secondary_yaxis('right', functions=(forward, inverse))
print(secax.get_ylim())
medium
A. [0.0, 2.0]
B. [0, 20]
C. [0.0, 200.0]
D. [0, 10]

Solution

  1. Step 1: Understand the original y-axis limits

    The original y-axis data ranges from 0 to 20, so default limits are approximately (0, 20).
  2. Step 2: Apply the forward function to original limits for secondary axis

    The forward function divides by 10, so 0 becomes 0.0 and 20 becomes 2.0 on the secondary axis.
  3. Final Answer:

    [0.0, 2.0] -> Option A
  4. Quick Check:

    Secondary axis limits = original limits / 10 [OK]
Hint: Secondary axis limits = apply forward function to original limits [OK]
Common Mistakes:
  • Confusing forward and inverse functions
  • Expecting original limits instead of transformed
  • Assuming inverse function applies to limits
4. Identify the error in this code that tries to add a secondary x-axis:
import matplotlib.pyplot as plt
fig, ax = plt.subplots()
ax.plot([0, 1, 2], [0, 1, 4])

forward = lambda x: x * 2
inverse = lambda x: x / 2
secax = ax.secondary_xaxis('top', functions=(inverse, forward))
medium
A. The lambda functions should not be used
B. The order of functions in the tuple is reversed
C. The position 'top' is invalid for secondary_xaxis
D. The method name should be secondary_yaxis instead

Solution

  1. Step 1: Check the order of conversion functions

    The first function should convert from primary to secondary axis (forward), the second from secondary to primary (inverse).
  2. Step 2: Identify the mistake in the code

    The code uses (inverse, forward) instead of (forward, inverse), so the order is reversed causing incorrect scaling.
  3. Final Answer:

    The order of functions in the tuple is reversed -> Option B
  4. Quick Check:

    Functions order = (forward, inverse) [OK]
Hint: First function forward, second inverse in tuple [OK]
Common Mistakes:
  • Swapping forward and inverse functions
  • Using invalid axis position
  • Confusing secondary_xaxis with secondary_yaxis
5. You have temperature data in Celsius and want to add a secondary y-axis in Fahrenheit on the right side. Which of these code snippets correctly creates the secondary axis with proper conversion?
hard
A. forward = lambda f: (f - 32) * 5/9 inverse = lambda c: (c * 9/5) + 32 ax.secondary_yaxis('right', functions=(inverse, forward))
B. forward = lambda c: (c * 5/9) + 32 inverse = lambda f: (f - 32) * 9/5 ax.secondary_yaxis('right', functions=(forward, inverse))
C. forward = lambda c: (c - 32) * 5/9 inverse = lambda f: (f * 9/5) + 32 ax.secondary_yaxis('left', functions=(forward, inverse))
D. forward = lambda c: (c * 9/5) + 32 inverse = lambda f: (f - 32) * 5/9 ax.secondary_yaxis('right', functions=(forward, inverse))

Solution

  1. Step 1: Recall Celsius to Fahrenheit conversion formulas

    Celsius to Fahrenheit: F = (C * 9/5) + 32; Fahrenheit to Celsius: C = (F - 32) * 5/9.
  2. Step 2: Match the forward and inverse functions correctly

    Forward converts primary (C) to secondary (F), inverse converts secondary (F) back to primary (C). Position 'right' is correct for secondary y-axis.
  3. Final Answer:

    forward = lambda c: (c * 9/5) + 32 inverse = lambda f: (f - 32) * 5/9 ax.secondary_yaxis('right', functions=(forward, inverse)) -> Option D
  4. Quick Check:

    Correct conversion and axis position = forward = lambda c: (c * 9/5) + 32 inverse = lambda f: (f - 32) * 5/9 ax.secondary_yaxis('right', functions=(forward, inverse)) [OK]
Hint: Forward: C to F; Inverse: F to C; position 'right' for y-axis [OK]
Common Mistakes:
  • Swapping forward and inverse functions
  • Using wrong conversion formulas
  • Placing secondary axis on 'left' instead of 'right'
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