Bird
Raised Fist0
Matplotlibdata~15 mins

Figure and Axes mental model in Matplotlib - Deep Dive

Choose your learning style10 modes available
Overview - Figure and Axes mental model
What is it?
In matplotlib, a Figure is like a blank canvas or a sheet of paper where you can draw your plots. Axes are the individual plots or graphs drawn on this canvas. Each Axes contains the actual data visualization, including lines, bars, or points, along with labels and ticks. Understanding how Figures and Axes relate helps you organize and customize your plots effectively.
Why it matters
Without knowing the Figure and Axes structure, you might struggle to create multiple plots in one image or customize parts of your graph. This concept solves the problem of managing complex visualizations by separating the overall image (Figure) from the individual plots (Axes). Without it, plotting would be confusing and limited, making it hard to present data clearly.
Where it fits
Before this, you should know basic Python programming and how to install and import matplotlib. After learning this, you can explore advanced plotting techniques, customizing styles, and creating interactive visualizations.
Mental Model
Core Idea
A Figure is the whole picture or canvas, and Axes are the individual plots drawn inside it where data is visualized.
Think of it like...
Think of a Figure as a photo album page and Axes as the individual photos glued onto that page. You can arrange, resize, or decorate each photo separately, but they all belong to the same page.
┌─────────────────────────────┐
│          Figure             │
│  ┌───────────┐  ┌─────────┐ │
│  │   Axes 1  │  │ Axes 2  │ │
│  │ (plot 1)  │  │(plot 2) │ │
│  └───────────┘  └─────────┘ │
│                             │
└─────────────────────────────┘
Build-Up - 6 Steps
1
FoundationUnderstanding the Figure concept
🤔
Concept: Learn what a Figure is in matplotlib and its role as the container for plots.
A Figure in matplotlib is the top-level container that holds everything you see in a plot image. It can contain one or more Axes (plots). You create a Figure using plt.figure() or plt.subplots(). Think of it as the blank page where you will place your graphs.
Result
You get a blank Figure object ready to hold plots.
Understanding that the Figure is the overall container helps you manage multiple plots and control the size and resolution of your final image.
2
FoundationWhat are Axes in matplotlib
🤔
Concept: Discover that Axes are the actual plots inside a Figure where data is drawn.
Axes represent the area where data is plotted, including the x and y axes, labels, ticks, and the graphical elements like lines or bars. You can create Axes inside a Figure using methods like add_subplot() or plt.subplots(). Each Axes is a separate plot.
Result
You create one or more Axes objects inside a Figure.
Knowing that Axes hold the data visualization itself allows you to customize each plot independently within the same Figure.
3
IntermediateCreating multiple Axes in one Figure
🤔Before reading on: Do you think multiple Axes share the same Figure or require separate Figures? Commit to your answer.
Concept: Learn how to add multiple plots (Axes) inside a single Figure to compare data side by side.
Using plt.subplots(nrows, ncols), you can create a grid of Axes inside one Figure. For example, plt.subplots(2, 2) creates four Axes arranged in 2 rows and 2 columns. This helps you display multiple related plots together.
Result
A Figure with multiple Axes arranged in a grid layout.
Understanding that multiple Axes can coexist in one Figure enables you to build complex dashboards and comparative visualizations.
4
IntermediateAccessing and modifying Axes properties
🤔Before reading on: Can you change the title of a Figure or only of an Axes? Commit to your answer.
Concept: Explore how to customize individual Axes, such as setting titles, labels, and limits.
Each Axes object has methods like set_title(), set_xlabel(), and set_xlim() to customize the plot. For example, ax.set_title('My Plot') sets the title of that specific Axes. The Figure itself can have a suptitle for the whole image using fig.suptitle().
Result
Customized Axes with titles, labels, and axis limits.
Knowing how to modify Axes properties lets you tailor each plot's appearance without affecting others in the same Figure.
5
AdvancedFigure and Axes interaction in complex layouts
🤔Before reading on: Do you think Axes can overlap or must always be neatly arranged? Commit to your answer.
Concept: Understand how to control Axes placement and size within a Figure for advanced layouts.
You can manually position Axes inside a Figure using add_axes([left, bottom, width, height]) with coordinates from 0 to 1. This allows overlapping or custom-sized plots. This is useful for inset plots or complex dashboard designs.
Result
A Figure with precisely positioned Axes, possibly overlapping or irregularly sized.
Mastering Axes placement unlocks creative and professional-quality visualizations beyond simple grids.
6
ExpertInternal reference and rendering order of Axes
🤔Before reading on: Does the order you add Axes affect which plot appears on top? Commit to your answer.
Concept: Learn how matplotlib manages Axes internally, including rendering order and references.
Matplotlib stores Axes in a list inside the Figure. The order of this list determines which Axes are drawn on top. Later added Axes appear above earlier ones. Understanding this helps when layering plots or adding annotations. Also, each Axes has a unique ID and references to the Figure for event handling.
Result
Clear understanding of how Axes stacking and rendering works inside a Figure.
Knowing the internal order prevents confusing visual bugs when plots overlap and helps in designing interactive plots.
Under the Hood
Matplotlib creates a Figure object as a container that holds multiple Axes objects. Each Axes manages its own coordinate system, data elements, and decorations like labels and ticks. When rendering, the Figure calls each Axes to draw itself in order. The Figure manages the overall canvas size and resolution, while Axes handle the detailed drawing of data.
Why designed this way?
This design separates concerns: the Figure handles the overall image and layout, while Axes focus on individual plots. This modularity allows flexible composition of multiple plots and easier customization. Early matplotlib versions had simpler models, but this layered approach supports complex visualizations and interactive features.
┌─────────────────────────────┐
│          Figure             │
│  ┌───────────┐  ┌─────────┐ │
│  │   Axes 1  │  │ Axes 2  │ │
│  │ ┌───────┐ │  │ ┌─────┐ │ │
│  │ │ Data  │ │  │ │Data │ │ │
│  │ └───────┘ │  │ └─────┘ │ │
│  └───────────┘  └─────────┘ │
│                             │
└─────────────────────────────┘
Myth Busters - 3 Common Misconceptions
Quick: Do you think calling plt.plot() automatically creates a new Figure each time? Commit yes or no.
Common Belief:Calling plt.plot() always creates a new Figure and Axes automatically.
Tap to reveal reality
Reality:plt.plot() draws on the current active Axes inside the current Figure. It does not create new Figures or Axes unless none exist.
Why it matters:Assuming new Figures are created each time can lead to unexpected overwriting or plotting on the same graph, causing confusion in multi-plot workflows.
Quick: Can a Figure contain Axes of different sizes and positions by default? Commit yes or no.
Common Belief:All Axes inside a Figure must be the same size and arranged in a grid.
Tap to reveal reality
Reality:Axes can have different sizes and positions inside a Figure. You can manually set their location and size for custom layouts.
Why it matters:Believing Axes must be uniform limits creativity and prevents advanced layout designs like insets or dashboards.
Quick: Does changing the Figure size automatically resize existing Axes? Commit yes or no.
Common Belief:Changing the Figure size automatically adjusts all Axes sizes proportionally.
Tap to reveal reality
Reality:Changing Figure size changes the canvas size, but Axes sizes and positions remain fixed unless explicitly adjusted.
Why it matters:Misunderstanding this can cause plots to look stretched or squished unexpectedly when resizing Figures.
Expert Zone
1
Axes objects can share the same x or y axis to synchronize zooming and panning, which is crucial for comparative analysis.
2
The Figure canvas can be rendered in different backends (e.g., PNG, SVG, interactive windows), affecting how Figures and Axes behave and display.
3
Matplotlib caches some rendering details inside Axes to optimize redraws, so changing properties dynamically requires careful management.
When NOT to use
For very large datasets or highly interactive visualizations, matplotlib's Figure and Axes model can be slow or cumbersome. Alternatives like Plotly or Bokeh offer better interactivity and performance for web-based plots.
Production Patterns
Professionals often create Figures with multiple Axes arranged in grids or custom layouts for dashboards. They use Axes sharing to link plots and customize each Axes independently. Saving Figures in vector formats ensures high-quality prints. Layering Axes with precise positioning is common for inset plots or annotations.
Connections
HTML and CSS Box Model
Both organize content in containers and sub-containers with layout control.
Understanding how Figures contain Axes is like how a webpage contains divs; mastering container relationships helps in both web design and plotting.
Object-Oriented Programming (OOP)
Figure and Axes are objects with properties and methods that manage state and behavior.
Knowing OOP concepts clarifies how Figures and Axes interact, inherit, and encapsulate plotting logic.
Photography Composition
Arranging multiple Axes in a Figure is like composing multiple photos in a collage.
This connection helps appreciate layout design principles in data visualization.
Common Pitfalls
#1Plotting multiple graphs without creating new Axes leads to overlapping plots on the same Axes.
Wrong approach:plt.plot(x1, y1) plt.plot(x2, y2) # Both plots on same Axes unintentionally
Correct approach:fig, ax = plt.subplots() ax.plot(x1, y1) fig2, ax2 = plt.subplots() ax2.plot(x2, y2) # Separate Axes for each plot
Root cause:Not understanding that plt.plot() uses the current Axes by default causes unintended plot overlap.
#2Trying to set a title on the Figure using Axes method causes no effect or error.
Wrong approach:ax.set_title('Overall Title') # Sets title only on one Axes, not Figure
Correct approach:fig.suptitle('Overall Title') # Sets title for the whole Figure
Root cause:Confusing Figure-level and Axes-level methods leads to misplaced titles.
#3Assuming changing Figure size automatically rescales Axes content.
Wrong approach:fig.set_size_inches(10, 8) # Axes remain same size, plot looks distorted
Correct approach:fig.set_size_inches(10, 8) plt.tight_layout() # Adjusts Axes to fit new Figure size
Root cause:Not calling layout adjustment methods after resizing Figure causes layout issues.
Key Takeaways
A Figure is the overall container or canvas for one or more plots called Axes.
Axes are the individual plots where data is drawn, each with its own labels and ticks.
Multiple Axes can be arranged in grids or custom layouts inside a single Figure.
Understanding the Figure and Axes relationship allows precise control over complex visualizations.
Knowing the internal rendering order and customization methods prevents common plotting mistakes.

