Bird
Raised Fist0
Matplotlibdata~15 mins

Secondary axes in Matplotlib - Deep Dive

Choose your learning style10 modes available
Overview - Secondary axes
What is it?
Secondary axes in matplotlib allow you to add an additional axis to a plot that shares the same x or y axis but has a different scale or units. This helps compare two related datasets with different ranges on the same graph. It is useful when you want to visualize two variables that are connected but measured differently. Secondary axes can be placed on the top, bottom, left, or right of the plot.
Why it matters
Without secondary axes, comparing two datasets with different scales on the same plot is confusing or impossible. You might have to create separate plots or lose clarity. Secondary axes solve this by letting you see both datasets clearly in one view, making analysis and communication easier. This is important in real life when you want to compare things like temperature and sales, or speed and fuel consumption, side by side.
Where it fits
Before learning secondary axes, you should understand basic plotting with matplotlib, including how to create simple plots and customize axes. After mastering secondary axes, you can explore advanced visualization techniques like multiple subplots, interactive plots, and custom axis transformations.
Mental Model
Core Idea
Secondary axes let you add a new axis with a different scale to the same plot area, enabling clear comparison of related data with different units.
Think of it like...
It's like having a ruler with centimeters on one side and inches on the other side, so you can measure the same length in two different units without changing the object.
Primary axis (left or bottom) ──────────────┐
                                         │
                                         │
Secondary axis (right or top) ───────────┘

