Bird
Raised Fist0
Matplotlibdata~10 mins

Axes creation with add_subplot in Matplotlib - Step-by-Step Execution

Choose your learning style10 modes available
Concept Flow - Axes creation with add_subplot
Create Figure Object
↓
Call add_subplot(rows, cols, index)
↓
Create Axes Object
↓
Add Axes to Figure
↓
Return Axes Object for plotting
This flow shows how calling add_subplot on a figure creates and adds an axes object to the figure, which you can then use to plot.
Execution Sample
Matplotlib
import matplotlib.pyplot as plt
fig = plt.figure()
ax = fig.add_subplot(2, 2, 1)
ax.plot([1, 2, 3], [4, 5, 6])
plt.show()
This code creates a figure, adds a 2x2 grid subplot at position 1, plots a line, and shows the plot.
Execution Table
StepActionInput ParametersResultNotes
1Create FigureNoneFigure object createdEmpty canvas for plots
2Call add_subplotrows=2, cols=2, index=1Axes object created and addedAxes placed at top-left in 2x2 grid
3Plot datax=[1,2,3], y=[4,5,6]Line plotted on AxesData points connected by line
4Show plotNonePlot window displayedUser sees the figure with subplot and line
💡 All steps complete, plot displayed with one subplot.
Variable Tracker
VariableStartAfter Step 1After Step 2After Step 3Final
figNoneFigure objectFigure objectFigure objectFigure object
axNoneNoneAxes objectAxes object with line plotAxes object with line plot
Key Moments - 3 Insights
Why do we need to call add_subplot on the figure object?
Because add_subplot creates an Axes object inside the figure where we can draw plots. The execution_table row 2 shows add_subplot returns this Axes.
What do the numbers (2, 2, 1) mean in add_subplot(2, 2, 1)?
They define a grid of 2 rows and 2 columns, and select the first subplot position. See execution_table row 2 for this placement.
Can we plot before creating an Axes?
No, plotting requires an Axes object to draw on. The variable_tracker shows ax is None before add_subplot, so no plot can happen.
Visual Quiz - 3 Questions
Test your understanding
Look at the execution_table, what is the result after step 2?
AAxes object created and added
BFigure object created
CLine plotted on Axes
DPlot window displayed
💡 Hint
Refer to execution_table row 2 under Result column.
At which step does the variable 'ax' get assigned an Axes object?
AAfter Step 1
BAfter Step 2
CAfter Step 3
DFinal
💡 Hint
Check variable_tracker row for 'ax' and see when it changes from None.
If we change add_subplot(2, 2, 1) to add_subplot(1, 1, 1), what changes in the execution?
APlot will not show
BNo Axes will be created
CAxes will be created in a 1x1 grid instead of 2x2
DFigure object will not be created
💡 Hint
Look at the meaning of parameters in key_moments question 2.
Concept Snapshot
Use fig.add_subplot(rows, cols, index) to create an Axes in a grid layout.
Rows and cols define grid size; index selects position.
Returns an Axes object to plot on.
Multiple subplots can be added to one figure.
Plot on Axes, then show figure with plt.show().
Full Transcript
This visual execution traces how matplotlib's add_subplot method creates axes inside a figure. First, a figure object is created as a blank canvas. Then add_subplot is called with parameters for grid size and position, which creates an axes object placed accordingly. This axes is where plotting commands draw lines or points. Finally, plt.show() displays the figure window with the subplot and plotted data. Variables 'fig' and 'ax' track the figure and axes objects respectively. Key moments clarify why add_subplot is needed and what its parameters mean. The quiz tests understanding of these steps and variable states.

Practice

(1/5)
1. What does the add_subplot method do in matplotlib?
easy
A. It removes a plot from the figure.
B. It saves the figure to a file.
C. It changes the color of the plot.
D. It adds a new plot (axes) to an existing figure.

Solution

  1. Step 1: Understand the purpose of add_subplot

    The add_subplot method is used to add one or more plots (axes) inside a figure in matplotlib.
  2. Step 2: Compare with other options

    Saving, coloring, or removing plots are done by other methods, not add_subplot.
  3. Final Answer:

    It adds a new plot (axes) to an existing figure. -> Option D
  4. Quick Check:

    add_subplot adds axes [OK]
Hint: Remember: add_subplot adds plots inside a figure [OK]
Common Mistakes:
  • Confusing add_subplot with savefig
  • Thinking it changes plot colors
  • Assuming it deletes plots
2. Which of the following is the correct way to create a 2x2 grid of subplots and select the third subplot using add_subplot?
easy
A. fig.add_subplot(2, 2, 3)
B. fig.add_subplot(3, 2, 2)
C. fig.add_subplot(2, 3, 1)
D. fig.add_subplot(2, 2)