Practice

(1/5)
1. What does the Figure represent in matplotlib's Figure and Axes model?
easy
A. A single data point on the plot
B. The area where data points are drawn
C. The entire image or window that contains all plots
D. The color scheme of the plot

Solution

  1. Step 1: Understand the role of Figure

    The Figure is the whole container or window that holds one or more plots.
  2. Step 2: Differentiate Figure from Axes

    Axes is the part inside the Figure where data is drawn, not the entire window.
  3. Final Answer:

    The entire image or window that contains all plots -> Option C
  4. Quick Check:

    Figure = whole window [OK]
Hint: Figure is the whole plot window, not just the data area [OK]
Common Mistakes:
  • Confusing Figure with Axes
  • Thinking Figure is a single plot line
  • Mixing Figure with plot colors
2. Which of the following is the correct way to create a Figure and Axes in matplotlib?
easy
A. fig, ax = plt.subplots()
B. fig = plt.figure(), ax = plt.plot()
C. ax = plt.figure(), fig = plt.axes()
D. plt.create_figure(), plt.create_axes()

Solution

  1. Step 1: Recall matplotlib syntax

    The standard way to create Figure and Axes together is using plt.subplots().
  2. Step 2: Check each option

    fig, ax = plt.subplots() correctly assigns Figure and Axes from plt.subplots(). Others misuse functions or assign incorrectly.
  3. Final Answer:

    fig, ax = plt.subplots() -> Option A
  4. Quick Check:

    Use plt.subplots() to get Figure and Axes [OK]
