0
0
Matplotlibdata~15 mins

Figure creation with plt.figure in Matplotlib - Deep Dive

Choose your learning style9 modes available
Overview - Figure creation with plt.figure
What is it?
Figure creation with plt.figure is how you start making a new drawing area in matplotlib, a popular tool for making charts in Python. A figure is like a blank canvas where you can add one or more plots or graphs. Using plt.figure lets you control the size, resolution, and other properties of this canvas before adding your data visuals. This helps organize and customize your charts clearly.
Why it matters
Without creating figures explicitly, all plots would go to a default canvas, making it hard to manage multiple charts or customize their look. plt.figure solves this by giving you control over each drawing area, so you can make clear, professional visuals. This is important when you want to compare charts side by side or prepare visuals for reports and presentations.
Where it fits
Before learning plt.figure, you should know basic Python and how to plot simple charts using matplotlib's pyplot interface. After mastering figure creation, you can learn about axes, subplots, and advanced customization like adding titles, labels, and legends. This fits early in the matplotlib learning path as the foundation for all plotting.
Mental Model
Core Idea
plt.figure creates a new blank canvas where you can draw one or more plots, controlling size and appearance before adding data.
Think of it like...
It's like opening a new sheet of paper before drawing your pictures, so you decide how big the paper is and how it looks before starting.
┌───────────────┐
│   plt.figure  │  ← Create blank canvas
│  (canvas)     │
│               │
│  ┌─────────┐  │  ← Add plots inside
│  │  plot1  │  │
│  └─────────┘  │
│  ┌─────────┐  │
│  │  plot2  │  │
│  └─────────┘  │
└───────────────┘
Build-Up - 7 Steps
1
FoundationWhat is plt.figure in matplotlib
🤔
Concept: Introduction to the plt.figure function as the way to create a new figure canvas.
In matplotlib, plt.figure() creates a new figure object. This figure is like a blank page where you can draw your charts. If you don't create a figure, matplotlib uses a default one. You can call plt.figure() with no arguments to get a default blank figure.
Result
A new empty figure canvas is created, ready for plotting.
Understanding that plt.figure is the starting point for any plot helps you control where and how your charts appear.
2
FoundationBasic usage of plt.figure
🤔
Concept: How to create a figure and add a simple plot to it.
You create a figure by calling fig = plt.figure(). Then you add plots using plt.plot() or other plotting functions. For example: import matplotlib.pyplot as plt fig = plt.figure() plt.plot([1, 2, 3], [4, 5, 6]) plt.show() This creates a figure and draws a line plot on it.
Result
A window or image with a line plot appears on a blank figure canvas.
Knowing that plt.figure creates the canvas and plt.plot adds content shows the two-step process of making a chart.
3
IntermediateCustomizing figure size and resolution
🤔Before reading on: do you think figure size is set by the plot data or by plt.figure parameters? Commit to your answer.
Concept: You can control the figure's width, height, and resolution using parameters in plt.figure().
plt.figure() accepts parameters like figsize=(width, height) in inches and dpi for dots per inch (resolution). For example: fig = plt.figure(figsize=(8, 4), dpi=100) plt.plot([1, 2, 3], [4, 5, 6]) plt.show() This creates a wider figure with better resolution.
Result
The plot appears on a figure sized 8 inches wide and 4 inches tall with 100 dpi resolution.
Understanding figure size and dpi lets you prepare visuals that fit specific spaces or print quality needs.
4
IntermediateMultiple figures and switching between them
🤔Before reading on: do you think matplotlib can show multiple figures at once or only one? Commit to your answer.
Concept: You can create multiple figures and switch between them to plot different charts separately.
Each plt.figure() call creates a new figure object. You can store them in variables and make one active by calling plt.figure(fig.number). For example: fig1 = plt.figure() plt.plot([1, 2], [3, 4]) fig2 = plt.figure() plt.plot([10, 20], [30, 40]) plt.figure(fig1.number) plt.title('First Figure') plt.show() This manages multiple figures independently.
Result
Two separate figures are created, and you can add content to each by switching the active figure.
Knowing how to handle multiple figures helps organize complex visualizations and compare charts side by side.
5
IntermediateAdding subplots inside a figure
🤔
Concept: A figure can hold multiple smaller plots called subplots, arranged in a grid.
Use fig.add_subplot(rows, cols, index) to add subplots inside a figure. For example: fig = plt.figure(figsize=(6, 4)) ax1 = fig.add_subplot(1, 2, 1) # Left subplot ax2 = fig.add_subplot(1, 2, 2) # Right subplot ax1.plot([1, 2, 3], [4, 5, 6]) ax2.plot([10, 20, 30], [40, 50, 60]) plt.show() This creates one figure with two side-by-side plots.
Result
A single figure window shows two separate plots arranged horizontally.
Understanding subplots inside a figure allows you to compare multiple charts in one organized space.
6
AdvancedFigure lifecycle and memory management
🤔Before reading on: do you think figures stay in memory forever or get removed automatically? Commit to your answer.
Concept: Figures consume memory and must be closed explicitly to free resources in long-running programs.
When you create figures, they stay in memory until closed. Use plt.close(fig) to close a figure and free memory. In scripts that create many figures, forgetting to close them can cause slowdowns or crashes. For example: fig = plt.figure() plt.plot([1, 2], [3, 4]) plt.show() plt.close(fig) This closes the figure after showing it.
Result
Memory used by the figure is released, preventing resource leaks.
Knowing figure lifecycle prevents memory issues in programs that generate many plots.
7
ExpertHow plt.figure integrates with backends and GUI
🤔Before reading on: do you think plt.figure directly draws on screen or uses another system? Commit to your answer.
Concept: plt.figure creates a figure object that interacts with matplotlib's backend to render visuals on different platforms or file formats.
Matplotlib separates figure creation from rendering. plt.figure creates a Figure object in memory. The backend (like TkAgg, Qt5Agg) handles drawing on screen or saving to files. This design allows matplotlib to work on many systems and output formats. For example, plt.show() tells the backend to display the figure window. This separation means you can create figures without showing them immediately, or save them directly to images.
Result
Figures are rendered flexibly by different backends, enabling cross-platform and file output support.
Understanding the backend separation explains why plt.figure is powerful and flexible across environments.
Under the Hood
When you call plt.figure(), matplotlib creates a Figure object in memory. This object holds metadata like size, dpi, and a list of Axes (plots). The Figure does not draw anything immediately. Instead, it waits for plotting commands to add Axes and data. When plt.show() or save commands run, the backend takes the Figure and renders it using GUI libraries or image writers. This design separates data structure from rendering, allowing flexible output.
Why designed this way?
Matplotlib was designed to support many output formats and platforms. Separating figure creation from rendering lets users build complex visuals without immediate display. This also allows batch processing, saving figures to files, or interactive GUI display. Early plotting libraries were limited to immediate drawing, so this design was a major improvement for flexibility and control.
┌───────────────┐       ┌───────────────┐
│ plt.figure()  │──────▶│ Figure Object │
│ (create fig)  │       │ (metadata,    │
└───────────────┘       │  axes list)   │
                        └──────┬────────┘
                               │
                               ▼
                      ┌─────────────────┐
                      │ Backend Renderer │
                      │ (TkAgg, Qt5Agg,  │
                      │  SVG, PDF, etc.) │
                      └────────┬────────┘
                               │
                               ▼
                      ┌─────────────────┐
                      │ Screen or File   │
                      │ (window or image)│
                      └─────────────────┘
