Page9/13
Subplots & Multi-Panel Layouts Β· Page 1 of 1
Creating Subplots
Subplots & Multi-Panel Layouts
Why Multiple Plots?
Comparing distributions, time series, or different aspects of data side-by-side helps spot patterns.
Basic Subplots
import matplotlib.pyplot as plt
# 2 rows, 3 columns β 6 subplots
fig, axes = plt.subplots(2, 3, figsize=(15, 8))
# Access individual axes
axes[0, 0].plot([1, 2, 3])
axes[0, 1].scatter([1, 2, 3], [1, 4, 2])
axes[1, 2].hist([1, 1, 2, 2, 2, 3, 3, 3, 3])
Using GridSpec for Custom Layouts
import matplotlib.gridspec as gridspec
fig = plt.figure()
gs = gridspec.GridSpec(3, 3, figure=fig)
# Big plot on left (spans 2 rows)
ax_left = fig.add_subplot(gs[0:2, 0])
ax_right_top = fig.add_subplot(gs[0, 1:])
ax_right_bot = fig.add_subplot(gs[1:, 1:])
Share Axes (Link Zooming)
fig, (ax1, ax2) = plt.subplots(1, 2, sharex=True) # Same x-axis
ax1.plot(x, y1)
ax2.plot(x, y2)
# Zoom in ax1 β ax2 zooms too!
main.py
Loading...
OUTPUT
βΆClick "Run Code" to executeβ¦