Bird
Raised Fist0
Matplotlibdata~15 mins

Figure-level methods vs axes-level in Matplotlib - Trade-offs & Expert Analysis

Choose your learning style10 modes available
Overview - Figure-level methods vs axes-level
What is it?
In matplotlib, figure-level methods control the entire drawing area called the figure, which can contain multiple plots or axes. Axes-level methods focus on individual plots or subplots within the figure, managing details like lines, labels, and ticks. Understanding the difference helps you organize and customize your visualizations effectively. This distinction allows you to work either on the big picture or on specific parts of your chart.
Why it matters
Without knowing the difference, you might try to change a small part of a plot using a figure-level method or vice versa, leading to confusion or errors. This can slow down your work and make your charts look wrong. Knowing when to use figure-level or axes-level methods helps you create clear, precise, and well-organized visualizations that communicate your data story better.
Where it fits
Before this, you should understand basic matplotlib concepts like figures, axes, and plotting simple charts. After learning this, you can explore advanced customization, multiple subplots, and integrating matplotlib with other libraries like seaborn or pandas for richer visualizations.
Mental Model
Core Idea
Figure-level methods manage the whole canvas, while axes-level methods manage individual plots inside that canvas.
Think of it like...
Think of a figure as a photo album and axes as the individual photos inside it. Figure-level methods let you arrange or decorate the whole album, while axes-level methods let you edit each photo separately.
┌─────────────────────────────┐
│          Figure             │  ← whole canvas
│  ┌───────────────┐          │
│  │    Axes 1     │          │  ← individual plot 1
│  └───────────────┘          │
│  ┌───────────────┐          │
│  │    Axes 2     │          │  ← individual plot 2
│  └───────────────┘          │
└─────────────────────────────┘
Build-Up - 6 Steps
1
FoundationUnderstanding Figure and Axes Basics
🤔
Concept: Learn what figures and axes are in matplotlib and how they relate.
A figure is the entire window or page where your plots appear. Axes are the individual plots or graphs inside the figure. You can have one or many axes in a figure. For example, a figure can hold a single plot or a grid of plots.
Result
You can create a figure and add one or more axes to it, preparing the space for plotting.
Knowing the difference between figure and axes is the foundation for controlling where and how your data is shown.
2
FoundationCreating Plots with Axes-Level Methods
🤔
Concept: Use axes-level methods to draw and customize individual plots.
After creating axes, you use methods like plot(), scatter(), set_title(), and set_xlabel() on the axes object to draw lines, points, and labels. These methods affect only that specific plot, not the entire figure.
Result
You get a single plot with customized lines and labels inside the figure.
Axes-level methods give you detailed control over each plot, letting you tailor the data presentation precisely.
3
IntermediateUsing Figure-Level Methods for Overall Control
🤔
Concept: Figure-level methods manage the whole figure, including layout and saving.
Methods like suptitle(), tight_layout(), and savefig() belong to the figure object. suptitle() adds a title above all plots, tight_layout() adjusts spacing between plots, and savefig() saves the entire figure as an image file.
Result
You can add a main title, fix spacing, and save your complete set of plots as one image.
Figure-level methods help you organize and finalize your entire visualization, not just individual plots.
4
IntermediateManaging Multiple Axes in One Figure
🤔Before reading on: do you think calling plot() on the figure object draws on all axes or none? Commit to your answer.
Concept: Learn how to create and control multiple axes inside one figure and how figure-level methods affect them.
You can create multiple axes using subplots() or add_subplot(). Each axes can be customized separately with axes-level methods. Figure-level methods like tight_layout() adjust spacing for all axes at once. Calling plot() on the figure object does not work; plotting must be done on axes.
Result
Multiple plots appear in one figure, each independently controlled but arranged neatly by figure-level methods.
Understanding that plotting happens on axes, not figures, prevents common errors and clarifies control flow.
5
AdvancedCustomizing Figures and Axes Together
🤔Before reading on: do you think changing figure size affects axes size automatically or not? Commit to your answer.
Concept: Explore how figure size and axes size relate and how to customize both for better visuals.
Changing figure size with figure.set_size_inches() changes the whole canvas size. Axes size depends on figure size and layout. You can adjust axes position and size manually with set_position() or use gridspec for complex layouts. Combining figure-level and axes-level adjustments gives precise control over the final look.
Result
You get a figure with well-sized plots arranged exactly as you want.
Knowing how figure and axes sizes interact helps you create professional, publication-quality charts.
6
ExpertInternals of Figure and Axes Interaction
🤔Before reading on: do you think axes are independent objects or tightly bound to their figure? Commit to your answer.
Concept: Understand the internal relationship and communication between figure and axes objects in matplotlib.
Each axes is an object linked to its parent figure. The figure manages the canvas and rendering, while axes handle data plotting. When you call a figure-level method, it can loop through all axes to apply changes. Axes can request redraws from the figure. This design allows modular control but requires knowing which object to call for each task.
Result
You understand why some methods only exist on figure or axes and how they coordinate to produce the final image.
Understanding this internal design prevents confusion and helps debug complex plotting issues.
Under the Hood
Matplotlib uses an object-oriented design where the Figure object represents the entire drawing area, and Axes objects represent individual plots inside it. The Figure manages the canvas and rendering pipeline, while Axes handle plotting data, labels, and ticks. When rendering, the Figure calls each Axes to draw its content, then combines them into one image. This separation allows independent control and flexible layouts.
Why designed this way?
This design was chosen to separate concerns: the figure handles overall layout and output, while axes focus on data visualization details. It allows users to create complex multi-plot figures with independent customization. Alternatives like a single monolithic plot object would limit flexibility and reuse.
┌───────────────┐
│   Figure      │
│  ┌─────────┐  │
│  │  Axes 1 │◄── manages data plotting
│  └─────────┘  │
│  ┌─────────┐  │
│  │  Axes 2 │◄── independent plot
│  └─────────┘  │
│  Rendering & │
│  layout     │
└───────────────┘
Myth Busters - 4 Common Misconceptions
Quick: Does calling plot() on a figure object draw on all axes or none? Commit to your answer.
Common Belief:Calling plot() on the figure object draws the plot on all axes inside it automatically.
Tap to reveal reality
Reality:The figure object does not have a plot() method; plotting must be done on individual axes objects.
Why it matters:Trying to plot on the figure causes errors or no output, confusing beginners and wasting time.
Quick: Does changing the figure size automatically resize all axes proportionally? Commit to your answer.
Common Belief:Changing figure size always resizes all axes inside it proportionally without extra work.
Tap to reveal reality
Reality:Axes size depends on figure size and layout settings; sometimes axes need manual adjustment after resizing the figure.
Why it matters:Assuming automatic resizing can lead to cramped or oddly spaced plots, hurting readability.
Quick: Can you add a title to the whole figure using axes.set_title()? Commit to your answer.
Common Belief:You can add a main title for the entire figure using axes.set_title().
Tap to reveal reality
Reality:axes.set_title() adds a title only to that specific plot; use figure.suptitle() for a main figure title.
Why it matters:Misplacing titles can confuse viewers and make your visualization look unprofessional.
Quick: Are figure-level methods always applied before axes-level methods? Commit to your answer.
Common Belief:Figure-level methods always override axes-level methods if they conflict.
Tap to reveal reality
Reality:Figure-level and axes-level methods control different scopes and do not override each other; they complement each other.
Why it matters:Misunderstanding this can cause incorrect assumptions about which method to use for customization.
Expert Zone
1
Figure-level methods like tight_layout() can fail silently if axes have manual positions, requiring manual adjustment.
2
Axes objects can be shared between figures in rare cases, but this breaks the usual parent-child relationship and can cause rendering issues.
3
Some third-party libraries build on matplotlib by wrapping figure-level methods to simplify multi-axes management, hiding complexity from users.
When NOT to use
Avoid using figure-level methods when you need fine-grained control over individual plots; use axes-level methods instead. Conversely, do not use axes-level methods to manage overall layout or saving the figure; use figure-level methods. For interactive plotting, consider libraries like Plotly that handle figure and axes differently.
Production Patterns
In production, developers create figures with multiple axes for dashboards, using figure-level methods to arrange plots and axes-level methods to customize each chart. Automated scripts often save figures with savefig() after applying tight_layout() to ensure neat output. Complex layouts use gridspec for axes placement, combining both levels effectively.
Connections
Object-Oriented Programming
Figure and axes are objects with parent-child relationships, similar to classes and instances.
Understanding OOP helps grasp why figure-level methods control the container and axes-level methods control contained objects.
Graphic Design Layout
Figure-level methods manage overall layout like a page designer, while axes-level methods manage individual elements like text or images.
Knowing layout principles in design helps understand spacing and arrangement in matplotlib figures.
Photography Albums
A figure is like an album holding photos (axes), where you can decorate the album or edit each photo separately.
This real-world concept clarifies the separation of concerns between figure and axes.
Common Pitfalls
#1Trying to plot directly on the figure object.
Wrong approach:fig = plt.figure() fig.plot([1, 2, 3], [4, 5, 6]) # wrong, figure has no plot()
Correct approach:fig = plt.figure() ax = fig.add_subplot(111) ax.plot([1, 2, 3], [4, 5, 6]) # correct, plot on axes
Root cause:Misunderstanding that plotting functions belong to axes, not the figure.
#2Using axes.set_title() to add a main title for the whole figure.
Wrong approach:fig, ax = plt.subplots() ax.set_title('Main Title') # only titles one plot
Correct approach:fig, ax = plt.subplots() fig.suptitle('Main Title') # titles entire figure
Root cause:Confusing axes-level and figure-level titles.
#3Assuming tight_layout() always fixes spacing perfectly without checking axes positions.
Wrong approach:fig, ax = plt.subplots() ax.set_position([0.1, 0.1, 0.8, 0.8]) fig.tight_layout() # may not adjust as expected
Correct approach:fig, ax = plt.subplots() fig.tight_layout() # works best with default axes positions
Root cause:Not realizing manual axes positioning can interfere with automatic layout adjustments.
Key Takeaways
Figures are the whole canvas; axes are individual plots inside the figure.
Plotting commands belong to axes, not figures, so always plot on axes objects.
Figure-level methods control overall layout, titles, and saving, while axes-level methods customize individual plots.
Understanding the separation helps avoid common errors and creates clearer, more flexible visualizations.
Advanced control comes from combining figure-level and axes-level methods thoughtfully.

