ProCodebaseProCodebase
  • ModusA Growth OS for your business, on WhatsAppKiosqSell more. Chase less.AI InterviewerAutomated screening & AI-led interviewsXperto AIAI prep companion for candidatesAI Tools HubResume builder, learning paths & more
  • Pre-Vetted DevelopersScreened, scored and ready to interviewAI-Native DevelopersSenior engineers on an hourly basis
  • Services
  • Features
  • AI Coaching
  • Jobs
  • FAQs
Sign inBook a demo
  • Services
  • Features
  • AI Coaching
  • Jobs
  • FAQs
Sign inBook a demo
ProCodebaseProCodebase

ProCodebase Technologies builds AI products for hiring and growth, and ships software for clients as a technical consultancy. We source, screen and deliver pre-vetted developers — so you only interview high-signal candidates.

Products

  • Modus
  • Kiosq
  • AI Interviewer
  • Xperto AI
  • AI Tools Hub

Hire & build

  • Pre-Vetted Developers
  • AI-Native Developers
  • Technical Consultancy
  • MVP Development
  • Features

Resources

  • Articles
  • Topics
  • Certifications
  • Collections
  • Jobs

Company

  • About Us
  • Contact Us
  • Book a Demo
  • FAQs

© 2026 ProCodebase Technologies. All rights reserved.

  • Privacy Policy
  • Terms & Conditions
  • Refund & Cancellation

Level Up Your Skills with Xperto-AI

A multi-AI agent platform that helps you level up your development skills and ace your interview preparation to secure your dream job.

Launch Xperto-AI

Mastering Subplots and Multiple Figures in Matplotlib

author
Generated by
ProCodebase AI

05/10/2024

matplotlib

Sign in to read full article

Introduction

Matplotlib is a powerful plotting library in Python that allows you to create a wide range of visualizations. When working with complex datasets or multiple related plots, it's often necessary to use subplots or multiple figures. In this guide, we'll explore how to effectively use these features to create compelling and informative visualizations.

Getting Started with Subplots

Subplots are a way to create multiple plots within a single figure. They're incredibly useful when you want to compare different datasets or show various aspects of the same data side by side.

Let's start with a basic example:

import matplotlib.pyplot as plt import numpy as np # Create some sample data x = np.linspace(0, 10, 100) y1 = np.sin(x) y2 = np.cos(x) # Create a figure with two subplots fig, (ax1, ax2) = plt.subplots(1, 2, figsize=(10, 4)) # Plot data on the first subplot ax1.plot(x, y1) ax1.set_title('Sine Wave') # Plot data on the second subplot ax2.plot(x, y2) ax2.set_title('Cosine Wave') # Add a main title to the figure fig.suptitle('Trigonometric Functions', fontsize=16) plt.tight_layout() plt.show()

In this example, we create a figure with two subplots side by side. The plt.subplots(1, 2) function creates a figure with one row and two columns of subplots.

Customizing Subplot Layouts

Matplotlib offers great flexibility in arranging subplots. You can create grids of any size and even have subplots span multiple rows or columns.

Here's an example of a more complex layout:

fig = plt.figure(figsize=(12, 8)) # Create a 2x2 grid of subplots ax1 = fig.add_subplot(2, 2, 1) ax2 = fig.add_subplot(2, 2, 2) ax3 = fig.add_subplot(2, 2, 3) ax4 = fig.add_subplot(2, 2, 4) # Plot some data ax1.plot(np.random.rand(50)) ax2.scatter(np.arange(50), np.random.rand(50)) ax3.bar(np.arange(10), np.random.rand(10)) ax4.hist(np.random.randn(1000), bins=30) # Customize titles ax1.set_title('Line Plot') ax2.set_title('Scatter Plot') ax3.set_title('Bar Plot') ax4.set_title('Histogram') plt.tight_layout() plt.show()

This script creates a 2x2 grid of subplots, each with a different type of plot.

Working with Multiple Figures

Sometimes, you might want to create separate figures instead of subplots within a single figure. This is useful when you want to generate multiple independent visualizations.

Here's how you can work with multiple figures:

# Create the first figure plt.figure(1, figsize=(6, 4)) plt.plot(np.random.rand(100)) plt.title('Figure 1: Random Data') # Create the second figure plt.figure(2, figsize=(6, 4)) plt.scatter(np.arange(50), np.random.rand(50)) plt.title('Figure 2: Scatter Plot') # Show both figures plt.show()

This script creates two separate figures, each with its own plot.

Advanced Techniques

Sharing Axes

When working with related data, it's often useful to share axes between subplots:

fig, (ax1, ax2) = plt.subplots(2, 1, sharex=True, figsize=(8, 6)) x = np.linspace(0, 10, 100) ax1.plot(x, np.sin(x)) ax2.plot(x, np.cos(x)) ax1.set_title('Sine and Cosine Waves') ax2.set_xlabel('X-axis') plt.tight_layout() plt.show()

This example creates two subplots that share the same x-axis, making it easier to compare the two plots.

Gridspec for Complex Layouts

For even more control over your subplot layouts, you can use GridSpec:

from matplotlib.gridspec import GridSpec fig = plt.figure(figsize=(12, 8)) gs = GridSpec(3, 3, figure=fig) ax1 = fig.add_subplot(gs[0, :]) ax2 = fig.add_subplot(gs[1, :-1]) ax3 = fig.add_subplot(gs[1:, -1]) ax4 = fig.add_subplot(gs[-1, 0]) ax5 = fig.add_subplot(gs[-1, -2]) # Add plots to each subplot ax1.plot(np.random.rand(100)) ax2.scatter(np.arange(50), np.random.rand(50)) ax3.hist(np.random.randn(200), bins=20) ax4.bar(np.arange(10), np.random.rand(10)) ax5.imshow(np.random.rand(10, 10), cmap='viridis') plt.tight_layout() plt.show()

This creates a complex layout with subplots of different sizes and positions.

Conclusion

Subplots and multiple figures are powerful tools in Matplotlib that allow you to create rich, informative visualizations. By mastering these techniques, you can effectively communicate complex data and relationships in your plots. Remember to experiment with different layouts and configurations to find the best way to present your data.

Popular tags

matplotlibpythondata visualization

Share now!

Like & bookmark

Related collections

  • Streamlit Mastery: From Basics to Advanced

    15/11/2024 · Python

  • Python Advanced Mastery: Beyond the Basics

    13/01/2025 · Python

  • Python with MongoDB: A Practical Guide

    08/11/2024 · Python

  • Matplotlib Mastery: From Plots to Pro Visualizations

    05/10/2024 · Python

  • LangChain Mastery: From Basics to Advanced

    26/10/2024 · Python

Related articles

  • Unleashing the Power of Heatmaps and Color Mapping in Matplotlib

    05/10/2024 · Python

  • Leveraging Python for Efficient Structured Data Processing with LlamaIndex

    05/11/2024 · Python

  • Leveraging LangChain for Enterprise-Level Python Applications

    26/10/2024 · Python

  • Unlocking Advanced Color Mapping Techniques in Seaborn

    06/10/2024 · Python

  • Getting Started with spaCy

    22/11/2024 · Python

  • Mastering Authentication and User Management in Streamlit

    15/11/2024 · Python

  • Mastering Text Splitting and Chunking in Python with LlamaIndex

    05/11/2024 · Python

Popular category

  • Python
  • Generative AI
  • Machine Learning
  • ReactJS
  • System Design