Open In App

How to Generate Subplots With Python’s Matplotlib

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

Data visualization plays a pivotal role in the process of analyzing and interpreting data. The Matplotlib library in Python offers a robust toolkit for crafting diverse plots and charts. One standout feature is its capability to generate subplots within a single figure, providing a valuable tool for presenting data in a well-organized and structured manner. The use of subplots enables the simultaneous display of multiple plots, contributing to an improved and comprehensive visual representation of the underlying data. This functionality in Matplotlib empowers data analysts and scientists to create informative and visually appealing presentations of their findings.

Generate Subplots With Python’s Matplotlib

There are several ways to generate subplots with Python’s Matplotlib. Here, we will explore some commonly used methods for creating subplots with Python’s Matplotlib.

Generate Multiple Subplots Using Line Plot

In this example the code utilizes Matplotlib to generate a 2×2 grid of line plots, each depicting a mathematical function (sine, cosine, tangent, and exponential) based on example data. The subplots are created and customized using the plt.subplots function, and each subplot is labeled with a title, line color, and a legend. The resulting visualization is displayed using plt.show after adjusting the layout for optimal spacing between subplots.

Python




import matplotlib.pyplot as plt
import numpy as np
 
# Example data
x = np.linspace(0, 10, 100)
y1 = np.sin(x)
y2 = np.cos(x)
y3 = np.tan(x)
y4 = np.exp(-x)
 
# Creating Multiple Subplots for Line Plots
fig, axes = plt.subplots(nrows=2, ncols=2, figsize=(10, 8))
 
# Line Plot 1
axes[0, 0].plot(x, y1, label='sin(x)', color='blue')
axes[0, 0].set_title('Line Plot 1')
axes[0, 0].legend()
 
# Line Plot 2
axes[0, 1].plot(x, y2, label='cos(x)', color='orange')
axes[0, 1].set_title('Line Plot 2')
axes[0, 1].legend()
 
# Line Plot 3
axes[1, 0].plot(x, y3, label='tan(x)', color='green')
axes[1, 0].set_title('Line Plot 3')
axes[1, 0].legend()
 
# Line Plot 4
axes[1, 1].plot(x, y4, label='exp(-x)', color='red')
axes[1, 1].set_title('Line Plot 4')
axes[1, 1].legend()
 
# Adjusting layout
plt.tight_layout()
 
# Show the plots
plt.show()


Output:

Subplots Using Line Plot

Generate Multiple Subplots Using Bar Plot

In this example Python code utilizes Matplotlib to generate a 2×2 grid of subplots, each containing a bar plot. The example data consists of four categories (A, B, C, D) and corresponding values for four sets. The plt.subplots function is employed to create the subplot grid, and individual bar plots are then generated for each set of values. The resulting visualization displays the distribution of values across categories in Bar Plots 1 through 4, with customized colors and titles for each subplot. The layout is adjusted for clarity, and the combined set of subplots is displayed using plt.show().

Python




import matplotlib.pyplot as plt
import numpy as np
 
# Example data for bar plots
categories = ['A', 'B', 'C', 'D']
values1 = [3, 7, 1, 5]
values2 = [5, 2, 8, 4]
values3 = [2, 6, 3, 9]
values4 = [8, 4, 6, 2]
 
# Creating Multiple Subplots for Bar Plots
fig, axes = plt.subplots(nrows=2, ncols=2, figsize=(10, 8))
 
# Bar Plot 1
axes[0, 0].bar(categories, values1, color='blue')
axes[0, 0].set_title('Bar Plot 1')
 
# Bar Plot 2
axes[0, 1].bar(categories, values2, color='orange')
axes[0, 1].set_title('Bar Plot 2')
 
# Bar Plot 3
axes[1, 0].bar(categories, values3, color='green')
axes[1, 0].set_title('Bar Plot 3')
 
# Bar Plot 4
axes[1, 1].bar(categories, values4, color='red')
axes[1, 1].set_title('Bar Plot 4')
 
# Adjusting layout
plt.tight_layout()
 
# Show the plots
plt.show()


Output:

Subplots Using Bar Plot

Generate Multiple Subplots Using Pie Plot

In this example the Python code uses Matplotlib to create a 2×2 grid of pie charts. Each chart represents different categorical data, with specified labels, sizes, and colors. The `plt.subplots` function generates the subplot grid, and each subplot is then filled with a pie chart using the `pie` function. The code adjusts the layout for spacing and displays the resulting visual representation of the pie charts.

Python




import matplotlib.pyplot as plt
 
# Example data for pie charts
labels1 = ['Category 1', 'Category 2', 'Category 3']
sizes1 = [30, 40, 30]
 
