When working with multiple datasets, creating separate charts can get messy. That’s where subplots come in.

Subplots allow you to display multiple graphs in a single figure, making comparison and analysis much easier.


🔹 What are Subplots?

Subplots are multiple plots arranged in a grid within a single figure.

👉 Think of it as:

  • One window
  • Multiple charts inside it

🔹 When to Use Subplots?

Use subplots when:

✔ You want to compare multiple datasets
✔ You need to display different chart types together
✔ You want a clean and organized layout


🔹 Basic Example

import matplotlib.pyplot as pltfig, axs = plt.subplots(2)axs[0].plot([1, 2, 3], [3, 2, 1])
axs[1].plot([1, 2, 3], [1, 2, 3])plt.show()

🔹 Output Explanation

  • plt.subplots(2) → Creates 2 rows of plots
  • axs[0] → First subplot
  • axs[1] → Second subplot

🔹 Grid Layout (Rows & Columns)

fig, axs = plt.subplots(2, 2)axs[0, 0].plot([1,2], [3,4])
axs[0, 1].bar([1,2], [5,6])
axs[1, 0].scatter([1,2], [7,8])
axs[1, 1].hist([1,2,2,3])plt.show()

👉 Creates a 2×2 grid of plots.


🔹 Real-Life Use Cases

📊 Comparing multiple datasets
📈 Dashboard-style visualizations
📉 Before vs After comparisons
📦 Multi-metric analysis


🔹 Customizing Subplots

fig, axs = plt.subplots(2)axs[0].plot([1,2,3], [3,2,1])
axs[0].set_title("Plot 1")axs[1].plot([1,2,3], [1,2,3])
axs[1].set_title("Plot 2")plt.tight_layout()
plt.show()

🔹 Important Functions

FunctionDescription
plt.subplots()Create subplot grid
axs[i].plot()Plot on specific subplot
set_title()Add title to subplot
tight_layout()Adjust spacing automatically

🔹 Sharing Axes

fig, axs = plt.subplots(2, sharex=True)axs[0].plot([1,2,3], [3,2,1])
axs[1].plot([1,2,3], [1,2,3])plt.show()

👉 Useful for comparing data on the same scale.


🔹 Adjusting Figure Size

fig, axs = plt.subplots(2, 2, figsize=(8, 6))

🔹 Saving the Figure

plt.savefig("subplots.png")

🔹 Best Practices

✔ Keep layout simple and readable
✔ Use titles for each subplot
✔ Use tight_layout() to avoid overlap
✔ Maintain consistent scales when comparing
✔ Avoid overcrowding too many plots


🔗 Useful Resources


🔚 Conclusion

Subplots are a powerful feature in Matplotlib that allow you to organize multiple visualizations in one place. They are essential for comparisons and dashboard-style analysis.

Master subplots to make your data visualization more structured and professional.


🔖 Hashtags

#Matplotlib #Python #DataVisualization #Subplots #DataScience #MachineLearning #Coding #Analytics #Programming #AI #BigData

Learn Python