Bird
Raised Fist0
Matplotlibdata~20 mins

Secondary axes in Matplotlib - Practice Problems & Coding Challenges

Choose your learning style10 modes available
Challenge - 5 Problems
🎖️
Secondary Axes Master
Get all challenges correct to earn this badge!
Test your skills under time pressure!
❓ Predict Output
intermediate
2:00remaining
Output of plot with secondary y-axis
What will be the output of this code snippet that uses a secondary y-axis in matplotlib?
Matplotlib
import matplotlib.pyplot as plt
x = [1, 2, 3, 4]
y1 = [10, 20, 25, 30]
y2 = [100, 200, 250, 300]
fig, ax1 = plt.subplots()
ax1.plot(x, y1, 'g-')
ax2 = ax1.twinx()
ax2.plot(x, y2, 'b--')
plt.show()
AA plot with one x-axis, left y-axis in green line for y1, and right y-axis in blue dashed line for y2
BA plot with two x-axes and one y-axis showing both y1 and y2 overlapped
CA plot with one x-axis and one y-axis showing only y1 in green line
DA plot with one x-axis and one y-axis showing only y2 in blue dashed line
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 secondary y-axis
Given this code, how many major ticks will the secondary y-axis have by default?
Matplotlib
import matplotlib.pyplot as plt
x = [0, 1, 2, 3]
y1 = [1, 4, 9, 16]
y2 = [10, 40, 90, 160]
fig, ax1 = plt.subplots()
ax1.plot(x, y1)
ax2 = ax1.twinx()
ax2.plot(x, y2)
print(len(ax2.get_yticks()))
A5
B10
C7
D4
Attempts:
2 left
💡 Hint
Check the default number of yticks matplotlib creates for a linear scale.
❓ visualization
advanced
2:30remaining
Identify the correct secondary x-axis transformation
Which option correctly creates a secondary x-axis that shows the square root of the primary x-axis values?
Matplotlib
import matplotlib.pyplot as plt
import numpy as np
x = np.linspace(0, 16, 100)
y = np.sqrt(x)
fig, ax = plt.subplots()
ax.plot(x, y)
secax = ax.secondary_xaxis(1.0, functions=(np.sqrt, np.square))
secax.set_xlabel('Square root of x')
plt.show()
Asecax = ax.secondary_xaxis(1.0, functions=(np.sqrt, np.square))
Bsecax = ax.secondary_xaxis(1.0, functions=(np.square, np.sqrt))
Csecax = ax.secondary_xaxis(0.0, functions=(np.sqrt, np.square))
Dsecax = ax.secondary_xaxis(1.0, functions=(np.log, np.exp))
Attempts:
2 left
💡 Hint
The first function converts primary to secondary axis, the second converts back.
🔧 Debug
advanced
2:00remaining
Error when adding secondary y-axis with incompatible scales
What error will this code raise when trying to plot on a secondary y-axis with incompatible data types?
Matplotlib
import matplotlib.pyplot as plt
x = [1, 2, 3]
y1 = [10, 20, 30]
y2 = ['a', 'b', 'c']
fig, ax1 = plt.subplots()
ax1.plot(x, y1)
ax2 = ax1.twinx()
ax2.plot(x, y2)
plt.show()
AValueError: x and y must have same first dimension
BNo error, plot displays with categorical y2
CSyntaxError: invalid syntax
DTypeError: float() argument must be a string or a number, not 'str'
Attempts:
2 left
💡 Hint
Check if matplotlib can plot strings as y-values.
🚀 Application
expert
3:00remaining
Using secondary y-axis to compare different units
You have temperature data in Celsius and Fahrenheit for the same dates. Which code snippet correctly plots Celsius on the left y-axis and Fahrenheit on the right y-axis using secondary y-axis?
Matplotlib
import matplotlib.pyplot as plt
dates = ['Mon', 'Tue', 'Wed', 'Thu', 'Fri']
celsius = [0, 10, 20, 15, 5]
fahrenheit = [32, 50, 68, 59, 41]
fig, ax1 = plt.subplots()
ax1.plot(dates, celsius, 'r-', label='Celsius')
ax2 = ax1.twinx()
ax2.plot(dates, fahrenheit, 'b--', label='Fahrenheit')
ax1.set_ylabel('Celsius')
ax2.set_ylabel('Fahrenheit')
plt.show()
AThe code runs but both lines overlap on the same y-axis scale
BThe code runs correctly and shows Celsius on left y-axis and Fahrenheit on right y-axis
CThe code raises TypeError because twinx() cannot be used with string x-axis
DThe code raises ValueError because dates are strings and cannot be plotted
Attempts:
2 left
💡 Hint
Matplotlib can plot categorical x-axis labels as strings.

Practice

(1/5)
1. What is the main purpose of using secondary_xaxis or secondary_yaxis in matplotlib?
easy
A. To add a new axis with a different scale on the same plot
B. To create a separate figure window
C. To change the color of the existing axis
D. To remove the original axis from the plot

Solution

  1. Step 1: Understand the concept of secondary axes

    Secondary axes allow adding a new axis that shares the same plot but has a different scale or units.
  2. Step 2: Identify the purpose of secondary_xaxis or secondary_yaxis

    These functions add a secondary axis to the existing plot to compare data with different units clearly.
  3. Final Answer:

    To add a new axis with a different scale on the same plot -> Option A
  4. Quick Check:

    Secondary axes = different scale on same plot [OK]
