Matplotlib is a powerful library in Python for creating visualizations. One of its features is the ability to create multiple plots in a single figure, allowing us to compare and analyze data more effectively.
In this blog post, we will explore how to create multiple plots using Matplotlib in Python. Let’s dive in!
Importing the required libraries
Before we start creating multiple plots, we need to import the necessary libraries. In this case, we need to import the pyplot
sub-module from matplotlib
.
import matplotlib.pyplot as plt
Creating a figure and multiple subplots
To create multiple subplots, we first need to create a figure object. Then, we can create subplots using the subplots()
function. The subplots()
function takes in two arguments: the number of rows and columns of subplots.
fig, axes = plt.subplots(nrows=2, ncols=2)
In the above code, we create a figure with 2 rows and 2 columns, which gives us a total of 4 subplots.
Plotting data on subplots
Once we have created the subplots, we can plot our data on them. We can access each subplot using the axes
object, which is a 2-dimensional array.
axes[0, 0].plot(x1, y1, 'r--')
axes[0, 0].set_title('Plot 1')
axes[0, 1].scatter(x2, y2)
axes[0, 1].set_title('Plot 2')
axes[1, 0].bar(x3, y3)
axes[1, 0].set_title('Plot 3')
axes[1, 1].hist(x4, bins=10)
axes[1, 1].set_title('Plot 4')
plt.tight_layout() # Optional, to improve the spacing between subplots
In the above code, we plot different types of data on each subplot - a line plot, a scatter plot, a bar plot, and a histogram. We also set titles for each plot.
Displaying the figure
Finally, we can display the figure with our multiple subplots by calling the show()
function.
plt.show()
The show()
function opens a window with our figure, displaying all the subplots.
That’s it! We have successfully created multiple plots using Matplotlib in Python. This technique is useful when we want to compare different aspects of the data or visualize multiple datasets together.
I hope this blog post was helpful in understanding how to create multiple plots in Matplotlib. Happy plotting!