Solution

  1. Step 1: Understand the parameters of add_subplot

    The method add_subplot(rows, columns, index) creates a grid and selects the subplot at the given index.
  2. Step 2: Match the correct grid and index

    For a 2x2 grid, the third subplot is at position 3, so fig.add_subplot(2, 2, 3) is correct.
  3. Final Answer:

    fig.add_subplot(2, 2, 3) -> Option A
  4. Quick Check:

    2x2 grid, third subplot = add_subplot(2,2,3) [OK]
Hint: Use (rows, cols, position) to pick subplot [OK]
Common Mistakes:
  • Mixing rows and columns order
  • Omitting the position argument
  • Using wrong grid size
3. What will be the output of the following code snippet?
import matplotlib.pyplot as plt
fig = plt.figure()
ax1 = fig.add_subplot(121)
ax2 = fig.add_subplot(122)
print(type(ax1), type(ax2))
medium
A.
B.
C.
D. SyntaxError

Solution

  1. Step 1: Understand add_subplot with 3-digit code

    The code 121 means 1 row, 2 columns, subplot 1; 122 means subplot 2.
  2. Step 2: Check the returned object types

    Both ax1 and ax2 are subplot axes objects of type AxesSubplot.
  3. Final Answer:

    <class 'matplotlib.axes._subplots.AxesSubplot'> <class 'matplotlib.axes._subplots.AxesSubplot'> -> Option A
  4. Quick Check:

    add_subplot returns AxesSubplot objects [OK]
Hint: 3-digit code means (rows, cols, index) [OK]
Common Mistakes:
  • Expecting Figure type instead of Axes
  • Confusing syntax with tuple input
  • Thinking it causes syntax error
4. Identify the error in this code snippet:
import matplotlib.pyplot as plt
fig = plt.figure()
ax = fig.add_subplot(2, 2)
ax.plot([1, 2, 3], [4, 5, 6])
plt.show()
medium
A. plt.figure() should be plt.subplots() instead.
B. Missing the subplot position argument in add_subplot.
C. The plot data lists have different lengths.
D. plt.show() is called before plotting.

Solution

  1. Step 1: Check add_subplot parameters

    The method requires three arguments: rows, columns, and position. Here, only two are given.
  2. Step 2: Verify other parts of the code

    Plot data lists have equal length, plt.show() is correctly placed, and plt.figure() is valid.
  3. Final Answer:

    Missing the subplot position argument in add_subplot. -> Option B
  4. Quick Check:

    add_subplot needs 3 args (rows, cols, pos) [OK]
Hint: add_subplot needs three numbers: rows, cols, position [OK]
Common Mistakes:
  • Forgetting the position argument
  • Confusing plt.figure() with plt.subplots()
  • Assuming plt.show() order matters here
5. You want to create a figure with 3 subplots arranged in 1 row and 3 columns. You want to add the second subplot and plot a line on it. Which code snippet correctly does this?
hard
A. fig = plt.figure() ax = fig.add_subplot(3, 1, 2) ax.plot([0, 1, 2], [2, 1, 0]) plt.show()
B. fig, ax = plt.subplots(3, 1) ax[1].plot([0, 1, 2], [2, 1, 0]) plt.show()
C. fig = plt.figure() ax = fig.add_subplot(1, 3, 2) ax.plot([0, 1, 2], [2, 1, 0]) plt.show()
D. fig = plt.figure() ax = fig.add_subplot(1, 2, 3) ax.plot([0, 1, 2], [2, 1, 0]) plt.show()

Solution

  1. Step 1: Understand subplot layout

    We want 1 row and 3 columns, so the call is add_subplot(1, 3, position).
  2. Step 2: Select the second subplot and plot

    Position 2 selects the second subplot. The plot command is correct.
  3. Step 3: Check other options

    fig, ax = plt.subplots(3, 1) ax[1].plot([0, 1, 2], [2, 1, 0]) plt.show() uses plt.subplots with wrong shape, C uses wrong layout, D uses invalid position 3 in 1x2 grid.
  4. Final Answer:

    fig = plt.figure() ax = fig.add_subplot(1, 3, 2) ax.plot([0, 1, 2], [2, 1, 0]) plt.show() -> Option C
  5. Quick Check:

    1 row, 3 cols, second subplot = add_subplot(1,3,2) [OK]
Hint: Match rows, cols, and position carefully [OK]
Common Mistakes:
  • Mixing rows and columns numbers
  • Using wrong subplot index
  • Confusing plt.figure() and 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