Bird
Raised Fist0
Matplotlibdata~12 mins

Dual y-axis for different scales in Matplotlib - Step-by-Step Execution

Choose your learning style10 modes available
Concept Flow - Dual y-axis for different scales
Create main plot with x and y1
↓
Create second y-axis sharing x
↓
Plot y2 on second y-axis
↓
Set labels and colors for clarity
↓
Display combined plot with two y-axes
First, plot data on the main y-axis. Then create a second y-axis sharing the same x-axis. Plot the second data on this new axis. Finally, label both axes and show the plot.
Execution Sample
Matplotlib
import matplotlib.pyplot as plt
import numpy as np
x = np.linspace(0, 10, 100)
y1 = np.sin(x)
y2 = np.exp(x / 10)
fig, ax1 = plt.subplots(figsize=(10, 6))
color = 'tab:red'
ax1.set_xlabel('X data')
ax1.set_ylabel('Y1 data (sin)', color=color)
ax1.plot(x, y1, color=color, linewidth=2)
ax1.tick_params(axis='y', labelcolor=color)
ax2 = ax1.twinx()
color = 'tab:blue'
ax2.set_ylabel('Y2 data (exp)', color=color)
ax2.plot(x, y2, color=color, linewidth=2)
ax2.tick_params(axis='y', labelcolor=color)
fig.tight_layout()
plt.title('Dual Y-Axis Plot: Sine vs Exponential')
plt.show()
Enhanced code with labels, colors matching axes, title, and realistic data (sine on left, exponential on right) for better clarity and visualization.
Execution Table
StepActionVariable/FunctionResult/State
1Import librariesplt, npMatplotlib and NumPy imported
2Create x datax = np.linspace(0, 10, 100)Array of 100 points from 0 to 10
3Create y1 data (sine)y1 = np.sin(x)Sine wave values
4Create y2 data (exp)y2 = np.exp(x / 10)Exponential growth values
5Create figure and ax1fig, ax1 = plt.subplots(figsize=(10, 6))Figure and main axis created
6Set ax1 labelsax1.set_xlabel, ax1.set_ylabelX label and left Y label set (red)
7Plot y1 on ax1ax1.plot(x, y1, color='tab:red')Red sine line on left axis
8Set ax1 tick colorsax1.tick_paramsLeft y-ticks colored red
9Create ax2ax2 = ax1.twinx()Right y-axis sharing x
10Set ax2 labelsax2.set_ylabelRight Y label set (blue)
11Plot y2 on ax2ax2.plot(x, y2, color='tab:blue')Blue exp line on right axis
12Set ax2 tick colorsax2.tick_paramsRight y-ticks colored blue
13Tight layout and titlefig.tight_layout(), plt.titleLayout adjusted, title added
14Show plotplt.show()Dual y-axis plot displayed
💡 Professional dual y-axis plot with matching colors, labels, and scales for disparate data.
Variable Tracker
VariableStartAfter Step 2After Step 3After Step 4After Step 5After Step 7After Step 9After Step 11Final
xundefinedlinspace(0,10,100)linspace(0,10,100)linspace(0,10,100)linspace(0,10,100)linspace(0,10,100)linspace(0,10,100)linspace(0,10,100)linspace(0,10,100)
y1undefinedundefinedsin(x)sin(x)sin(x)sin(x)sin(x)sin(x)sin(x)
y2undefinedundefinedundefinedexp(x/10)exp(x/10)exp(x/10)exp(x/10)exp(x/10)exp(x/10)
figundefinedundefinedundefinedundefinedFigure(10x6)Figure(10x6)Figure(10x6)Figure(10x6)Figure w/ title & layout
ax1undefinedundefinedundefinedundefinedMain axis w/ labelsMain axis w/ red sine plotMain axis w/ red sineMain axis w/ red sineMain axis finalized
ax2undefinedundefinedundefinedundefinedundefinedundefinedTwin y-axisTwin y-axis w/ blue expTwin y-axis finalized
Key Moments - 3 Insights
Why match line colors to axis tick colors?
It visually links each line to its y-axis, preventing confusion (steps 8 & 12). Essential for readability in dual-axis plots.
When is twinx() unnecessary?
If scales are similar (e.g., both y1/y2 ~0-1), plot on single ax1. Use dual only for disparate ranges like sin(±1) vs exp(0-2+).
Role of fig.tight_layout()?
Prevents label overlap between left/right y-axes and x-axis (step 13).
Visual Quiz - 4 Questions
Test your understanding
What does ax1.twinx() create?
ASecond y-axis (right side)
BSecond x-axis
CNew figure
DLegend
💡 Hint
See execution_table step 9: 'Right y-axis sharing x'
Which step plots the blue exponential line?
AStep 7
BStep 11
CStep 6
DStep 14
💡 Hint
'ax2.plot(x, y2, color='tab:blue')' in execution_table.
Why use np.linspace for x?
ADiscrete points only
BRequired for exp
CSaves memory
DSmooth continuous line plot
💡 Hint
100 points from 0-10 create smooth curves vs jagged [1,2,3,4].
Best practice for clarity?
ASame color for both lines
BNo labels needed
CMatch line color to its axis labels/ticks
DAlways use black
💡 Hint
Steps 6-8,10-12: 'tab:red' for ax1, 'tab:blue' for ax2.
Concept Snapshot
Dual y-axis (twinx()) plots disparate scales on shared x.
Key: color-match lines/axes/labels; use tight_layout(); ideal for sin vs exp, sales vs profit, etc.
Avoid if scales similar—use single axis.
Full Transcript
Master dual y-axes: import plt/np; generate x,y1=sin(x),y2=exp(x/10); fig/ax1; label ax1 red/sine; plot red sine; twin ax2 blue/exp; plot blue exp; tight_layout/title/show. Colors link visually; perfect for mixed-scale data viz.

