Challenge - 5 Problems
Matplotlib OO Mastery
Get all challenges correct to earn this badge!
Test your skills under time pressure!
❓ Predict Output
intermediate2:00remaining
Output of plot commands using OO interface
What will be the output of this code snippet using matplotlib's OO interface?
Matplotlib
import matplotlib.pyplot as plt fig, ax = plt.subplots() ax.plot([1, 2, 3], [4, 5, 6]) ax.set_title('Test Plot') plt.show()
Attempts:
2 left
💡 Hint
Remember that ax.plot creates a line plot and ax.set_title sets the title for that axes.
✗ Incorrect
Using the OO interface, ax.plot draws a line plot on the axes, and ax.set_title sets the title. So the plot shows a line connecting points (1,4), (2,5), (3,6) with the given title.
🧠 Conceptual
intermediate1:30remaining
Why prefer OO interface over pyplot state-machine?
Which reason best explains why the OO interface is preferred over the pyplot state-machine interface in matplotlib?
Attempts:
2 left
💡 Hint
Think about managing multiple plots at once.
✗ Incorrect
The OO interface lets you create and control multiple figures and axes explicitly, which is important for complex plots. The pyplot interface relies on a global state which can cause confusion.
🔧 Debug
advanced2:00remaining
Identify the error in this OO interface code
What error will this code raise when run?
Matplotlib
import matplotlib.pyplot as plt fig, ax = plt.subplots() ax.plot([1, 2, 3], [4, 5]) ax.set_title('Mismatch Data') plt.show()
Attempts:
2 left
💡 Hint
Check the lengths of x and y data passed to plot.
✗ Incorrect
The x data has length 3 but y data has length 2, so matplotlib raises a ValueError because the dimensions do not match.
❓ data_output
advanced1:30remaining
Number of axes created with subplots
What is the shape and number of axes objects created by this code?
Matplotlib
import matplotlib.pyplot as plt fig, axes = plt.subplots(2, 3) print(type(axes), axes.shape)
Attempts:
2 left
💡 Hint
plt.subplots returns a numpy array of axes when rows and columns are more than 1.
✗ Incorrect
When creating multiple subplots with plt.subplots(2,3), axes is a 2x3 numpy array of AxesSubplot objects.
🚀 Application
expert2:30remaining
Correctly update title for specific subplot
Given a 2x2 grid of subplots, which code correctly sets the title of the bottom-right subplot only?
Matplotlib
import matplotlib.pyplot as plt fig, axes = plt.subplots(2, 2) # Set title for bottom-right subplot here
Attempts:
2 left
💡 Hint
Remember Python uses zero-based indexing for arrays.
✗ Incorrect
axes is a 2x2 numpy array indexed by [row, column]. The bottom-right subplot is at row 1, column 1 (zero-based).