0
0
Matplotlibdata~20 mins

Fig, ax = plt.subplots pattern in Matplotlib - Practice Problems & Coding Challenges

Choose your learning style9 modes available
Challenge - 5 Problems
🎖️
Subplots Mastery
Get all challenges correct to earn this badge!
Test your skills under time pressure!
Predict Output
intermediate
1:30remaining
What does this code output?
Consider the following code using plt.subplots(). What will be the type of ax?
Matplotlib
import matplotlib.pyplot as plt
fig, ax = plt.subplots()
print(type(ax))
A<class 'tuple'>
B<class 'matplotlib.axes._subplots.AxesSubplot'>
C<class 'list'>
D<class 'matplotlib.figure.Figure'>
Attempts:
2 left
💡 Hint
Remember that plt.subplots() returns a figure and axes object.
data_output
intermediate
1:30remaining
How many axes are created?
What is the shape and type of ax after running this code?
Matplotlib
import matplotlib.pyplot as plt
fig, ax = plt.subplots(2, 3)
print(type(ax))
print(ax.shape)
Anumpy.ndarray with shape (2, 3)
Blist with length 6
Ctuple with 2 elements
Dmatplotlib.axes._subplots.AxesSubplot with no shape
Attempts:
2 left
💡 Hint
When multiple subplots are created, ax is an array of axes.
visualization
advanced
2:00remaining
Identify the correct subplot layout
Which option shows the correct subplot layout for fig, ax = plt.subplots(1, 4)?
Matplotlib
import matplotlib.pyplot as plt
fig, ax = plt.subplots(1, 4)
for i, axis in enumerate(ax):
    axis.plot([0, 1], [i, i+1])
plt.show()
AFour plots arranged vertically in one column
BTwo rows and two columns of plots
CFour plots arranged horizontally in one row
DSingle plot only
Attempts:
2 left
💡 Hint
The arguments (1, 4) mean 1 row and 4 columns.
🔧 Debug
advanced
1:30remaining
Why does this code raise an error?
What error does this code raise and why?
import matplotlib.pyplot as plt
fig, ax = plt.subplots()
ax[0].plot([1, 2, 3])
Matplotlib
import matplotlib.pyplot as plt
fig, ax = plt.subplots()
ax[0].plot([1, 2, 3])
ATypeError: 'AxesSubplot' object is not subscriptable
BIndexError: list index out of range
CAttributeError: 'Figure' object has no attribute 'plot'
DNo error, plots successfully
Attempts:
2 left
💡 Hint
Check the type of ax when only one subplot is created.
🚀 Application
expert
2:00remaining
How to flatten axes array for iteration?
Given fig, ax = plt.subplots(3, 2), which option correctly iterates over all axes to plot a line on each?
Matplotlib
import matplotlib.pyplot as plt
fig, ax = plt.subplots(3, 2)
# Fill in the blank to plot on each axis
for axis in _____:
    axis.plot([0, 1], [1, 2])
plt.show()
Alist(ax)
Bax.tolist()
Cax
Dax.flatten()
Attempts:
2 left
💡 Hint
The axes array is 2D; flatten it to 1D for simple iteration.