Bird
Raised Fist0
Matplotlibdata~20 mins

Dual y-axis for different scales in Matplotlib - Practice Problems & Coding Challenges

Choose your learning style10 modes available
Challenge - 5 Problems
🎖️
Dual Y-Axis Mastery
Get all challenges correct to earn this badge!
Test your skills under time pressure!
❓ Predict Output
intermediate
2:00remaining
Output of dual y-axis plot code

What will be the output of this Python code using matplotlib?

Matplotlib
import matplotlib.pyplot as plt
x = [1, 2, 3, 4, 5]
y1 = [10, 20, 30, 40, 50]
y2 = [100, 200, 300, 400, 500]
fig, ax1 = plt.subplots()
ax1.plot(x, y1, 'g-')
ax2 = ax1.twinx()
ax2.plot(x, y2, 'b--')
plt.show()
AA single plot with two y-axes: left y-axis green solid line for y1, right y-axis blue dashed line for y2
BTwo separate plots stacked vertically, one with green line and one with blue dashed line
CA plot with one y-axis showing both green and blue lines overlapping
DSyntaxError due to incorrect use of twinx()
Attempts:
2 left
💡 Hint

Remember that twinx() creates a second y-axis sharing the same x-axis.

❓ data_output
intermediate
1:30remaining
Number of ticks on each y-axis

Given this code snippet, how many major ticks will appear on the left and right y-axes respectively?

Matplotlib
import matplotlib.pyplot as plt
x = [1, 2, 3, 4, 5]
y1 = [10, 20, 30, 40, 50]
y2 = [100, 200, 300, 400, 500]
fig, ax1 = plt.subplots()
ax1.plot(x, y1, 'r-')
ax2 = ax1.twinx()
ax2.plot(x, y2, 'b-')
left_ticks = len(ax1.get_yticks())
right_ticks = len(ax2.get_yticks())
print(left_ticks, right_ticks)
A5 6
B5 5
C6 5
D6 6
Attempts:
2 left
💡 Hint

Default matplotlib y-axis ticks usually include the min and max plus intermediate ticks.

🔧 Debug
advanced
2:00remaining
Identify the error in dual y-axis code

What error will this code produce?

Matplotlib
import matplotlib.pyplot as plt
x = [1, 2, 3]
y1 = [10, 20, 30]
y2 = [100, 200, 300]
fig, ax1 = plt.subplots()
ax2 = ax1.twinx()
ax1.plot(x, y1, 'r-')
ax2.plot(x, y2, 'b-')
ax1.set_ylabel('Y1')
ax2.set_ylabel('Y2')
ax1.set_xlabel('X')
ax2.set_xlabel('X')
plt.show()
ANo error; plot shows correctly
BAttributeError: 'AxesSubplot' object has no attribute 'set_xlabel'
CThe second set_xlabel call overwrites the first, no error but confusing labels
DRuntimeWarning: Multiple x-labels set on the same axes
Attempts:
2 left
💡 Hint

Check if setting xlabel on both axes causes an error or just overwrites.

❓ visualization
advanced
1:30remaining
Visual difference between single and dual y-axis plots

Which option best describes the visual difference between these two plots?

Plot 1: Single y-axis plotting y1 and y2 on the same scale.
Plot 2: Dual y-axis plotting y1 on left and y2 on right with different scales.

APlot 1 shows two separate plots; Plot 2 shows one plot with one y-axis
BPlot 1 has two y-axes; Plot 2 has one y-axis
CPlot 1 and Plot 2 look identical
DPlot 1 shows overlapping lines possibly distorted; Plot 2 shows clear lines with separate scales
Attempts:
2 left
💡 Hint

Think about how different scales affect line visibility on one axis.

🧠 Conceptual
expert
1:30remaining
Reason to use dual y-axis in data visualization

Why would a data scientist choose to use a dual y-axis plot?

ATo create two separate plots stacked vertically for better clarity
BTo plot two variables with identical scales for simplicity
CTo compare two variables with very different scales on the same x-axis clearly
DTo avoid labeling axes and keep the plot minimal
Attempts:
2 left
💡 Hint

Think about when one y-axis scale is not enough to show both data sets clearly.

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