This pattern helps you create a figure and one or more plots (axes) in a clear and organized way.
0
0
Fig, ax = plt.subplots pattern in Matplotlib
Introduction
When you want to draw one or more charts in a single window.
When you need to control the size or layout of your plots.
When you want to customize each plot separately.
When you want to save or show the whole figure with all plots.
When you want to add titles, labels, or legends to your plots.
Syntax
Matplotlib
fig, ax = plt.subplots(nrows=1, ncols=1, figsize=(width, height))
fig is the whole figure or window that holds your plots.
ax is the plot area where you draw your data.
Examples
Create one plot with default size.
Matplotlib
fig, ax = plt.subplots()
Create one plot with width 8 inches and height 6 inches.
Matplotlib
fig, ax = plt.subplots(figsize=(8, 6))
Create a 2 by 2 grid of plots.
axs is a 2D array of axes.Matplotlib
fig, axs = plt.subplots(2, 2)
Create 3 plots stacked vertically with a tall figure size.
Matplotlib
fig, ax = plt.subplots(nrows=3, ncols=1, figsize=(5, 10))
Sample Program
This code creates a figure with one plot. It draws a line connecting points (1,4), (2,5), and (3,6). Then it adds a title and labels for the axes. Finally, it shows the plot window.
Matplotlib
import matplotlib.pyplot as plt # Create a figure and one plot fig, ax = plt.subplots(figsize=(6, 4)) # Draw a simple line ax.plot([1, 2, 3], [4, 5, 6]) # Add title and labels ax.set_title('Simple Line Plot') ax.set_xlabel('X axis') ax.set_ylabel('Y axis') # Show the plot plt.show()
OutputSuccess
Important Notes
If you create multiple plots, ax becomes an array or matrix of axes objects.
You can use fig to adjust the whole figure, like saving it or changing layout.
Always call plt.show() to display your plots when running scripts.
Summary
The fig, ax = plt.subplots() pattern creates a figure and plot(s) together.
fig is the container; ax is where you draw your data.
This pattern helps organize and customize your charts easily.