MatplotlibXBy @CodeWithMunnaX
Catalog
Track: Subplots & Layouts
Layouts12 mins

25. Twin Axes (twinx / twiny) for Dual Scales

When two correlated metrics share the same X-axis (e.g. date) but operate on completely different scales and units (e.g. Stock Price in $ vs Trading Volume in millions), `ax.twinx()` creates a second Y-axis on the right.

Mental Model Intuition

A ruler with inches marked on the left edge and centimeters marked on the right edge.

Core Concepts & Mechanics

How `twinx()` WorksTwin Axes

`ax2 = ax1.twinx()` creates an overlay axes sharing `ax1`'s X-axis coordinates, but possessing an independent right-hand Y-axis.

Color-code the Y-axis labels and tick numbers to match each curve's color so readers know which axis belongs to which series.
ax2 = ax1.twinx() ax2.plot(x, y2, color='green')

Common Beginner Mistakes & Pro Fixes

Avoid the top errors and bad plotting practices that trip up new Python developers

Troubleshooting

Quick Lesson Takeaways

  • `ax2 = ax1.twinx()` generates a shared X, independent right Y-axis.
  • `ax2 = ax1.twiny()` generates a shared Y, independent top X-axis.
  • Always color-match axis labels with line colors for clarity.
Topic 25 • Python IDE
Python 3.12 • Matplotlib
Run Python code to inspect terminal output.

Real-World Datasets (1-Click Switcher)

Switch from abstract numbers to relatable Cricket, Cinema & Business charts

5 Curated Datasets

Hands-on Challenge: Create Twin Y-Axes

+50 XP

Write Matplotlib code to solve the objective and see your live plot render

Objective Instructions:

Create `fig, ax1 = plt.subplots()`, plot `[1, 2, 3]` and `[10, 20, 30]` on `ax1`, then call `ax2 = ax1.twinx()` and plot `[100, 200, 300]` on `ax2`.

Required Keywords:✓ twinx✓ set_ylabel
Challenge Code Editor
Challenge Output GraphLive Vector Preview
Write code on the left to render live challenge plot
End of Lesson Knowledge Check

Quick Mini Quiz: 2 Concept Questions

Test your understanding to unlock the lesson completion badge

Q1

Which Matplotlib function is used to create a standard continuous 2D line plot?

Q2

What must you call after specifying label='...' so that the legend actually appears on the canvas?

0 of 2 answered