0
0
Matplotlibdata~12 mins

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

Choose your learning style9 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.