Skip to main content
Brave Programmer Logo

BraveProgrammer

BraveProgrammer

HomeProjectsBlogsCoursesLessonsAbout

Site footer

BraveProgrammer

Free coding courses, practical tutorials, and real projects from BraveProgrammer. Learn web development with React, Next.js, and TypeScript.

Navigation

  • Home
  • Projects
  • Blogs
  • Courses

Resources

  • About
  • Lessons
  • Teach on BraveProgrammer

© 2026 BraveProgrammer. All rights reserved.

Subplots, Grids, and | Master Data Science with Python lesso | BraveProgrammer
  1. Courses
  2. /
  3. Master Data Science with Python

Lesson 34 of 60

·python

Subplots, Grids, and Layouts

20 minutes

Course progress57%

Subplots and Layout Management

Often you need multiple plots in a single figure.

Simple 2×2 grid of subplots

fig, axs = plt.subplots(2, 2, figsize=(10,8))
axs[0,0].plot(x, y)
axs[0,0].set_title()
axs[,].scatter(x, y)
axs[,].set_title()
axs[,].hist(y, bins=)
axs[,].set_title()
axs[,].boxplot(y)
axs[,].set_title()
plt.tight_layout()
plt.show()
'Top‑Left'
0
1
0
1
'Top‑Right'
1
0
20
1
0
'Bottom‑Left'
1
1
1
1
'Bottom‑Right'

Using GridSpec for custom layout

import matplotlib.gridspec as gridspec

fig = plt.figure(constrained_layout=True)
gs = gridspec.GridSpec(3, 3, figure=fig)
ax1 = fig.add_subplot(gs[0, :])   # first row, spanning all columns
ax2 = fig.add_subplot(gs[1:, 0:2]) # bottom‑left 2×2 block
ax3 = fig.add_subplot(gs[1:, 2])   # rightmost column, spanning rows 1‑2

Sharing axes

fig, (ax1, ax2) = plt.subplots(2, 1, sharex=True, sharey=True)

Adding a single legend for all subplots

handles, labels = ax1.get_legend_handles_labels()
fig.legend(handles, labels, loc='upper center', ncol=3)

Info

plt.tight_layout() or constrained_layout=True helps avoid overlapping labels.
Make it stickPractice what you've learned1 quiz · 4 practical tests · Optional activities from Master Data Science with PythonBrowse activities
Previous lessonCustomizing Plots: Styles, Labels, Legends, and ThemesContinue to lesson 35Advanced Plotting: Histograms, Boxplots, and Violin PlotsBack to Master Data Science with Python curriculum