Open In App

How to Create Subplots in Matplotlib with Python?

Last Updated : 06 Dec, 2023
Improve
Improve
Like Article
Like
Save
Share
Report

In this article, we will learn how to add markers to a Graph Plot using Matplotlib with Python. For that one must be familiar with the following concepts: 

  • Matplotlib: Matplotlib may be a multi-platform data visualization library built on NumPy arrays designed to figure with the broader SciPy stack.
  • Matplotlib Subplots: The matplotlib.pyplot.subplots() method provides a way to plot multiple plots on a single figure. Given the number of rows and columns, it returns a tuple (fig, ax), giving a single figure fig with an array of axes ax.

Add Subplots in Matplotlib

Here we are demonstrating different examples of how to Create Subplots in Matplotlib with Python using plt.subplots:

  • Creating Multiple Subplots using plt.subplots
  • Creating Multiple Subplots of Line Plots
  • Creating Multiple Subplots of Bar Plots
  • Creating Multiple Subplots of Pie Charts
  • Creating a custom Multiple Subplots

Creating Multiple Subplots using plt.subplots

The code is a simple example of how to create a Matplotlib subplot figure. Create a matplotlib subplot with a 3×3 grid of subplots, and iterate over the subplots to plot a random line in each subplot.

Python3




# importing packages
import matplotlib.pyplot as plt
import numpy as np
 
# making subplots objects
fig, ax = plt.subplots(3, 3)
 
# draw graph
for i in ax:
    for j in i:
        j.plot(np.random.randint(0, 5, 5), np.random.randint(0, 5, 5))
 
plt.show()


Output :

Example: Create a matplotlib subplot with a 2×2 grid of subplots, plot the sine, cosine, tangent, and sinc functions in different subplots with different line styles and colors, and display the figure

Python3




# importing packages
import matplotlib.pyplot as plt
import numpy as np
 
# making subplots objects
fig, ax = plt.subplots(2, 2)
 
# create data
x = np.linspace(0, 10, 1000)
 
# draw graph
ax[0, 0].plot(x, np.sin(x), 'r-.')
ax[0, 1].plot(x, np.cos(x), 'g--')
ax[1, 0].plot(x, np.tan(x), 'y-')
ax[1, 1].plot(x, np.sinc(x), 'c.-')
 
plt.show()


Output :

Multiple Subplots of Line Plot using Matplotlib

In this example, code generates three different mathematical functions (sine, cosine, and tangent) and plots them using subplots in Matplotlib.

Python3




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

Multiple Subplots of Bar Plot using Matplotlib

In this example, first we will creates a DataFrame with random categorical data and generates three bar charts to visualize the distribution of each data category using subplots in Matplotlib.

Python3




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

Multiple Pie Charts using Matplotlib

In this example, it generates random data for three pie charts and creates subplots to display them using subplots in Matplotlib.

Python3




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

Customizing Multiple Subplots in Matplotlib

In this example, we will see how to create a custom subplot layout using GridSpec in Matplotlib. It creates a figure with four subplots arranged in a non-standard grid and displays different types of visualizationscode like line plots, scatter plots, bar plots, and pie charts in separate subplots using Matplotlib.

Python3




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



Like Article
Suggest improvement
Previous
Next
Share your thoughts in the comments

Similar Reads