Practice

(1/5)
1. Which method would you use to set the main title for the entire figure in matplotlib?
easy
A. plt.title()
B. ax.set_title()
C. ax.set_xlabel()
D. fig.suptitle()

Solution

  1. Step 1: Understand figure-level vs axes-level

    Figure-level methods control the whole figure, axes-level methods control individual plots.
  2. Step 2: Identify method for main figure title

    The method fig.suptitle() sets the main title for the entire figure, while ax.set_title() sets title for one subplot.
  3. Final Answer:

    fig.suptitle() -> Option D
  4. Quick Check:

    Figure main title = fig.suptitle() [OK]
Hint: Main figure title uses fig.suptitle(), not ax.set_title() [OK]
Common Mistakes:
  • Using ax.set_title() for main figure title
  • Using plt.title() which affects current axes
  • Confusing xlabel with title
2. Which of the following is the correct syntax to set the x-axis label for a single plot (axes) in matplotlib?
easy
A. plt.set_xlabel('X Label')
B. fig.set_xlabel('X Label')
C. ax.set_xlabel('X Label')
D. fig.xlabel('X Label')

Solution

  1. Step 1: Identify the object controlling axis labels

    Axis labels belong to individual plots, so axes-level methods are used.
  2. Step 2: Choose correct method and object

    The method set_xlabel() is called on an axes object, so ax.set_xlabel('X Label') is correct.
  3. Final Answer:

    ax.set_xlabel('X Label') -> Option C
  4. Quick Check:

    Axis label = ax.set_xlabel() [OK]
