0
0
Data Analysis Pythondata~15 mins

Figure and axes creation in Data Analysis Python - Deep Dive

Choose your learning style9 modes available
Overview - Figure and axes creation
What is it?
Figure and axes creation is about making the basic parts of a plot in Python using libraries like Matplotlib. A figure is the whole image or window where plots appear. Axes are the individual plots or charts inside the figure where data is drawn. This concept helps organize and control how visual data is displayed.
Why it matters
Without understanding how to create figures and axes, you cannot control where and how your data plots appear. This would make it hard to compare multiple charts or customize your visuals. Good figure and axes creation lets you build clear, organized, and professional graphs that communicate data effectively.
Where it fits
Before this, you should know basic Python programming and how to install and import libraries. After learning figure and axes creation, you can explore plotting different chart types, customizing styles, and adding labels or legends to make your visuals informative.
Mental Model
Core Idea
A figure is like a blank canvas, and axes are the frames where you paint your data plots.
Think of it like...
Imagine a photo album (figure) that holds several pictures (axes). Each picture shows a different scene, but all belong to the same album. You decide how many pictures to include and where to place them.
┌─────────────────────────────┐
│          Figure             │
│  ┌───────────┐  ┌─────────┐ │
│  │  Axes 1   │  │ Axes 2  │ │
│  │ (plot 1)  │  │(plot 2) │ │
│  └───────────┘  └─────────┘ │
│                             │
└─────────────────────────────┘
Build-Up - 7 Steps
1
FoundationUnderstanding the Figure Concept
🤔
Concept: Learn what a figure is and why it is the main container for plots.
In Matplotlib, a figure is the entire window or image that holds one or more plots. You create a figure first, which acts like a blank canvas. You can think of it as the paper where you will draw your charts.
Result
You have a blank figure ready to hold plots.
Understanding the figure as the main container helps you organize multiple plots in one image.
2
FoundationIntroducing Axes as Plot Areas
🤔
Concept: Axes are the areas inside a figure where data is drawn as plots.
Axes are like frames inside the figure. Each axes can hold one plot, like a line chart or bar chart. You can create axes inside a figure to decide where your plot appears.
Result
You have a figure with one or more axes ready for plotting data.
Knowing axes are separate from the figure lets you control layout and add multiple plots.
3
IntermediateCreating Figures and Axes with plt.subplots()
🤔Before reading on: do you think plt.subplots() creates one figure with multiple axes or multiple figures with one axes each? Commit to your answer.
Concept: plt.subplots() is a common way to create a figure and one or more axes at once.
Using plt.subplots(), you get a figure and axes in one step. For example, fig, ax = plt.subplots() creates one figure and one axes. You can also create multiple axes by passing rows and columns, like plt.subplots(2, 2) for four plots.
Result
You get a figure object and axes object(s) ready for plotting.
Understanding plt.subplots() simplifies creating complex layouts with multiple plots.
4
IntermediateCustomizing Axes Placement Manually
🤔Before reading on: do you think axes can only be placed in a grid or anywhere inside the figure? Commit to your answer.
Concept: You can place axes anywhere inside a figure by specifying their position and size manually.
Using fig.add_axes([left, bottom, width, height]), you add an axes at a custom position. The numbers are fractions of the figure size, from 0 to 1. This lets you create unusual layouts or inset plots.
Result
Axes appear exactly where you want inside the figure.
Knowing manual placement gives full control over plot layout beyond grids.
5
IntermediateWorking with Multiple Axes Objects
🤔Before reading on: do you think multiple axes returned by plt.subplots() are in a list, array, or separate variables? Commit to your answer.
Concept: When creating multiple axes, you get them as arrays or lists to access each plot individually.
For example, fig, axs = plt.subplots(2, 2) returns axs as a 2x2 array of axes. You can plot on axs[0,0], axs[1,1], etc. This helps organize and update each subplot separately.
Result
You can control each subplot independently within one figure.
Understanding axes arrays helps manage complex multi-plot figures efficiently.
6
AdvancedFigure and Axes Interaction in Plotting
🤔Before reading on: do you think plotting commands affect the figure, the axes, or both? Commit to your answer.
Concept: Plotting commands usually target axes, but the figure manages overall layout and rendering.
When you call plot functions, they draw on a specific axes. The figure handles spacing, titles, and saving the image. Knowing this separation helps debug layout issues and customize appearance.
Result
You can precisely control where and how data is drawn and how the whole image looks.
Recognizing the division of roles between figure and axes clarifies plotting behavior and customization.
7
ExpertAdvanced Figure and Axes Management Internals
🤔Before reading on: do you think figures and axes are recreated every time you plot, or are they persistent objects? Commit to your answer.
Concept: Figures and axes are persistent objects managed by Matplotlib's backend, allowing updates and redraws without recreating them.
Matplotlib keeps figure and axes objects in memory. When you update a plot, it modifies these objects and redraws the canvas. This design supports interactive plotting and efficient updates. Understanding this helps optimize performance and avoid common bugs like overlapping plots.
Result
You can build interactive and dynamic plots by manipulating figure and axes objects directly.
Knowing the persistence and backend management of figures and axes unlocks advanced plotting and debugging skills.
Under the Hood
Matplotlib creates a Figure object as the main container. Inside it, Axes objects represent individual plot areas. Each Axes manages its own coordinate system, data, and drawing commands. The Figure manages layout, rendering, and interaction with the display or file output. When you call plotting functions, they update the Axes, which then notify the Figure to redraw the image.
Why designed this way?
This design separates concerns: the Figure handles overall layout and output, while Axes focus on plotting data. It allows flexible layouts with multiple plots and efficient updates. Early plotting libraries mixed these roles, causing inflexible and hard-to-maintain code. Matplotlib's object model supports both simple and complex visualizations.
┌─────────────────────────────┐
│          Figure             │
│  ┌───────────┐  ┌─────────┐ │
│  │  Axes 1   │  │ Axes 2  │ │
│  │(coordinates│ │(coordinates│
│  │ and data)  │ │ and data) │
│  └───────────┘  └─────────┘ │
│                             │
│  Layout & Rendering Manager  │
└─────────────────────────────┘
Myth Busters - 4 Common Misconceptions
Quick: Does plt.plot() create a new figure automatically every time? Commit yes or no.
Common Belief:Calling plt.plot() always creates a new figure window.
Tap to reveal reality
Reality:plt.plot() draws on the current active axes in the current figure. It does not create a new figure unless none exists.
Why it matters:Assuming a new figure is created each time can cause confusion when plots overlap or update unexpectedly.
Quick: Can you add multiple axes to a figure anywhere you want? Commit yes or no.
Common Belief:Axes can only be arranged in a grid layout inside a figure.
Tap to reveal reality
Reality:Axes can be placed anywhere inside a figure using manual positioning with add_axes().
Why it matters:Believing axes are limited to grids restricts creative and precise plot layouts.
Quick: Are figures and axes recreated every time you plot? Commit yes or no.
Common Belief:Each plot command creates new figure and axes objects.
Tap to reveal reality
Reality:Figures and axes are persistent objects that update with new plot commands.
Why it matters:Misunderstanding persistence can lead to bugs like overlapping plots or unexpected plot updates.
Quick: Does plt.subplots() always return a single axes object? Commit yes or no.
Common Belief:plt.subplots() returns only one axes object regardless of parameters.
Tap to reveal reality
Reality:plt.subplots() returns a single axes if one plot is created, or an array of axes if multiple plots are requested.
Why it matters:Not handling multiple axes correctly can cause errors when plotting or customizing subplots.
Expert Zone
1
Figures can have multiple axes with overlapping or inset plots, enabling complex visual storytelling.
2
Axes objects maintain their own coordinate systems, allowing different scales or projections within one figure.
3
Matplotlib's backend manages figure rendering asynchronously, which can cause delays or require explicit redraw commands in interactive environments.
When NOT to use
For very simple plots, using high-level plotting functions like plt.plot() without explicit figure or axes creation is easier. For interactive dashboards, specialized libraries like Plotly or Bokeh offer better interactivity. When performance is critical, consider libraries optimized for speed like Datashader.
Production Patterns
Professionals create figures and axes explicitly to build multi-panel figures for reports or publications. They use gridspec or manual axes placement for precise control. Interactive applications manipulate axes objects directly to update plots dynamically without recreating figures.
Connections
Object-Oriented Programming
Figure and axes creation uses object-oriented design with Figure and Axes as objects.
Understanding how figures and axes are objects helps grasp how methods and properties control plotting behavior.
Graphic Design Layout
Arranging axes inside a figure is like designing layouts in graphic design.
Knowing layout principles from design helps create balanced and readable multi-plot figures.
User Interface Windows
A figure is like a window, and axes are panels inside it, similar to UI design.
Understanding window and panel concepts in UI design clarifies how figures and axes manage space and interaction.
Common Pitfalls
#1Plotting without creating or selecting axes causes plots to overlap unexpectedly.
Wrong approach:plt.plot([1, 2, 3], [4, 5, 6]) plt.plot([1, 2, 3], [6, 5, 4])
Correct approach:fig, ax = plt.subplots() ax.plot([1, 2, 3], [4, 5, 6]) ax.plot([1, 2, 3], [6, 5, 4])
Root cause:Not managing axes explicitly leads to plotting on the same default axes, causing confusion.
#2Trying to index axes as a list when only one axes was created.
Wrong approach:fig, axs = plt.subplots() axs[0].plot([1, 2], [3, 4])
Correct approach:fig, ax = plt.subplots() ax.plot([1, 2], [3, 4])
Root cause:Assuming multiple axes are always returned causes errors when only one axes object exists.
#3Using add_axes() with incorrect coordinates outside [0,1] range causes axes not to appear.
Wrong approach:fig = plt.figure() fig.add_axes([1.2, 0.5, 0.3, 0.3])
Correct approach:fig = plt.figure() fig.add_axes([0.5, 0.5, 0.3, 0.3])
Root cause:Misunderstanding that axes position coordinates are fractions of figure size leads to invisible plots.
Key Takeaways
A figure is the main container for plots, and axes are the individual plot areas inside it.
Creating figures and axes explicitly gives you control over plot layout and appearance.
plt.subplots() is a powerful function to create figures and multiple axes easily.
Axes can be placed manually anywhere inside a figure for flexible layouts.
Understanding the persistence and roles of figure and axes objects helps build complex and interactive visualizations.