0
0
Matplotlibdata~15 mins

Figure and Axes mental model in Matplotlib - Deep Dive

Choose your learning style9 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.