Bird
Raised Fist0
Pandasdata~20 mins

Subplots for multiple charts in Pandas - Practice Problems & Coding Challenges

Choose your learning style10 modes available
Challenge - 5 Problems
🎖️
Subplot Mastery Badge
Get all challenges correct to earn this badge!
Test your skills under time pressure!
❓ Predict Output
intermediate
2:00remaining
Output of subplot creation with pandas
What will be the output of this code snippet that creates subplots for two line charts using pandas and matplotlib?
Pandas
import pandas as pd
import matplotlib.pyplot as plt

data = {'A': [1, 3, 2, 4], 'B': [4, 2, 3, 1]}
df = pd.DataFrame(data)

axes = df.plot(subplots=True, layout=(2, 1), figsize=(6, 6))
plt.tight_layout()
plt.show()

print(type(axes))
A<class 'tuple'>
B<class 'list'>
C<class 'numpy.ndarray'>
D<class 'matplotlib.axes._subplots.AxesSubplot'>
Attempts:
2 left
💡 Hint
Think about what pandas returns when plotting multiple subplots.
❓ data_output
intermediate
2:00remaining
Number of subplot axes created
Given this DataFrame and plotting code, how many subplot axes will be created?
Pandas
import pandas as pd
import matplotlib.pyplot as plt

data = {'X': [5, 6, 7], 'Y': [1, 2, 3], 'Z': [9, 8, 7]}
df = pd.DataFrame(data)

axes = df.plot(subplots=True, layout=(1, 3), figsize=(9, 3))
plt.close()  # Close plot to avoid display

print(len(axes.flatten()))
A3
B1
C9
D0
Attempts:
2 left
💡 Hint
Count the number of columns in the DataFrame.
🔧 Debug
advanced
2:00remaining
Identify the error in subplot layout code
What error will this code raise when trying to create subplots with pandas?
Pandas
import pandas as pd
import matplotlib.pyplot as plt

data = {'A': [1, 2], 'B': [3, 4], 'C': [5, 6]}
df = pd.DataFrame(data)

axes = df.plot(subplots=True, layout=(1, 2), figsize=(8, 4))
plt.show()
AIndexError: list index out of range
BTypeError: 'layout' argument must be a tuple of length 3
CNo error, plots display correctly
DValueError: Layout shape (1, 2) is too small for 3 subplots
Attempts:
2 left
💡 Hint
Check if the layout can fit all subplots.
❓ visualization
advanced
2:00remaining
Effect of figsize on subplot appearance
What visual difference will you see when changing figsize from (6, 4) to (12, 8) in this subplot code?
Pandas
import pandas as pd
import matplotlib.pyplot as plt

data = {'A': [1, 4, 2, 3], 'B': [4, 1, 3, 2]}
df = pd.DataFrame(data)

axes = df.plot(subplots=True, figsize=(6, 4))
plt.show()
ANo change in subplot size or spacing
BSubplots become larger and more spaced out with figsize (12, 8)
CSubplots become smaller and closer together with figsize (12, 8)
DSubplots overlap and become unreadable
Attempts:
2 left
💡 Hint
Figsize controls the overall figure size in inches.
🚀 Application
expert
3:00remaining
Creating a 2x2 grid of subplots with different chart types
Which code correctly creates a 2x2 grid of subplots from this DataFrame, plotting a line, bar, histogram, and scatter plot respectively?
Pandas
import pandas as pd
import matplotlib.pyplot as plt
import numpy as np

data = {'A': np.random.randint(1, 10, 10),
        'B': np.random.randint(10, 20, 10),
        'C': np.random.randn(10),
        'D': np.random.randn(10)}
df = pd.DataFrame(data)
A
fig, axes = plt.subplots(2, 2, figsize=(10, 8))
df['A'].plot(ax=axes[0,0], kind='line')
df['B'].plot(ax=axes[0,1], kind='bar')
df['C'].plot(ax=axes[1,0], kind='hist')
df.plot.scatter(x='C', y='D', ax=axes[1,1])
plt.tight_layout()
plt.show()
B
fig, axes = plt.subplots(2, 2)
df['A'].plot(kind='line', ax=axes[0,0])
df['B'].plot(kind='bar', ax=axes[0,1])
df['C'].plot(kind='hist', ax=axes[1,0])
df['D'].plot(kind='scatter', ax=axes[1,1])
plt.show()
C
fig, axes = plt.subplots(4, 1)
df['A'].plot(kind='line')
df['B'].plot(kind='bar')
df['C'].plot(kind='hist')
df.plot.scatter(x='C', y='D')
plt.show()
D
fig, axes = plt.subplots(2, 2)
df.plot(kind='line', ax=axes[0])
df.plot(kind='bar', ax=axes[1])
df.plot(kind='hist', ax=axes[2])
df.plot.scatter(x='C', y='D', ax=axes[3])
plt.show()
Attempts:
2 left
💡 Hint
Remember scatter plots require x and y arguments and axes indexing for 2D arrays.

Practice

(1/5)
1. What is the main purpose of using subplots in pandas plotting?
easy
A. To display multiple charts in one figure for easy comparison
B. To save plots as separate image files automatically
C. To change the color of a single plot
D. To increase the size of a single chart

Solution

  1. Step 1: Understand what subplots do

    Subplots allow multiple charts to be shown together in one figure.
  2. Step 2: Compare options

    Only To display multiple charts in one figure for easy comparison describes this purpose correctly.
  3. Final Answer:

    To display multiple charts in one figure for easy comparison -> Option A
  4. Quick Check:

    Subplots = multiple charts in one figure [OK]