Hint: Use plt.subplots() to get both Figure and Axes [OK]
Common Mistakes:
  • Using plt.plot() to create Axes
  • Confusing plt.figure() with plt.subplots()
  • Trying non-existent functions like plt.create_figure()
3. What will be the output type of the variable ax after running this code?
import matplotlib.pyplot as plt
fig, ax = plt.subplots()
medium
A. A matplotlib Figure object
B. A matplotlib Axes object
C. A list of Axes objects
D. A NumPy array

Solution

  1. Step 1: Understand plt.subplots() return values

    It returns a tuple: (Figure object, Axes object or array of Axes).
  2. Step 2: Check variable assignment

    Here, ax is assigned the second element, which is a single Axes object.
  3. Final Answer:

    A matplotlib Axes object -> Option B
  4. Quick Check:

    ax = Axes object from plt.subplots() [OK]
Hint: plt.subplots() returns (Figure, Axes) tuple [OK]
Common Mistakes:
  • Thinking ax is a Figure
  • Assuming ax is a list without multiple plots
  • Confusing Axes with NumPy arrays
4. Identify the error in this code snippet:
import matplotlib.pyplot as plt
fig = plt.figure()
ax = plt.axes()
ax.plot([1, 2, 3], [4, 5, 6])
plt.show()
medium
A. plt.axes() should be called on the Figure object
B. plt.axes() creates a new Figure, not Axes
C. plt.figure() must be called after plt.axes()
D. No error, code runs fine