Hint: Use ax.set_xlabel() for x-axis label, not fig or plt [OK]
Common Mistakes:
  • Calling set_xlabel() on figure object
  • Using plt.set_xlabel() which does not exist
  • Confusing axis label with figure title
3. What will the following code display?
import matplotlib.pyplot as plt
fig, ax = plt.subplots()
fig.suptitle('Main Title')
ax.set_title('Plot Title')
ax.set_xlabel('X Axis')
ax.set_ylabel('Y Axis')
plt.show()
medium
A. A figure with main title 'Main Title' and one plot titled 'Plot Title' with labeled axes
B. Only a plot titled 'Main Title' with axes labeled 'X Axis' and 'Y Axis'
C. A figure with no titles but axes labeled 'X Axis' and 'Y Axis'
D. Error because fig.suptitle() cannot be used with ax.set_title()

Solution

  1. Step 1: Understand figure and axes titles

    fig.suptitle() sets the main figure title; ax.set_title() sets the subplot title.
  2. Step 2: Analyze axis labels and display

    ax.set_xlabel() and ax.set_ylabel() label the x and y axes of the plot. The code will show all these correctly.
  3. Final Answer:

    A figure with main title 'Main Title' and one plot titled 'Plot Title' with labeled axes -> Option A
  4. Quick Check:

    fig.suptitle + ax.set_title + ax labels = A figure with main title 'Main Title' and one plot titled 'Plot Title' with labeled axes [OK]