Data plotted shares the same position but uses different scales on these axes.
Build-Up - 7 Steps
1
FoundationBasic single-axis plotting
🤔
Concept: Learn how to create a simple plot with one x and one y axis.
import matplotlib.pyplot as plt x = [1, 2, 3, 4, 5] y = [10, 20, 25, 30, 40] plt.plot(x, y) plt.xlabel('X axis') plt.ylabel('Y axis') plt.title('Simple plot') plt.show()
Result
A line plot with x values on the horizontal axis and y values on the vertical axis.
Understanding how to plot data on a single axis is the foundation for adding more complex features like secondary axes.
2
FoundationUnderstanding axis scales and labels
🤔
Concept: Learn how axis scales and labels represent data ranges and units.
plt.plot(x, y) plt.xlabel('Time (seconds)') plt.ylabel('Distance (meters)') plt.title('Distance over time') plt.show()
Result
The plot shows distance changing over time with clear axis labels indicating units.
Knowing how axis labels and scales communicate data meaning is key before adding a second axis with different units.
3
IntermediateAdding a secondary y-axis
🤔Before reading on: do you think a secondary y-axis shares the same x-axis or y-axis scale? Commit to your answer.
Concept: Introduce a secondary y-axis that shares the x-axis but has a different scale and data.
fig, ax1 = plt.subplots() x = [1, 2, 3, 4, 5] y1 = [10, 20, 25, 30, 40] y2 = [100, 200, 300, 400, 500] ax1.plot(x, y1, 'b-') ax1.set_xlabel('X axis') ax1.set_ylabel('Primary Y axis', color='b') ax2 = ax1.twinx() # Create secondary y-axis sharing x-axis ax2.plot(x, y2, 'r--') ax2.set_ylabel('Secondary Y axis', color='r') plt.title('Plot with secondary y-axis') plt.show()
Result
A plot with two y-axes: left y-axis for y1 data in blue, right y-axis for y2 data in red, sharing the same x-axis.
Understanding that secondary y-axes share the x-axis but have independent y scales allows clear comparison of different data ranges.
4
IntermediateCreating a secondary x-axis
🤔Before reading on: do you think a secondary x-axis shares the same y-axis or x-axis scale? Commit to your answer.
Concept: Learn how to add a secondary x-axis that shares the y-axis but has a different scale or units.
fig, ax = plt.subplots() x = [0, 1, 2, 3, 4] y = [0, 10, 20, 30, 40] ax.plot(x, y) ax.set_xlabel('Primary X axis') ax.set_ylabel('Y axis') # Create secondary x-axis on top with a function converting x secax = ax.secondary_xaxis('top', functions=(lambda x: x * 1.60934, lambda x: x / 1.60934)) secax.set_xlabel('Secondary X axis (km)') plt.title('Plot with secondary x-axis') plt.show()
Result
A plot with primary x-axis in miles at bottom and secondary x-axis in kilometers at top, sharing the same y-axis.
Knowing how to transform data scales for secondary axes helps compare related units like miles and kilometers on the same plot.
5
IntermediateCustom transformations for secondary axes
🤔Before reading on: can secondary axes use any mathematical function for scale conversion? Commit to your answer.
Concept: Learn how to define custom forward and inverse functions to convert between primary and secondary axis scales.
def celsius_to_fahrenheit(c): return c * 9 / 5 + 32 def fahrenheit_to_celsius(f): return (f - 32) * 5 / 9 fig, ax = plt.subplots() x = [0, 10, 20, 30, 40] y = [0, 15, 30, 45, 60] ax.plot(x, y) ax.set_xlabel('Temperature (°C)') ax.set_ylabel('Some measurement') secax = ax.secondary_xaxis('top', functions=(celsius_to_fahrenheit, fahrenheit_to_celsius)) secax.set_xlabel('Temperature (°F)') plt.title('Plot with temperature conversion secondary axis') plt.show()
Result
A plot with primary x-axis in Celsius and secondary x-axis in Fahrenheit, correctly converting between scales.
Understanding custom transformations enables flexible secondary axes for any related units or scales.
6
AdvancedUsing secondary axes with bar and scatter plots
🤔Before reading on: do you think secondary axes work only with line plots or also with bar and scatter plots? Commit to your answer.
Concept: Explore how secondary axes can be applied to different plot types like bar charts and scatter plots.
fig, ax1 = plt.subplots() x = [1, 2, 3, 4, 5] y1 = [5, 7, 9, 6, 8] y2 = [50, 70, 90, 60, 80] ax1.bar(x, y1, color='blue', alpha=0.6) ax1.set_ylabel('Primary Y axis') ax2 = ax1.twinx() ax2.scatter(x, y2, color='red') ax2.set_ylabel('Secondary Y axis') plt.title('Bar and scatter plot with secondary y-axis') plt.show()
Result
A plot showing bars for primary data and scatter points for secondary data with two y-axes.
Knowing that secondary axes work with various plot types expands visualization possibilities beyond simple lines.
7
ExpertHandling layout and tick alignment challenges
🤔Before reading on: do you think secondary axes always align perfectly with primary axes ticks? Commit to your answer.
Concept: Understand the challenges of aligning ticks and labels on secondary axes and how to customize them for clarity.
import matplotlib.ticker as ticker fig, ax1 = plt.subplots() x = range(5) y1 = [1, 2, 3, 4, 5] y2 = [10, 20, 30, 40, 50] ax1.plot(x, y1, 'g-') ax1.set_ylabel('Primary Y') ax2 = ax1.twinx() ax2.plot(x, y2, 'r--') ax2.set_ylabel('Secondary Y') # Customize ticks on secondary axis ax2.yaxis.set_major_locator(ticker.MultipleLocator(10)) ax2.yaxis.set_minor_locator(ticker.AutoMinorLocator()) plt.title('Customized ticks on secondary axis') plt.show()
Result
A plot with two y-axes where secondary axis ticks are customized for better readability and alignment.
Knowing how to control tick placement prevents confusing or cluttered plots when using secondary axes.
Under the Hood
Secondary axes in matplotlib are implemented by creating a new axis object that shares the position and one axis (x or y) with the primary axis but has an independent scale and tick labels. Internally, matplotlib links the secondary axis scale to the primary axis through transformation functions that convert coordinates back and forth. This allows the secondary axis to update dynamically when the primary axis changes, keeping the plot synchronized.
Why designed this way?
This design allows maximum flexibility by reusing the existing axis space without duplicating the plot area. It avoids clutter and makes it easy to compare related data with different units. Alternatives like separate plots or manual scaling were less intuitive and harder to maintain, so matplotlib introduced secondary axes to simplify multi-scale visualization.
┌─────────────────────────────┐
│        Figure Canvas        │
│ ┌───────────────┐           │
│ │ Primary Axis  │◄──────────┤ shares x or y axis
│ │ (main plot)   │           │
│ └───────────────┘           │
│          │                  │
│          ▼                  │
│ ┌─────────────────────────┐ │
│ │ Secondary Axis          │ │
│ │ (linked scale, own ticks)│ │
│ └─────────────────────────┘ │
└─────────────────────────────┘
Myth Busters - 4 Common Misconceptions
Quick: Does a secondary axis create a completely independent plot area? Commit to yes or no.
Common Belief:A secondary axis is a separate plot area independent from the primary axis.
Tap to reveal reality
Reality:A secondary axis shares the same plot area and one axis (x or y) with the primary axis; it only has a different scale and ticks.
Why it matters:Believing it is independent can lead to confusion when trying to align data or interpret the plot, causing miscommunication of results.
Quick: Can secondary axes only be used for y-axes? Commit to yes or no.
Common Belief:Secondary axes can only be added on the y-axis, not the x-axis.
Tap to reveal reality
Reality:Matplotlib supports secondary axes on both x and y axes, allowing flexible comparisons.
Why it matters:Limiting to y-axis only restricts visualization options and misses opportunities to compare data with different x scales.
Quick: Do secondary axes automatically synchronize tick marks with the primary axis? Commit to yes or no.
Common Belief:Secondary axes always have ticks perfectly aligned with the primary axis ticks.
Tap to reveal reality
Reality:Ticks on secondary axes often need manual adjustment because scales differ; automatic alignment is not guaranteed.
Why it matters:Assuming automatic alignment can produce confusing or cluttered plots, reducing clarity and interpretability.
Quick: Is it safe to use any arbitrary function for secondary axis transformations without inverse? Commit to yes or no.
Common Belief:You can use any function for the secondary axis scale conversion without providing an inverse function.
Tap to reveal reality
Reality:Matplotlib requires both forward and inverse functions to correctly map between primary and secondary axes.
Why it matters:Missing the inverse function causes errors or incorrect axis behavior, breaking the plot's integrity.
Expert Zone
1
Secondary axes can be linked with complex nonlinear transformations, not just linear scaling, enabling advanced scientific visualizations.
2
When stacking multiple secondary axes, managing layout and tick visibility becomes critical to avoid clutter and maintain readability.
3
Secondary axes interact with matplotlib's event system, so dynamic updates (like zoom or pan) require careful handling to keep axes synchronized.
When NOT to use
Avoid secondary axes when datasets are unrelated or when the scales differ too much, causing misleading visual comparisons. Instead, use separate subplots or interactive dashboards to present data clearly.
Production Patterns
Professionals use secondary axes in financial charts to show price and volume, in meteorology to compare temperature and humidity, and in engineering to display stress and strain on the same graph, improving insight without clutter.
Connections
Data normalization
Secondary axes often complement normalization by showing raw and normalized data scales side by side.
Understanding normalization helps interpret secondary axes that display data in different units or scales, improving comparison.
Dual-scale thermometers
Secondary axes mimic dual-scale thermometers that show Celsius and Fahrenheit on the same device.
Knowing how physical instruments display multiple scales clarifies why and how secondary axes improve data visualization.
User interface design
Secondary axes relate to UI design principles of showing related information together without overwhelming the user.
Appreciating UI design helps create plots with secondary axes that are clear, intuitive, and user-friendly.
Common Pitfalls
#1Adding a secondary axis without providing inverse transformation functions.
Wrong approach:ax.secondary_xaxis('top', functions=(lambda x: x * 2))
Correct approach:ax.secondary_xaxis('top', functions=(lambda x: x * 2, lambda x: x / 2))
Root cause:Matplotlib requires both forward and inverse functions to map coordinates correctly; missing inverse causes errors.
#2Plotting unrelated data on secondary axes without clear labels or scales.
Wrong approach:ax1.plot(x, y1) ax2 = ax1.twinx() ax2.plot(x, unrelated_data)
Correct approach:ax1.plot(x, y1) ax2 = ax1.twinx() ax2.plot(x, related_data) ax2.set_ylabel('Related units')
Root cause:Confusing or unrelated data on secondary axes misleads viewers and reduces plot clarity.
#3Not customizing tick marks on secondary axes leading to cluttered or misaligned ticks.
Wrong approach:ax2 = ax1.twinx() ax2.plot(x, y2) # No tick customization
Correct approach:ax2 = ax1.twinx() ax2.plot(x, y2) ax2.yaxis.set_major_locator(ticker.MultipleLocator(10))
Root cause:Default ticks may not suit the secondary axis scale, requiring manual adjustment for readability.
Key Takeaways
Secondary axes let you compare related data with different scales on the same plot area, improving clarity.
They require defining how the secondary axis scale relates to the primary axis, often with forward and inverse functions.
Secondary axes can be added to either x or y axes and work with various plot types like line, bar, and scatter plots.
Proper labeling and tick customization are essential to avoid confusion and maintain plot readability.
Understanding when and how to use secondary axes helps create effective visualizations that communicate complex data clearly.

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