Skip to content
    geeksforgeeks
    • Interview Prep
      • DSA
      • Interview Corner
      • Aptitude & Reasoning
      • Practice Coding Problems
      • All Courses
    • Tutorials
      • Python
      • Java
      • ML & Data Science
      • Programming Languages
      • Web Development
      • CS Subjects
      • DevOps
      • Software and Tools
      • School Learning
    • Tracks
      • Languages
        • Python
        • C
        • C++
        • Java
        • Advanced Java
        • SQL
        • JavaScript
        • C#
      • Interview Preparation
        • GfG 160
        • GfG 360
        • System Design
        • Core Subjects
        • Interview Questions
        • Interview Puzzles
        • Aptitude and Reasoning
        • Product Management
        • Computer Organisation and Architecture
      • Data Science
        • Python
        • Data Analytics
        • Complete Data Science
        • Gen AI
        • Agentic AI
      • Dev Skills
        • Full-Stack Web Dev
        • DevOps
        • Software Testing
        • CyberSecurity
        • NextJS
        • Git
      • Tools
        • Computer Fundamentals
        • AI Tools
        • MS Excel & Google Sheets
        • MS Word & Google Docs
      • Maths
        • Maths For Computer Science
        • Engineering Mathematics
        • School Maths
    • Python Tutorial
    • Data Types
    • Interview Questions
    • Examples
    • Quizzes
    • DSA Python
    • Data Science
    • NumPy
    • Pandas
    • Practice
    • Django
    • Flask
    • Projects
    Open In App

    How to Create Subplots in Matplotlib with Python?

    Last Updated : 23 Jul, 2025
    Comments
    Improve
    Suggest changes
    2 Likes
    Like
    Report

    Matplotlib is a widely used data visualization library in Python that provides powerful tools for creating a variety of plots. One of the most useful features of Matplotlib is its ability to create multiple subplots within a single figure using the plt.subplots() method. This allows users to display multiple related visualizations side by side, making data analysis more insightful and effective.

    What are subplots in matplotlib?

    Subplots in Matplotlib refer to multiple plots arranged within a single figure. The matplotlib.pyplot.subplots() method provides an easy way to create a figure with multiple plots. Given the number of rows and columns, it returns a tuple (fig, ax), where fig is the entire figure object and ax is an array of axes objects representing individual subplots.

    Creating subplots using plt.subplots()

    Below are different ways to create subplots in Matplotlib along with examples demonstrating their usage.

    1. Creating a grid of subplots

    The following example creates a 3x3 grid of subplots, iterating over them to plot random lines.

    Python
    import matplotlib.pyplot as plt
    import numpy as np
    
    # Creating subplots
    fig, ax = plt.subplots(3, 3)
    
    # Plot random data in each subplot
    for row in ax:
        for col in row:
            col.plot(np.random.randint(0, 5, 5), np.random.randint(0, 5, 5))
    
    plt.show()
    

    Output

    Explanation: This code creates a 3×3 grid of subplots using Matplotlib. It then iterates over each subplot and plots random integer data using NumPy. Each subplot receives a unique set of random values, generating different plots within the grid.

    2. Creating Subplots for Different Mathematical Functions

    The following example creates a 2x2 grid and plots the sine, cosine, tangent, and sinc functions with different line styles and colors.

    Python
    import matplotlib.pyplot as plt
    import numpy as np
    
    # Creating subplots
    fig, ax = plt.subplots(2, 2)
    
    # Generating data
    x = np.linspace(0, 10, 1000)
    
    # Plot functions with different styles
    ax[0, 0].plot(x, np.sin(x), 'r-.', label='sin(x)')
    ax[0, 1].plot(x, np.cos(x), 'g--', label='cos(x)')
    ax[1, 0].plot(x, np.tan(x), 'y-', label='tan(x)')
    ax[1, 1].plot(x, np.sinc(x), 'c.-', label='sinc(x)')
    
    # Adding legends and showing the figure
    for axes in ax.flat:
        axes.legend()
    plt.tight_layout()
    plt.show()
    

    Output

    Output18

    Explanation: This code creates a 2×2 grid of subplots using Matplotlib and plots different mathematical functions (sin, cos, tan, and sinc) with distinct line styles. It generates x values using NumPy and assigns each function to a specific subplot.

    3. Line plots in subplots

    This example generates sine, cosine, and tangent functions and plots them in separate subplots.

    Python
    import matplotlib.pyplot as plt
    import numpy as np
    
    # Generate random data for subplots
    x = np.linspace(0, 10, 100)
    y1 = np.sin(x)
    y2 = np.cos(x)
    y3 = np.tan(x)
    
    # Create subplots with line plots
    fig, axes = plt.subplots(nrows=1, ncols=3, figsize=(12, 4))
    
    axes[0].plot(x, y1, color='blue', label='sin(x)')
    axes[1].plot(x, y2, color='green', label='cos(x)')
    axes[2].plot(x, y3, color='orange', label='tan(x)')
    
    # Add titles and legends
    axes[0].set_title('Sine Function')
    axes[1].set_title('Cosine Function')
    axes[2].set_title('Tangent Function')
    
    for ax in axes:
        ax.legend()
    
    # Adjust layout for better spacing
    plt.tight_layout()
    
    # Display the figure
    plt.show()
    

    Output:

    Screenshot-2023-12-05-220137

    Explanation: This code creates a single-row, three-column subplot layout using Matplotlib, plotting sin(x), cos(x) and tan(x) with distinct colors. Titles and legends are added for clarity and plt.tight_layout() ensures proper spacing before displaying the figure.

    4. Bar plots in subplots

    This example creates a DataFrame and generates three bar charts to visualize categorical data.

    Python
    import matplotlib.pyplot as plt
    import pandas as pd
    
    # Create a DataFrame with random categorical data
    data = {'Category': ['A', 'B', 'C', 'D'],'Value1': np.random.randint(1, 10, 4),'Value2': np.random.randint(1, 10, 4),'Value3': np.random.randint(1, 10, 4)}
    
    df = pd.DataFrame(data)
    
    # Create subplots with bar plots
    fig, axes = plt.subplots(nrows=1, ncols=3, figsize=(12, 4))
    
    df.plot(kind='bar', x='Category', y='Value1', color='skyblue', ax=axes[0])
    df.plot(kind='bar', x='Category', y='Value2', color='lightgreen', ax=axes[1])
    df.plot(kind='bar', x='Category', y='Value3', color='coral', ax=axes[2])
    
    # Add titles
    axes[0].set_title('Value1 Distribution')
    axes[1].set_title('Value2 Distribution')
    axes[2].set_title('Value3 Distribution')
    
    # Adjust layout for better spacing
    plt.tight_layout()
    
    # Display the figure
    plt.show()
    

    Output:

    Screenshot-2023-12-05-220156

    Explanation: This code creates a DataFrame with random categorical data and a 1×3 subplot layout, plotting bar charts for Value1, Value2 and Value3 with distinct colors, adding titles and adjusting spacing for clarity.

    5. Pie charts in subplots

    The following example generates three pie charts in subplots.

    Python
    import matplotlib.pyplot as plt
    
    # Generate random data for subplots
    labels = ['Category 1', 'Category 2', 'Category 3']
    sizes1 = np.random.randint(1, 10, 3)
    sizes2 = np.random.randint(1, 10, 3)
    sizes3 = np.random.randint(1, 10, 3)
    
    # Create subplots with pie charts
    fig, axes = plt.subplots(nrows=1, ncols=3, figsize=(12, 4))
    
    axes[0].pie(sizes1, labels=labels, autopct='%1.1f%%', colors=['lightcoral', 'lightblue', 'lightgreen'])
    axes[1].pie(sizes2, labels=labels, autopct='%1.1f%%', colors=['gold', 'lightseagreen', 'lightpink'])
    axes[2].pie(sizes3, labels=labels, autopct='%1.1f%%', colors=['lightskyblue', 'lightgreen', 'lightcoral'])
    
    # Add titles
    axes[0].set_title('Pie Chart 1')
    axes[1].set_title('Pie Chart 2')
    axes[2].set_title('Pie Chart 3')
    
    # Adjust layout for better spacing
    plt.tight_layout()
    
    # Display the figure
    plt.show()
    

    Output:

    Screenshot-2023-12-05-220116

    Explanation: This code creates a 1×3 subplot layout using Matplotlib, generating three pie charts with random category sizes and distinct colors. Titles are added for clarity and plt.tight_layout() ensures proper spacing before displaying the figure.

    6. Customizing Subplots using gridspec

    This example demonstrates creating a custom subplot layout using GridSpec in Matplotlib. It arranges four subplots in a non-standard grid, displaying a line plot, scatter plot, bar plot and pie chart.

    Python
    import matplotlib.pyplot as plt
    import matplotlib.gridspec as gridspec
    import numpy as np
    
    # Creating a custom layout with different subplot sizes
    fig = plt.figure(figsize=(12, 6))
    
    # Using gridspec to define the layout
    gs = gridspec.GridSpec(2, 3, width_ratios=[1, 2, 1], height_ratios=[2, 1])
    
    # Creating subplots based on the layout
    ax1 = plt.subplot(gs[0, 0])
    ax2 = plt.subplot(gs[0, 1])
    ax3 = plt.subplot(gs[0, 2])
    ax4 = plt.subplot(gs[1, :])
    
    # Customizing each subplot with different visualizations
    
    # Subplot 1: Line Plot
    x = np.linspace(0, 10, 100)
    y1 = np.sin(x)
    ax1.plot(x, y1, color='blue')
    ax1.set_title('Line Plot - Sine Function')
    
    # Subplot 2: Scatter Plot
    x = np.random.rand(30)
    y2 = 3 * x + np.random.randn(30)
    ax2.scatter(x, y2, color='green')
    ax2.set_title('Scatter Plot')
    
    # Subplot 3: Bar Plot
    categories = ['A', 'B', 'C', 'D']
    values = np.random.randint(1, 10, 4)
    ax3.bar(categories, values, color='orange')
    ax3.set_title('Bar Plot')
    
    # Subplot 4: Pie Chart
    labels = ['Category 1', 'Category 2', 'Category 3']
    sizes = np.random.randint(1, 10, 3)
    ax4.pie(sizes, labels=labels, autopct='%1.1f%%', colors=['lightcoral', 'lightblue', 'lightgreen'])
    ax4.set_title('Pie Chart')
    
    # Adjusting layout for better spacing
    plt.tight_layout()
    
    # Displaying the figure
    plt.show()
    

    Output:

    Screenshot-2023-12-05-220101

    Explanation: This code uses GridSpec to create a custom 2×3 subplot layout with varying sizes. It plots a sine wave (line plot), a scatter plot, a bar chart and a pie chart in separate subplots. Titles are added for clarity and plt.tight_layout() ensures proper spacing before displaying the figure.

    Create Quiz

    D

    deepanshu_rustagi
    Improve

    D

    deepanshu_rustagi
    Improve
    Article Tags :
    • Python
    • Python-matplotlib
    • Data Visualization

    Explore

      Python Fundamentals

      Python Introduction

      2 min read

      Input and Output in Python

      4 min read

      Python Variables

      4 min read

      Python Operators

      4 min read

      Python Keywords

      2 min read

      Python Data Types

      8 min read

      Conditional Statements in Python

      3 min read

      Loops in Python - For, While and Nested Loops

      5 min read

      Python Functions

      5 min read

      Recursion in Python

      4 min read

      Python Lambda Functions

      5 min read

      Python Data Structures

      Python String

      5 min read

      Python Lists

      4 min read

      Python Tuples

      4 min read

      Python Dictionary

      3 min read

      Python Sets

      6 min read

      Python Arrays

      7 min read

      List Comprehension in Python

      4 min read

      Advanced Python

      Python OOP Concepts

      11 min read

      Python Exception Handling

      5 min read

      File Handling in Python

      4 min read

      Python Database Tutorial

      4 min read

      Python MongoDB Tutorial

      3 min read

      Python MySQL

      9 min read

      Python Packages

      10 min read

      Python Modules

      3 min read

      Python DSA Libraries

      15 min read

      List of Python GUI Library and Packages

      3 min read

      Data Science with Python

      NumPy Tutorial - Python Library

      3 min read

      Pandas Tutorial

      4 min read

      Matplotlib Tutorial

      5 min read

      Python Seaborn Tutorial

      3 min read

      StatsModel Library - Tutorial

      3 min read

      Learning Model Building in Scikit-learn

      6 min read

      TensorFlow Tutorial

      2 min read

      PyTorch Tutorial

      6 min read

      Web Development with Python

      Flask Tutorial

      8 min read

      Django Tutorial | Learn Django Framework

      7 min read

      Django ORM - Inserting, Updating & Deleting Data

      4 min read

      Templating With Jinja2 in Flask

      6 min read

      Django Templates

      5 min read

      Build a REST API using Flask - Python

      3 min read

      Building a Simple API with Django REST Framework

      3 min read

      Python Practice

      Python Quiz

      1 min read

      Python Coding Practice

      1 min read

      Python Interview Questions and Answers

      15+ min read
    top_of_element && top_of_screen < bottom_of_element) || (bottom_of_screen > articleRecommendedTop && top_of_screen < articleRecommendedBottom) || (top_of_screen > articleRecommendedBottom)) { if (!isfollowingApiCall) { isfollowingApiCall = true; setTimeout(function(){ if (loginData && loginData.isLoggedIn) { if (loginData.userName !== $('#followAuthor').val()) { is_following(); } else { $('.profileCard-profile-picture').css('background-color', '#E7E7E7'); } } else { $('.follow-btn').removeClass('hideIt'); } }, 3000); } } }); } $(".accordion-header").click(function() { var arrowIcon = $(this).find('.bottom-arrow-icon'); arrowIcon.toggleClass('rotate180'); }); }); window.isReportArticle = false; function report_article(){ if (!loginData || !loginData.isLoggedIn) { const loginModalButton = $('.login-modal-btn') if (loginModalButton.length) { loginModalButton.click(); } return; } if(!window.isReportArticle){ //to add loader $('.report-loader').addClass('spinner'); jQuery('#report_modal_content').load(gfgSiteUrl+'wp-content/themes/iconic-one/report-modal.php', { PRACTICE_API_URL: practiceAPIURL, PRACTICE_URL:practiceURL },function(responseTxt, statusTxt, xhr){ if(statusTxt == "error"){ alert("Error: " + xhr.status + ": " + xhr.statusText); } }); }else{ window.scrollTo({ top: 0, behavior: 'smooth' }); $("#report_modal_content").show(); } } function closeShareModal() { const shareOption = document.querySelector('[data-gfg-action="share-article"]'); shareOption.classList.remove("hover_share_menu"); let shareModal = document.querySelector(".hover__share-modal-container"); shareModal && shareModal.remove(); } function openShareModal() { closeShareModal(); // Remove existing modal if any let shareModal = document.querySelector(".three_dot_dropdown_share"); shareModal.appendChild(Object.assign(document.createElement("div"), { className: "hover__share-modal-container" })); document.querySelector(".hover__share-modal-container").append( Object.assign(document.createElement('div'), { className: "share__modal" }), ); document.querySelector(".share__modal").append(Object.assign(document.createElement('h1'), { className: "share__modal-heading" }, { textContent: "Share to" })); const socialOptions = ["LinkedIn", "WhatsApp","Twitter", "Copy Link"]; socialOptions.forEach((socialOption) => { const socialContainer = Object.assign(document.createElement('div'), { className: "social__container" }); const icon = Object.assign(document.createElement("div"), { className: `share__icon share__${socialOption.split(" ").join("")}-icon` }); const socialText = Object.assign(document.createElement("span"), { className: "share__option-text" }, { textContent: `${socialOption}` }); const shareLink = (socialOption === "Copy Link") ? Object.assign(document.createElement('div'), { role: "button", className: "link-container CopyLink" }) : Object.assign(document.createElement('a'), { className: "link-container" }); if (socialOption === "LinkedIn") { shareLink.setAttribute('href', `https://www.linkedin.com/sharing/share-offsite/?url=${window.location.href}`); shareLink.setAttribute('target', '_blank'); } if (socialOption === "WhatsApp") { shareLink.setAttribute('href', `https://api.whatsapp.com/send?text=${window.location.href}`); shareLink.setAttribute('target', "_blank"); } if (socialOption === "Twitter") { shareLink.setAttribute('href', `https://twitter.com/intent/tweet?url=${window.location.href}`); shareLink.setAttribute('target', "_blank"); } shareLink.append(icon, socialText); socialContainer.append(shareLink); document.querySelector(".share__modal").appendChild(socialContainer); //adding copy url functionality if(socialOption === "Copy Link") { shareLink.addEventListener("click", function() { var tempInput = document.createElement("input"); tempInput.value = window.location.href; document.body.appendChild(tempInput); tempInput.select(); tempInput.setSelectionRange(0, 99999); // For mobile devices document.execCommand('copy'); document.body.removeChild(tempInput); this.querySelector(".share__option-text").textContent = "Copied" }) } }); // document.querySelector(".hover__share-modal-container").addEventListener("mouseover", () => document.querySelector('[data-gfg-action="share-article"]').classList.add("hover_share_menu")); } function toggleLikeElementVisibility(selector, show) { document.querySelector(`.${selector}`).style.display = show ? "block" : "none"; } function closeKebabMenu(){ document.getElementById("myDropdown").classList.toggle("show"); }
geeksforgeeks-footer-logo
Corporate & Communications Address:
A-143, 7th Floor, Sovereign Corporate Tower, Sector- 136, Noida, Uttar Pradesh (201305)
Registered Address:
K 061, Tower K, Gulshan Vivante Apartment, Sector 137, Noida, Gautam Buddh Nagar, Uttar Pradesh, 201305
GFG App on Play Store GFG App on App Store
  • Company
  • About Us
  • Legal
  • Privacy Policy
  • Contact Us
  • Advertise with us
  • GFG Corporate Solution
  • Campus Training Program
  • Explore
  • POTD
  • Job-A-Thon
  • Blogs
  • Nation Skill Up
  • Tutorials
  • Programming Languages
  • DSA
  • Web Technology
  • AI, ML & Data Science
  • DevOps
  • CS Core Subjects
  • Interview Preparation
  • Software and Tools
  • Courses
  • ML and Data Science
  • DSA and Placements
  • Web Development
  • Programming Languages
  • DevOps & Cloud
  • GATE
  • Trending Technologies
  • Videos
  • DSA
  • Python
  • Java
  • C++
  • Web Development
  • Data Science
  • CS Subjects
  • Preparation Corner
  • Interview Corner
  • Aptitude
  • Puzzles
  • GfG 160
  • System Design
@GeeksforGeeks, Sanchhaya Education Private Limited, All rights reserved
Lightbox
Improvement
Suggest Changes
Help us improve. Share your suggestions to enhance the article. Contribute your expertise and make a difference in the GeeksforGeeks portal.
geeksforgeeks-suggest-icon
Create Improvement
Enhance the article with your expertise. Contribute to the GeeksforGeeks community and help create better learning resources for all.
geeksforgeeks-improvement-icon
Suggest Changes
min 4 words, max Words Limit:1000

Thank You!

Your suggestions are valuable to us.
See More

What kind of Experience do you want to share?

Interview Experiences
Admission Experiences
Career Journeys
Work Experiences
Campus Experiences
Competitive Exam Experiences