Wednesday 11 October 2023

Plotting Multiple Graphs in a Single Figure with Python

Subplots are very helpful when you want to display multiple visualizations side by side for comparison in a single figure.

Using 'subplots' method of pyplot, we can create a grid of subplots within a single figure in pyplot.

 

sub_plot_demo.py

import matplotlib.pyplot as plt
import numpy as np

# Create a 2x2 grid of subplots
fig, axs = plt.subplots(nrows=2, ncols=2)
fig.suptitle('Sub plots demo', fontsize=16)

x1 = np.array([2, 3, 5, 7, 11, 13, 17])
y1 = 5 * x1 + 345

x2 = np.array([17, 13, 11, 7, 5, 3, 2])
y2 = 5 * x2 + 345

categories = ['Apple', 'Banana', 'Orange', 'Grapes']
liked_by_count = [120, 45, 32, 87]

# Plot data in each subplot
axs[0, 0].plot(x1, y1)
axs[0, 1].scatter(x2, y2)

axs[1, 0].bar(categories, liked_by_count)
colors = ['r', 'green', '#fedcba', (0, 1, 1), (1, 0, 0, 0.5)]

axs[1, 1].pie(liked_by_count, labels=categories, autopct='%1.1f%%', colors=colors)

# Customize each subplot as needed
axs[0, 0].set_title('Line Plot')
axs[0, 0].set_xlabel('primes')
axs[0, 0].set_ylabel('y=5x+345')

# Customize each subplot as needed
axs[0, 1].set_title('Scatter Plot')
axs[0, 1].set_xlabel('primes')
axs[0, 1].set_ylabel('y=5x+345')

# Add titles, labels, legends, etc., to other subplots similarly

# Adjust layout
plt.tight_layout(rect=[0, 0, 1, 0.95])

# Show the figure
plt.show()

Output



fig, axs = plt.subplots(nrows=2, ncols=2)

Above statement  creates a figure with a 2x2 grid of subplots. The nrows and ncols parameters specify the number of rows and columns in the grid. The fig variable represents the entire figure, while axs is a 2D array of subplot objects.

 

You can access each subplot using indexing, like axs[0, 0], axs[0, 1], and so on. axs[0,0] give you the reference to the plot in first row and first column.

 

plt.tight_layout(rect=[0, 0, 1, 0.95])

Above statement makes sure that the subplots are properly spaced and do not overlap.

 

Previous                                                    Next                                                    Home

No comments:

Post a Comment