Solution

  1. Step 1: Understand plt.figure() and plt.axes()

    plt.figure() creates a Figure and sets it as current. plt.axes() creates Axes in the current Figure using default positioning.
  2. Step 2: Verify code execution

    The plot is correctly added to ax and plt.show() displays the figure. The code runs without errors.
  3. Final Answer:

    No error, code runs fine -> Option D
  4. Quick Check:

    plt.axes() adds to current Figure [OK]
Hint: plt.figure() sets current figure for plt.axes() [OK]
Common Mistakes:
  • Calling plt.axes() without linking to Figure
  • Assuming plt.axes() auto-links to last Figure
  • Calling plt.figure() after plt.axes()
5. You want to create a figure with two side-by-side plots sharing the same y-axis. Which code correctly uses the Figure and Axes model to achieve this?
hard
A. fig, (ax1, ax2) = plt.subplots(1, 2, sharey=True) ax1.plot([1,2,3], [4,5,6]) ax2.plot([1,2,3], [6,5,4])
B. fig = plt.figure() ax1 = fig.add_subplot(1, 2, 1) ax2 = fig.add_subplot(1, 2, 2) ax1.sharey(ax2)
C. fig, ax = plt.subplots(2, 1) ax[0].plot([1,2,3], [4,5,6]) ax[1].plot([1,2,3], [6,5,4])
D. fig, ax = plt.subplots(1, 2) ax[0].plot([1,2,3], [4,5,6]) ax[1].plot([1,2,3], [6,5,4])

Solution

  1. Step 1: Understand subplots with shared axes

    Using plt.subplots(1, 2, sharey=True) creates one row, two columns of Axes sharing the y-axis.
  2. Step 2: Check code correctness

    fig, (ax1, ax2) = plt.subplots(1, 2, sharey=True) ax1.plot([1,2,3], [4,5,6]) ax2.plot([1,2,3], [6,5,4]): fig, (ax1, ax2) = plt.subplots(1, 2, sharey=True) ax1.plot([1,2,3], [4,5,6]) ax2.plot([1,2,3], [6,5,4]) correctly unpacks two Axes and plots data with shared y-axis. fig, ax = plt.subplots(1, 2) ax[0].plot([1,2,3], [4,5,6]) ax[1].plot([1,2,3], [6,5,4]) omits sharey=True. fig = plt.figure() ax1 = fig.add_subplot(1, 2, 1) ax2 = fig.add_subplot(1, 2, 2) ax1.sharey(ax2) calls non-existent sharey() method. fig, ax = plt.subplots(2, 1) ax[0].plot([1,2,3], [4,5,6]) ax[1].plot([1,2,3], [6,5,4]) creates vertical subplots.
  3. Final Answer:

    fig, (ax1, ax2) = plt.subplots(1, 2, sharey=True) ax1.plot([1,2,3], [4,5,6]) ax2.plot([1,2,3], [6,5,4]) -> Option A
  4. Quick Check:

    Use sharey=True in plt.subplots() for shared y-axis [OK]
Hint: Use sharey=True in plt.subplots() for shared y-axis [OK]
Common Mistakes:
  • Trying to call sharey() on Axes objects
  • Creating vertical subplots instead of horizontal
  • Not unpacking multiple Axes correctly
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