Hint: fig.suptitle is main title; ax.set_title is subplot title [OK]
Common Mistakes:
  • Thinking fig.suptitle replaces ax.set_title
  • Expecting error when using both titles
  • Ignoring axis labels
4. Identify the error in this code snippet:
import matplotlib.pyplot as plt
fig, ax = plt.subplots()
fig.set_title('Main Title')
ax.set_xlabel('X Label')
plt.show()
medium
A. fig.set_title() is not a valid method for figure objects
B. ax.set_xlabel() should be called on fig, not ax
C. plt.show() must be called before setting titles
D. fig, ax = plt.subplots() returns only one object

Solution

  1. Step 1: Check figure method usage

    The figure object does not have a method called set_title(). The correct method for figure title is suptitle().
  2. Step 2: Verify other method calls

    ax.set_xlabel() is correct for labeling x-axis. plt.show() is correctly placed at the end.
  3. Final Answer:

    fig.set_title() is not a valid method for figure objects -> Option A
  4. Quick Check:

    Figure title method = fig.suptitle() not fig.set_title() [OK]
Hint: Figure title uses suptitle(), not set_title() [OK]
Common Mistakes:
  • Using fig.set_title() instead of fig.suptitle()
  • Confusing axes methods with figure methods
  • Calling plt.show() too early
5. You want to create a figure with 2 subplots side by side. You want a main title for the figure and individual titles for each subplot. Which code correctly achieves this?
hard
A. fig, axs = plt.subplots(1, 2) fig.title('Main Title') axs[0].title('Left Plot') axs[1].title('Right Plot') plt.show()
B. fig, axs = plt.subplots(1, 2) fig.suptitle('Main Title') axs[0].set_title('Left Plot') axs[1].set_title('Right Plot') plt.show()
C. fig, axs = plt.subplots(2, 1) fig.set_title('Main Title') axs[0].set_xlabel('Left Plot') axs[1].set_xlabel('Right Plot') plt.show()
D. fig, axs = plt.subplots(1, 2) axs.set_title('Main Title') fig.set_title('Left Plot') fig.set_title('Right Plot') plt.show()

Solution

  1. Step 1: Create subplots and set main figure title

    plt.subplots(1, 2) creates two side-by-side plots. fig.suptitle() sets the main figure title.
  2. Step 2: Set individual subplot titles correctly

    Each subplot is accessed by axs[0] and axs[1]. Use set_title() to set their titles.
  3. Step 3: Verify other options are incorrect

    The other options misuse methods like fig.set_title() or fig.title() which do not exist or use wrong subplot layout.
  4. Final Answer:

    fig, axs = plt.subplots(1, 2) fig.suptitle('Main Title') axs[0].set_title('Left Plot') axs[1].set_title('Right Plot') plt.show() -> Option B
  5. Quick Check:

    Figure main title = fig.suptitle(), subplot titles = axs[i].set_title() [OK]
Hint: Use fig.suptitle() for main title, axs[i].set_title() for subplots [OK]
Common Mistakes:
  • Using fig.set_title() instead of fig.suptitle()
  • Calling title() instead of set_title()
  • Wrong subplot layout dimensions
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