Myth Busters - 4 Common Misconceptions
Quick: Does plt.figure() automatically display the figure on screen? Commit yes or no.
Common Belief:Calling plt.figure() immediately shows the figure window on screen.
Tap to reveal reality
Reality:plt.figure() only creates the figure object in memory; you must call plt.show() to display it.
Why it matters:Expecting immediate display can confuse beginners and lead to empty scripts that produce no visible output.
Quick: If you call plt.figure() twice, do the plots go on the same figure or different ones? Commit your answer.
Common Belief:Multiple calls to plt.figure() add plots to the same figure automatically.
Tap to reveal reality
Reality:Each plt.figure() call creates a new separate figure; plots go to the current active figure only.
Why it matters:Misunderstanding this causes plots to appear in unexpected windows or overwrite each other.
Quick: Does changing figsize after creating a figure resize the existing figure? Commit yes or no.
Common Belief:You can resize a figure anytime by changing its figsize attribute after creation.
Tap to reveal reality
Reality:figsize must be set when creating the figure; changing it later does not resize the figure window.
Why it matters:Trying to resize figures dynamically without recreating them leads to confusion and inconsistent visuals.
Quick: Does plt.figure() automatically clear previous plots? Commit yes or no.
Common Belief:Calling plt.figure() clears all previous plots and starts fresh automatically.
Tap to reveal reality
Reality:plt.figure() creates a new figure but does not clear existing figures; previous figures remain unless closed.
Why it matters:Assuming automatic clearing can cause memory leaks or cluttered output with many open figures.
Expert Zone
1
Creating figures without immediately showing them allows batch processing and saving multiple plots efficiently.
2
The figure's dpi affects both on-screen size and saved image quality, so setting dpi is crucial for publication-ready visuals.
3
Backends differ in how they handle figure windows and interactivity, so understanding your backend helps debug display issues.
When NOT to use
Avoid using plt.figure() when you only need quick inline plots in environments like Jupyter notebooks; there, using plt.subplots() or direct plotting is simpler. For very complex layouts, consider higher-level libraries like seaborn or plotly that manage figures internally.
Production Patterns
In production, plt.figure() is used to create multiple distinct charts saved as files for reports. Developers often create figures with specific sizes and dpi for consistent branding. Managing figure lifecycle by closing figures after saving prevents memory leaks in automated pipelines.
Connections
Canvas in GUI programming
plt.figure acts like a canvas object in GUI frameworks where drawings happen.
Knowing how canvases work in GUI helps understand why plt.figure separates drawing area from content.
Memory management in programming
Managing figure lifecycle is similar to managing resources like files or network connections.
Understanding resource cleanup in programming clarifies why closing figures is important to avoid leaks.
Page layout in publishing
Figure size and dpi in matplotlib relate to page size and resolution in print publishing.
Knowing print layout principles helps set figure dimensions and resolution for high-quality outputs.
Common Pitfalls
#1Creating multiple figures without closing them causes memory issues.
Wrong approach:for i in range(100): plt.figure() plt.plot([1, 2, 3], [4, 5, 6]) plt.show()
Correct approach:for i in range(100): fig = plt.figure() plt.plot([1, 2, 3], [4, 5, 6]) plt.show() plt.close(fig)
Root cause:Beginners forget that figures stay in memory until explicitly closed.
#2Expecting plt.figure() to display the plot immediately.
Wrong approach:plt.figure() plt.plot([1, 2, 3], [4, 5, 6]) # No plt.show() called
Correct approach:plt.figure() plt.plot([1, 2, 3], [4, 5, 6]) plt.show()
Root cause:Misunderstanding that plt.figure only creates the canvas, not the display.
#3Trying to resize a figure after creation by changing figsize attribute.
Wrong approach:fig = plt.figure(figsize=(6, 4)) fig.set_figwidth(10) # Does not resize window properly
Correct approach:fig = plt.figure(figsize=(10, 4)) # Set size at creation
Root cause:Not knowing that figure size must be set when creating the figure.
Key Takeaways
plt.figure creates a new blank canvas for your plots, giving you control over size and resolution.
You must call plt.show() to display the figure window; creating a figure alone does not show it.
Multiple figures can exist simultaneously, and you can switch between them to organize your plots.
Setting figure size and dpi at creation helps produce visuals suited for different screens or print.
Closing figures after use is important to free memory and avoid performance problems in long scripts.