Hint: Secondary axes add a new scale on the same plot [OK]
Common Mistakes:
  • Thinking it creates a new figure
  • Confusing axis color change with adding axes
  • Assuming it removes original axes
2. Which of the following is the correct way to add a secondary y-axis in matplotlib?
easy
A. ax.add_secondary_yaxis('right', functions=(forward, inverse))
B. ax.add_secondary_axis('right', functions=(forward, inverse))
C. ax.secondary_yaxis('right', functions=(forward, inverse))
D. ax.secondary_axis('right', functions=(forward, inverse))

Solution

  1. Step 1: Recall the matplotlib method for secondary y-axis

    The correct method is secondary_yaxis called on the axes object.
  2. Step 2: Match the exact syntax

    The method is ax.secondary_yaxis('right', functions=(forward, inverse)) where 'right' is the position and functions are conversion functions.
  3. Final Answer:

    ax.secondary_yaxis('right', functions=(forward, inverse)) -> Option C
  4. Quick Check:

    Correct method name = secondary_yaxis [OK]
Hint: Use ax.secondary_yaxis with conversion functions [OK]
Common Mistakes:
  • Using incorrect method names like add_secondary_axis
  • Missing the functions parameter
  • Using secondary_axis instead of secondary_yaxis
3. What will be the output of this code snippet?
import matplotlib.pyplot as plt
fig, ax = plt.subplots()
ax.plot([0, 1, 2], [0, 10, 20])

forward = lambda x: x / 10
inverse = lambda x: x * 10
secax = ax.secondary_yaxis('right', functions=(forward, inverse))
print(secax.get_ylim())
medium
A. [0.0, 2.0]
B. [0, 20]
C. [0.0, 200.0]
D. [0, 10]

Solution

  1. Step 1: Understand the original y-axis limits

    The original y-axis data ranges from 0 to 20, so default limits are approximately (0, 20).
  2. Step 2: Apply the forward function to original limits for secondary axis

    The forward function divides by 10, so 0 becomes 0.0 and 20 becomes 2.0 on the secondary axis.
  3. Final Answer:

    [0.0, 2.0] -> Option A
  4. Quick Check:

    Secondary axis limits = original limits / 10 [OK]
Hint: Secondary axis limits = apply forward function to original limits [OK]
Common Mistakes:
  • Confusing forward and inverse functions
  • Expecting original limits instead of transformed
  • Assuming inverse function applies to limits
4. Identify the error in this code that tries to add a secondary x-axis:
import matplotlib.pyplot as plt
fig, ax = plt.subplots()
ax.plot([0, 1, 2], [0, 1, 4])

forward = lambda x: x * 2
inverse = lambda x: x / 2
secax = ax.secondary_xaxis('top', functions=(inverse, forward))
medium
A. The lambda functions should not be used
B. The order of functions in the tuple is reversed
C. The position 'top' is invalid for secondary_xaxis
D. The method name should be secondary_yaxis instead

Solution

  1. Step 1: Check the order of conversion functions

    The first function should convert from primary to secondary axis (forward), the second from secondary to primary (inverse).
  2. Step 2: Identify the mistake in the code

    The code uses (inverse, forward) instead of (forward, inverse), so the order is reversed causing incorrect scaling.
  3. Final Answer:

    The order of functions in the tuple is reversed -> Option B
  4. Quick Check:

    Functions order = (forward, inverse) [OK]
Hint: First function forward, second inverse in tuple [OK]
Common Mistakes:
  • Swapping forward and inverse functions
  • Using invalid axis position
  • Confusing secondary_xaxis with secondary_yaxis
5. You have temperature data in Celsius and want to add a secondary y-axis in Fahrenheit on the right side. Which of these code snippets correctly creates the secondary axis with proper conversion?
hard
A. forward = lambda f: (f - 32) * 5/9 inverse = lambda c: (c * 9/5) + 32 ax.secondary_yaxis('right', functions=(inverse, forward))
B. forward = lambda c: (c * 5/9) + 32 inverse = lambda f: (f - 32) * 9/5 ax.secondary_yaxis('right', functions=(forward, inverse))
C. forward = lambda c: (c - 32) * 5/9 inverse = lambda f: (f * 9/5) + 32 ax.secondary_yaxis('left', functions=(forward, inverse))
D. forward = lambda c: (c * 9/5) + 32 inverse = lambda f: (f - 32) * 5/9 ax.secondary_yaxis('right', functions=(forward, inverse))

Solution

  1. Step 1: Recall Celsius to Fahrenheit conversion formulas

    Celsius to Fahrenheit: F = (C * 9/5) + 32; Fahrenheit to Celsius: C = (F - 32) * 5/9.
  2. Step 2: Match the forward and inverse functions correctly

    Forward converts primary (C) to secondary (F), inverse converts secondary (F) back to primary (C). Position 'right' is correct for secondary y-axis.
  3. Final Answer:

    forward = lambda c: (c * 9/5) + 32 inverse = lambda f: (f - 32) * 5/9 ax.secondary_yaxis('right', functions=(forward, inverse)) -> Option D
  4. Quick Check:

    Correct conversion and axis position = forward = lambda c: (c * 9/5) + 32 inverse = lambda f: (f - 32) * 5/9 ax.secondary_yaxis('right', functions=(forward, inverse)) [OK]
Hint: Forward: C to F; Inverse: F to C; position 'right' for y-axis [OK]
Common Mistakes:
  • Swapping forward and inverse functions
  • Using wrong conversion formulas
  • Placing secondary axis on 'left' instead of 'right'
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