Practice

(1/5)
1. What is the main purpose of using a dual y-axis in a matplotlib plot?
easy
A. To compare two datasets with different scales on the same plot
B. To create two separate plots side by side
C. To add a legend to the plot
D. To change the color of the plot lines

Solution

  1. Step 1: Understand the purpose of dual y-axis

    A dual y-axis allows plotting two datasets with different value ranges on the same graph for easy comparison.
  2. Step 2: Identify the correct use case

    Comparing datasets with different scales requires two y-axes; other options do not describe this purpose.
  3. Final Answer:

    To compare two datasets with different scales on the same plot -> Option A
  4. Quick Check:

    Dual y-axis = compare different scales [OK]
Hint: Dual y-axis means two y-scales on one graph [OK]
Common Mistakes:
  • Thinking dual y-axis creates two separate plots
  • Confusing dual y-axis with adding legends
  • Assuming it changes line colors only
2. Which matplotlib function is used to create a second y-axis sharing the same x-axis?
easy
A. plt.subplots()
B. ax.twiny()
C. ax.twinx()
D. plt.plot()

Solution

  1. Step 1: Recall matplotlib methods for axes

    The method twinx() creates a second y-axis sharing the x-axis.
  2. Step 2: Differentiate from similar methods

    twiny() creates a second x-axis, not y-axis; subplots() creates figure and axes; plot() draws lines.
  3. Final Answer:

    ax.twinx() -> Option C
  4. Quick Check:

    Second y-axis = twinx() [OK]
Hint: Use ax.twinx() for second y-axis, twiny() is for x-axis [OK]
Common Mistakes:
  • Using plt.subplots() to create second y-axis
  • Confusing twinx() with twiny()
  • Trying to use plt.plot() to add axes
3. What will the following code output?
import matplotlib.pyplot as plt
fig, ax1 = plt.subplots()
ax2 = ax1.twinx()
ax1.plot([1, 2, 3], [10, 20, 30], 'g-')
ax2.plot([1, 2, 3], [100, 200, 300], 'b-')
print(len(fig.axes))
medium
A. 2
B. 1
C. 3
D. 4

Solution

  1. Step 1: Understand axes creation

    plt.subplots() creates one axes (ax1), then ax1.twinx() adds a second y-axis (ax2), so total axes are 2.
  2. Step 2: Check figure axes count

    fig.axes is a list of all axes in the figure; after adding ax2, length is 2.
  3. Final Answer:

    2 -> Option A
  4. Quick Check:

    Two axes after twinx() = 2 [OK]
Hint: twinx() adds one more axes, so total axes count increases by 1 [OK]
Common Mistakes:
  • Assuming twinx() replaces the original axes
  • Thinking twinx() adds multiple axes
  • Confusing axes count with number of plots
4. Identify the error in this code snippet for creating dual y-axis:
import matplotlib.pyplot as plt
fig, ax = plt.subplots()
ax2 = plt.twinx()
ax.plot([1,2,3], [10,20,30])
ax2.plot([1,2,3], [100,200,300])
plt.show()
medium
A. plt.show() is missing
B. plt.subplots() should be plt.figure()
C. ax2.plot() should be ax.plot()
D. plt.twinx() should be ax.twinx()

Solution

  1. Step 1: Check method usage for second y-axis

    twinx() is a method of an axes object, not plt module. So plt.twinx() is invalid.
  2. Step 2: Correct method call

    Use ax.twinx() to create the second y-axis sharing the x-axis.
  3. Final Answer:

    plt.twinx() should be ax.twinx() -> Option D
  4. Quick Check:

    twinx() is an axes method, not plt function [OK]
Hint: twinx() must be called on axes object, not plt [OK]
Common Mistakes:
  • Calling twinx() on plt instead of axes
  • Confusing figure and axes creation methods
  • Missing plt.show() (though present here)
5. You want to plot temperature (°C) and rainfall (mm) over months on the same plot with dual y-axes. Which of these code snippets correctly sets different y-axis labels and colors for clarity?
hard
A. ax1.set_xlabel('Temperature (°C)', color='red')\nax2.set_xlabel('Rainfall (mm)', color='blue')
B. ax1.set_ylabel('Temperature (°C)', color='red')\nax2.set_ylabel('Rainfall (mm)', color='blue')
C. ax1.set_ylabel('Rainfall (mm)', color='blue')\nax2.set_ylabel('Temperature (°C)', color='red')
D. ax1.set_title('Temperature and Rainfall')\nax2.set_title('Temperature and Rainfall')

Solution

  1. Step 1: Assign correct y-axis labels

    Temperature and rainfall are y-axis data, so use set_ylabel() on each axis with matching labels.
  2. Step 2: Use colors to distinguish axes

    Setting label colors helps visually separate the two y-axes for clarity.
  3. Final Answer:

    ax1.set_ylabel('Temperature (°C)', color='red')\nax2.set_ylabel('Rainfall (mm)', color='blue') -> Option B
  4. Quick Check:

    Correct y-labels and colors = ax1.set_ylabel('Temperature (°C)', color='red')\nax2.set_ylabel('Rainfall (mm)', color='blue') [OK]
Hint: Label y-axes with units and colors for clear dual-axis plots [OK]
Common Mistakes:
  • Setting x-axis labels instead of y-axis
  • Swapping labels between axes
  • Using titles instead of axis labels
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