Tutorial – Matplotlib Subplots – Shiksha Online
Python’s most popular visualization library – Matplotlib, provides support for many useful data visualization techniques for effective data analysis, one of which is subplots. Let’s take a look at this function in this blog.
When analyzing data using graphical methods, you might want to compare multiple plots simultaneously. Matplotlib’s pyplot module has a convenience function called Matplotlib subplots() that is used to create multiple plots on a figure with a single call.
In this blog, we will be covering the following sections:
- Subplots in Matplotlib
- Installing and Importing Matplotlib
- Creating a Matplotlib Subplot
- Stacking Subplots
- Parameters of Subplots
- Plotting Different Graphs using Subplots
Subplots in Matplotlib
Matplotlib subplots are a grid of smaller axes, with each axis being a plot that is plotted together within a single figure. The subplots() function returns a Figure object and an Axes object.
The Figure object should be considered as your frame, and the Axes object is the canvas on which you’ll be drawing your graphs.
We will take a fun little example that we have also used in our blog Matplotlib Line Plot. You’ve been given the maximum recorded temperature around your city for the last three weeks:
Days | Week 1 | Week 2 | Week 3 |
Monday | 27° | 29° | 29° |
Tuesday | 29° | 30° | 28° |
Wednesday | 32° | 31° | 25° |
Thursday | 33° | 33° | 27° |
Friday | 33° | 34° | 31° |
Saturday | 31° | 34° | 30° |
Sunday | 29° | 31° | 29° |
Best-suited Python for data science courses for you
Learn Python for data science with these high-rated online courses
Installing and Importing Matplotlib
First, let’s install the Matplotlib library in your working environment. Execute the following command in your terminal:
pip install matplotlib
Now let’s import the libraries we’re going to need today:
import pandas as pdimport matplotlib.pyplot as plt%matplotlib inline
In Matplotlib, pyplot is used to create figures and change their characteristics.
The %matplotlib inline function allows for plots to be visible when using Jupyter Notebook
Creating a Matplotlib Subplot
Load the dataset
data = {'Days': ['Monday','Tuesday','Wednesday','Thursday','Friday', 'Saturday', 'Sunday'], 'Week 1': [27,29,32,33,33,31,29], 'Week 2': [29,30,31,33,34,34,31], 'Week 3': [29,28,25,27,31,30,29]}
days = df['Days']week1 = df['Week 1']week2 = df['Week 2']week3 = df['Week 3']
df = pd.DataFrame(data)df
Plotting the data
Let’s plot a figure with only one subplot:
#Plotting for Week 1fig, ax = plt.subplots()ax.plot(days, week1)ax.set_title('A single plot')
Adding elements to the subplot
- Use ax.set_title() for setting a plot title
- Use ax.set_xlabel() and ax.set_ylabel() for labeling x and y-axis respectively
- Use ax.legend() for the observation variables
fig, ax = plt.subplots()ax.plot(days, week1)ax.set_xlabel('Days')ax.set_ylabel('Temperature')ax.set_title('A single plot')ax.legend(['Week 1'])
Stacking Subplots
Stacking vertically in one direction
#Creating three subplotsfig, axs = plt.subplots(3, figsize=(10,5))fig.suptitle('Vertically stacked subplots')axs[0].plot(days, week1)axs[1].plot(days, week2, color = 'orange')axs[2].plot(days, week3, color = 'green')
Note: We have used figsize() to set the dimensions of the figure in inches and enlarge our plots.
Stacking horizontally in one direction
The first two parameters of subplots() defines the numbers of rows and columns respectively:
fig, (ax1, ax2, ax3) = plt.subplots(1, 3, figsize=(20,3))fig.suptitle('Horizontally stacked subplots')ax1.plot(days, week1)ax2.plot(days, week2, color = 'orange')ax3.plot(days, week3, color = 'green')
Stacking in two directions
When stacking in two directions, the returned Axes object is a 2D NumPy array and can be accessed individually by its position. For example, the top-left axes are denoted by axes[0, 0].
Let’s create a subplot of 2 rows x 2 columns and display 4 different plots:
fig, ax = plt.subplots(2, 2, figsize=(15,4))fig.suptitle('Subplots in two directions')ax[0][0].plot(days, week1)ax[0][1].plot(days, week2, color = 'orange')ax[1][0].plot(days, week3, color = 'green')ax[1][1].plot(days, -week3, color = 'green')
Note that the fourth plot is the inverse of the third plot on the y-axis.
Parameters of Matplotlib Subplots
sharex, sharey
- These parameters control sharing of properties among x (sharex) or y (sharey) axes:
fig, (ax1, ax2) = plt.subplots(1, 2, figsize=(12,3), sharey=True)fig.suptitle('Horizontally stacked subplots')ax1.plot(days, week1)ax1.set_title('Week 1')ax2.plot(days, week2, color = 'orange')ax2.set_title('Week 2')
Can you see how the two plots are sharing the y-axis above?
gridspec_kw
This parameter is a dictionary that specifies the geometry of the grid that a subplot will be placed in.
- width_ratio: Array that defines the relative widths of the columns
- height_ratio: Array that defines the relative height of rows
fig, (ax1, ax2) = plt.subplots(2, figsize=(12,3), gridspec_kw={'height_ratios':[2,1]})ax1.plot(days, week1)ax1.set_title('Week 1')ax2.plot(days, week2, color = 'orange')ax2.set_title('Week 2')
But the plot titles are overlapping here? Let’s get that fixed as well.
- hspace: Optional float value of height reserved for space between subplots
- wspace: Optional float value of width reserved for space between subplots
fig, (ax1, ax2) = plt.subplots(2, figsize=(12,3), gridspec_kw={'height_ratios':[2,1], 'hspace':1.2})ax1.plot(days, week1)ax1.set_title('Week 1')ax2.plot(days, week2, color = 'orange')ax2.set_title('Week 2')
- left: Optional float value that defines the position of the left edge of the subplots, as a fraction of the figure width
- right: Optional float value that defines the position of the right edge of the subplots, as a fraction of the figure width
- bottom: Optional float value that defines the position of the bottom edge of the subplots, as a fraction of the figure height
- top: Optional float value that defines the position of the top edge of the subplots, as a fraction of the figure height
fig, (ax1, ax2) = plt.subplots(2, figsize=(12,3), gridspec_kw={'height_ratios':[2,1], 'hspace':1.2, 'left':.07})ax1.plot(days, week1)ax1.set_title('Week 1')ax2.plot(days, week2, color = 'orange')ax2.set_title('Week 2')
You can also use the pyplot.subplots_adjust to adjust the subplot layout parameters.
subplot_kw
This parameter is a dictionary with keywords passed to the add_subplot call used to create each subplot.
- Projection: This parameter specifies the projection type of the subplot:
(None, ‘aitoff’, ‘hammer’, ‘lambert’, ‘mollweide’, ‘polar’, ‘rectilinear’, str)
fig, (ax1, ax2) = plt.subplots(1, 2, subplot_kw=dict(projection='polar'), figsize=(12,7))ax1.plot(days, week1)ax2.plot(days, week2 ** 2) plt.show()
Plotting Different Graphs using Subplots
You can plot different types of graphs with a single call using subplots(). For example, here we have plotted a bar graph, scatter plot, and a line plot for categorical variables:
import matplotlib.pyplot as plt data = {'student 1': 98, 'student 2': 81, 'student 3': 52, 'student 4': 69}names = list(data.keys())marks = list(data.values()) fig, ax = plt.subplots(1, 3, figsize=(15, 3), sharey=True)ax[0].bar(names, marks, facecolor="pink")ax[1].scatter(names, marks, facecolor="green")ax[2].plot(names, marks)fig.suptitle('Categorical Plots')
Endnotes
When trying to extract information from data, the organization of subplots plays a huge role in conveying the story your data is telling. Matplotlib is one of the oldest Python visualization libraries and provides a wide variety of charts and plots for better analysis. Hope this blog on Matplotlib subplots help you understand the concept better.
Top Trending Articles:
Data Analyst Interview Questions | Data Science Interview Questions | Machine Learning Applications | Big Data vs Machine Learning | Data Scientist vs Data Analyst | How to Become a Data Analyst | Data Science vs. Big Data vs. Data Analytics | What is Data Science | What is a Data Scientist | What is Data Analyst
This is a collection of insightful articles from domain experts in the fields of Cloud Computing, DevOps, AWS, Data Science, Machine Learning, AI, and Natural Language Processing. The range of topics caters to upski... Read Full Bio