Bird
Raised Fist0
Matplotlibdata~10 mins

Dual y-axis for different scales in Matplotlib - Interactive Code Practice

Choose your learning style10 modes available
Practice - 5 Tasks
Answer the questions below
1fill in blank
easy

Complete the code to create a plot with two y-axes 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()
ax2 = ax1.[1]()
ax1.plot(x, y1, 'g-')
ax2.plot(x, y2, 'b-')
plt.show()
Drag options to blanks, or click blank then click option'
Asubplots
Btwiny
Csubplot
Dtwinx
Attempts:
3 left
💡 Hint
Common Mistakes
Using twiny() creates a twin x-axis, not y-axis.
Using subplot() or subplots() creates new plots, not twin axes.
2fill in blank
medium

Complete the code to set the y-axis label for the second y-axis.

Matplotlib
ax2.[1]('Second Y Axis')
Drag options to blanks, or click blank then click option'
Aset_ylabel
Bset_xlabel
Clabel
Dset_title
Attempts:
3 left
💡 Hint
Common Mistakes
Using set_xlabel() sets the x-axis label instead.
Using label or set_title() does not set axis labels.
3fill in blank
hard

Fix the error in the code to correctly set the color of the second y-axis tick labels.

Matplotlib
ax2.tick_params(axis='y', [1]='b')
Drag options to blanks, or click blank then click option'
Alabelcolour
Bcolor
Clabelcolor
Dtickcolor
Attempts:
3 left
💡 Hint
Common Mistakes
Using 'color' or 'tickcolor' causes no effect or errors.
Misspelling 'labelcolor' as 'labelcolour'.
4fill in blank
hard

Fill both blanks to create a dictionary comprehension that maps words to their lengths only if length is greater than 3.

Matplotlib
words = ['data', 'science', 'is', 'fun']
lengths = {word: [1] for word in words if [2]
Drag options to blanks, or click blank then click option'
Alen(word)
Bword
Clen(word) > 3
Dword > 3
Attempts:
3 left
💡 Hint
Common Mistakes
Using 'word > 3' compares strings to numbers, causing errors.
Using 'word' instead of 'len(word)' for values.
5fill in blank
hard

Fill all three blanks to create a dictionary comprehension that maps uppercase words to their lengths if length is greater than 3.

Matplotlib
words = ['data', 'science', 'is', 'fun']
result = [1]: [2] for [3] in words if len([3]) > 3}}
Drag options to blanks, or click blank then click option'
Aword.upper()
Blen(word)
Cword
Dlen
Attempts:
3 left
💡 Hint
Common Mistakes
Using 'len' as loop variable causes errors.
Not using upper() for keys.
Mismatching variable names in comprehension.

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