Hint: Subplots = multiple charts in one figure [OK]
Common Mistakes:
  • Thinking subplots save images automatically
  • Confusing subplots with styling options
  • Believing subplots only affect one chart
2. Which of the following is the correct way to create a 2x2 grid of subplots using matplotlib with pandas?
easy
A. fig, axes = plt.subplots(rows=2)
B. fig, axes = plt.subplots(4)
C. fig, axes = plt.subplots(columns=2)
D. fig, axes = plt.subplots(2, 2)

Solution

  1. Step 1: Recall plt.subplots syntax

    The function plt.subplots(rows, columns) creates a grid of plots.
  2. Step 2: Match the 2x2 grid

    Using plt.subplots(2, 2) creates 2 rows and 2 columns, making 4 subplots.
  3. Final Answer:

    fig, axes = plt.subplots(2, 2) -> Option D
  4. Quick Check:

    plt.subplots(2, 2) = 2 rows, 2 columns [OK]
Hint: Use plt.subplots(rows, columns) for grid size [OK]
Common Mistakes:
  • Using plt.subplots(4) creates 4 rows, not a 2x2 grid
  • Using keyword arguments incorrectly
  • Confusing rows and columns parameters
3. Given the code below, what will axes be?
import matplotlib.pyplot as plt
fig, axes = plt.subplots(1, 3)
print(type(axes))
medium
A. <class 'numpy.ndarray'>
B. <class 'matplotlib.axes._subplots.AxesSubplot'>
C. <class 'list'>
D. <class 'tuple'>

Solution

  1. Step 1: Understand plt.subplots output for multiple plots

    When creating multiple subplots in one row, axes is a numpy array of AxesSubplot objects.
  2. Step 2: Check the printed type

    Printing type(axes) shows numpy.ndarray because axes is an array of subplot axes.
  3. Final Answer:

    <class 'numpy.ndarray'> -> Option A
  4. Quick Check:

    Multiple subplots = axes is numpy array [OK]
Hint: Multiple subplots return numpy array of axes [OK]
Common Mistakes:
  • Thinking axes is a single AxesSubplot object
  • Assuming axes is a list or tuple
  • Confusing axes with figure object
4. What is wrong with this code snippet for creating subplots?
fig, axes = plt.subplots(1)
axes[0].plot([1, 2, 3])
axes[1].plot([4, 5, 6])
medium
A. plt.subplots needs two arguments for multiple plots
B. axes is a single AxesSubplot, so indexing causes an error
C. axes is not iterable when only one argument is given
D. plot data lists must be the same length

Solution

  1. Step 1: Understand plt.subplots(1) output

    plt.subplots(1) creates a single subplot (1 row, 1 column), so axes is a single AxesSubplot object, not an array.
  2. Step 2: Indexing causes error

    Trying axes[0] or axes[1] on a single AxesSubplot raises TypeError: 'AxesSubplot' object is not subscriptable.
  3. Final Answer:

    axes is a single AxesSubplot, so indexing causes an error -> Option B
  4. Quick Check:

    plt.subplots(1) = single axes, indexing fails [OK]
Hint: Check if axes is array before indexing [OK]
Common Mistakes:
  • Assuming axes is always a single plot
  • Forgetting axes can be array for multiple subplots
  • Confusing number of arguments with subplot shape
5. You want to plot three different pandas DataFrame columns side-by-side using subplots in one row. Which code correctly creates the subplots and plots each column separately?
hard
A. fig, axes = plt.subplots(3, 1) for i, col in enumerate(df.columns[:3]): df[col].plot(ax=axes[i])
B. fig, axes = plt.subplots(3) for i, col in enumerate(df.columns[:3]): df[col].plot(ax=axes[i])
C. fig, axes = plt.subplots(1, 3) for i, col in enumerate(df.columns[:3]): df[col].plot(ax=axes[i])
D. fig, axes = plt.subplots(1, 3) for i, col in enumerate(df.columns[:3]): df[col].plot(ax=fig[i])

Solution

  1. Step 1: Determine subplot layout for side-by-side plots

    Side-by-side means 1 row and 3 columns, so plt.subplots(1, 3) is correct.
  2. Step 2: Check plotting loop and axes usage

    Looping over columns and plotting on axes[i] is correct usage.
  3. Step 3: Identify errors in other options

    fig, axes = plt.subplots(3, 1) for i, col in enumerate(df.columns[:3]): df[col].plot(ax=axes[i]) uses (3,1) which is vertical layout, not side-by-side. fig, axes = plt.subplots(1, 3) for i, col in enumerate(df.columns[:3]): df[col].plot(ax=fig[i]) uses fig[i] which is invalid. fig, axes = plt.subplots(3) for i, col in enumerate(df.columns[:3]): df[col].plot(ax=axes[i]) uses plt.subplots(3) which creates 3 rows and 1 column, not side-by-side.
  4. Final Answer:

    fig, axes = plt.subplots(1, 3) for i, col in enumerate(df.columns[:3]): df[col].plot(ax=axes[i]) -> Option C
  5. Quick Check:

    Side-by-side = plt.subplots(1, 3) + axes[i] [OK]
Hint: Side-by-side = 1 row, multiple columns in plt.subplots [OK]
Common Mistakes:
  • Using wrong subplot shape for layout
  • Passing fig instead of axes to plot
  • Confusing rows and columns in plt.subplots
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