labels2 = ['Section A', 'Section B', 'Section C']
sizes2 = [20, 50, 30]
 
labels3 = ['Apple', 'Banana', 'Orange', 'Grapes']
sizes3 = [25, 30, 20, 25]
 
labels4 = ['Red', 'Green', 'Blue']
sizes4 = [40, 30, 30]
 
# Creating Multiple Subplots for Pie Charts
fig, axes = plt.subplots(nrows=2, ncols=2, figsize=(10, 8))
 
# Pie Chart 1
axes[0, 0].pie(sizes1, labels=labels1, autopct='%1.1f%%', colors=['red', 'yellow', 'green'])
axes[0, 0].set_title('Pie Chart 1')
 
# Pie Chart 2
axes[0, 1].pie(sizes2, labels=labels2, autopct='%1.1f%%', colors=['blue', 'orange', 'purple'])
axes[0, 1].set_title('Pie Chart 2')
 
# Pie Chart 3
axes[1, 0].pie(sizes3, labels=labels3, autopct='%1.1f%%', colors=['orange', 'yellow', 'green', 'purple'])
axes[1, 0].set_title('Pie Chart 3')
 
# Pie Chart 4
axes[1, 1].pie(sizes4, labels=labels4, autopct='%1.1f%%', colors=['red', 'green', 'blue'])
axes[1, 1].set_title('Pie Chart 4')
 
# Adjusting layout
plt.tight_layout()
 
# Show the plots
plt.show()


Output:

Subplots Using Pie Plot

Custom layout With a Combination of Plots

In this example Python code employs Matplotlib to generate a figure with a 2×3 grid of subplots. The example data includes sine and cosine line plots, a bar plot, a pie chart, and custom plots of quadratic and exponential functions. Each subplot is customized with titles, labels, and legends. The code showcases how to create a visually diverse layout of subplots in a single figure, demonstrating the versatility of Matplotlib for various plot types.

Python




import matplotlib.pyplot as plt
import numpy as np
 
# Example data
x = np.linspace(0, 10, 100)
y1 = np.sin(x)
y2 = np.cos(x)
 
# Example data for bar plots
categories = ['A', 'B', 'C', 'D']
values = [3, 7, 1, 5]
 
# Example data for pie chart
labels = ['Category 1', 'Category 2', 'Category 3']
sizes = [30, 40, 30]
 
# Example data for custom layout
x_custom = np.linspace(0, 5, 50)
y3 = x_custom**2
y4 = np.exp(x_custom)
 
# Creating Multiple Subplots
fig, axes = plt.subplots(nrows=2, ncols=3, figsize=(15, 8))
 
# Creating Multiple Subplots of Line Plots
axes[0, 0].plot(x, y1, label='sin(x)', color='blue')
axes[0, 0].set_title('Line Plot 1')
axes[0, 0].legend()
 
axes[0, 1].plot(x, y2, label='cos(x)', color='orange')
axes[0, 1].set_title('Line Plot 2')
axes[0, 1].legend()
 
# Creating Multiple Subplots of Bar Plots
axes[0, 2].bar(categories, values, color='green')
axes[0, 2].set_title('Bar Plot')
 
# Creating Multiple Subplots of Pie Charts
axes[1, 0].pie(sizes, labels=labels, autopct='%1.1f%%', colors=['red', 'yellow', 'green'])
axes[1, 0].set_title('Pie Chart')
 
# Creating a custom Multiple Subplots
axes[1, 1].plot(x_custom, y3, label='x^2', color='purple')
axes[1, 1].set_title('Custom Plot 1')
axes[1, 1].legend()
 
axes[1, 2].plot(x_custom, y4, label='e^x', color='brown')
axes[1, 2].set_title('Custom Plot 2')
axes[1, 2].legend()
 
# Adjusting layout
plt.tight_layout()
 
# Show the plots
plt.show()


Output:

Combination of Plots

Conclusion

In conclusion, mastering the art of generating subplots with Python’s Matplotlib opens up a realm of possibilities for creating visually appealing and informative data visualizations. The flexibility provided by Matplotlib’s subplots allows for the simultaneous presentation of multiple plots within a single figure, enhancing the clarity and coherence of the displayed information. Whether organizing line plots, bar charts, pie charts, or custom plots, understanding the concepts of subplot grids, axes objects, and the `subplots` function proves essential. The ability to seamlessly arrange and customize subplots empowers data analysts and scientists to convey complex datasets in a structured and comprehensible manner.



Like Article
Suggest improvement
Share your thoughts in the comments

Similar Reads