Adjusting Size of Subplots in Matplotlib
As a data scientist or a data analyst, you’ve likely interacted with Matplotlib, the go-to visualization library for Python. Among the many features it provides are customizable subplots that enable you to compare and contrast different data sets in a single visualization.
Method 1: Specifying One Size for All Subplots
In some cases, you might want all your subplots to have the same dimensions.
To achieve this, you can use the figsize
parameter. This parameter specifies the dimensions of the figure and affects all subplots in the figure horizontally and vertically.
Simply put, the figsize
parameter determines how much space on a screen or page the subplots occupy. Let’s consider an example.
Suppose you want to plot two subplots side-by-side in a figure, each with a size of 5 inches by 3 inches. You can accomplish this by specifying the figsize
parameter as the tuple (10, 3).
To create two subplots with the same size, begin by importing Matplotlib and creating the figure and axes objects:
import matplotlib.pyplot as plt
fig, axs = plt.subplots(1, 2, figsize=(10, 3))
Here, we’ve specified figsize
(10, 3), so the width of the figure is 10 inches, while the height of each subplot is 3 inches. Next, we’ll create a sample plot using the plot
function in the single subplot:
x = [1, 2, 3, 4, 5]
y = [6, 7, 8, 9, 10]
axs[0].plot(x, y)
This code will draw a plot in the first subplot.
To add another subplot, simply use the next index and add your data:
z = [11, 12, 13, 14, 15]
axs[1].plot(z)
Here, we’ve plotted the data z
in the second subplot.
Once you’ve added all your subplots, you can finalize your figure with the tight_layout
method.
This method adjusts the subplots so they don’t overlap each other. To do this, simply add the tight_layout
method at the end of your code:
plt.tight_layout()
Using this method saves you time because you don’t have to specify the individual sizes of each subplot.
Method 2: Specifying Individual Sizes for Subplots
In some cases, you may want to specify individual sizes for your subplots. You may want one to be bigger than the others, or you might have a subplot in which you want to display a large amount of data.
In such cases, it may be optimal to specify individual dimensions for each. To do so, you can use the gridspec_kw
parameter.
This parameter takes as input a dictionary of properties that determine the shape of the subplot grid and the position of each subplot within the grid. For instance, to create an unhomogeneous grid layout, we can specify the width ratios instead of specifying uniform width across subplots.
Here is an example. Let’s say you want to create a figure with one subplot above two subplots at the bottom, where all subplots have different sizes.
The top subplot is two times the size of each of the bottom subplots.
We will start by creating the gridspec object with height_ratios
and width_ratios
as arguments:
import matplotlib.gridspec as gridspec
fig = plt.figure(figsize=(12, 8))
spec = gridspec.GridSpec(ncols=1, nrows=3, height_ratios=[2, 1, 1], width_ratios=[1])
Here, we’ve specified figsize
(12, 8), so the resulting image will be 12 inches wide and 8 inches tall.
Our GridSpec
has a ncols
argument as one (since we’re interested in one column of plots), and three rows we’re interested in. We’ve added 2 to the height_ratios
argument because the top subplot will be twice the size of the bottom subplots.
We’ve specified width_ratios
for flexibility in case we want to add more subplots in the future. Next, we’ll create our subplots by mapping them to the GridSpec
object and subsequently plotting chart data onto each subplot:
# top subplot
ax0 = fig.add_subplot(spec[0, 0])
ax0.plot(x, y)
# bottom left subplot
ax1 = fig.add_subplot(spec[1, 0])
ax1.plot(x, y)
# bottom right subplot
ax2 = fig.add_subplot(spec[2, 0])
ax2.plot(z, y)
Once you’ve added all your subplots, finalize the plot using the tight_layout
method.
Conclusion
Adjusting subplot sizes is a common task when using Matplotlib. Two easy and powerful methods for doing so are specifying individual sizes for each subplot and specifying a universal size for the entire figure.
The use of gridspec_kw
and width_ratios
ensures that you keep full control over the layout aesthetics. We hope this tutorial has empowered you with the knowledge you need to effectively customize your subplot sizes!
Example 2: Specify sizes for Individual Subplots
In the previous section, we discussed how to add a specified size to all subplots in a figure with the figsize
parameter.
In this section, we will discuss how to add specific sizes to each subplot within a figure using the width_ratios
parameter of the grid specifying object. Suppose we have three data sets representing monthly sales for three different products.
One product is a clear winner in terms of sales, while the other two trail behind. For such a scenario, we may want to display the first product’s sales chart to be more prominent than the rest.
Let’s start by creating a 1×3-grid of subplots where the first subplot will be twice as big as the rest of the subplots.
# Import packages
import matplotlib.pyplot as plt
# import numpy as np
# Create sample data
month = np.arange(1, 13)
sales_product_1 = np.random.randint(10, 50, size=(12,))
sales_product_2 = np.random.randint(5, 30, size=(12,))
sales_product_3 = np.random.randint(15, 50, size=(12,))
# Create figure and axes
fig, axs = plt.subplots(nrows=1, ncols=3, figsize=(8, 4), gridspec_kw={'width_ratios': [2, 1, 1]})
# Plot data
axs[0].plot(month, sales_product_1, color='blue')
axs[1].plot(month, sales_product_2, color='green')
axs[2].plot(month, sales_product_3, color='purple')
# Customize subplot titles
axs[0].set(title='Sales for Product 1')
axs[1].set(title='Sales for Product 2')
axs[2].set(title='Sales for Product 3')
We start by creating our sample data consisting of 12 months and sales for three products. We create a figure having a figsize
of (8,4) and add a 1×3-grid of subplots using the gridspec_kw
parameter.
We can see that the width_ratios
of the subplots are specified as [2, 1, 1]
. As a result, the first subplot will have double the width of the remaining subplots.
Once we’ve defined our grid and the subplots, we plot our data on each subplot by calling the necessary plotting functions. Finally, we customize the subplot titles with the set
method.
Additional Resources
Matplotlib Library
Matplotlib is a data visualization library in Python for creating static, animated, and interactive visualizations in Python. It is a python package used by data analysts, data scientists, and machine learning practitioners for creating beautiful and informative visualizations.
It provides easy customization and flexibility in building various types of plots such as line plots, scatter plots, bar plots, histograms, pie charts, and heatmaps. Thus, Matplotlib is an essential library for data science.
Subplot Sizes
Matplotlib’s gridspec
class provides high-level ways to create subplots of different sizes that can all fit together on the same figure. To create subplots with different sizes, we can specify the width_ratios
parameter of the gridspec_kw
parameter to create subplots with different widths.
The width_ratios
parameter takes a list of ratios, with each ratio corresponding to the widths of the subplots created in the same order as the subplots are defined in the plt.subplots()
function. We can also specify the height_ratios
parameter in the gridspec_kw
function to create subplots with different heights.
Additionally, we can adjust the proportion of whitespace between subplots with the wspace
and hspace
parameters. Overall, it is important to have a good understanding of the gridspec_kw
parameter and width_ratios
as they can help us customize our subplots.
Using the methods discussed here enables us to create aesthetically pleasing and informative data visualizations.
Conclusion
In conclusion, Matplotlib is a highly flexible Python library that provides a wide range of visualization tools. Creating subplots of different sizes is a common requirement when presenting complex data in a single visual, and Matplotlib provides us with several ways to achieve this.
In this article, we’ve explored two methods for resizing subplots in Matplotlib: specifying one size for all subplots with figsize
, and specifying individual sizes for subplots using gridspec_kw
and width_ratios
. We hope that this article helped you in making beautiful and informative data visualizations.
In summary, Matplotlib is an essential library for data analysts and scientists, providing various tools to create informative and visually pleasing visualizations. This article explored two methods of resizing subplots in Matplotlib: specifying one size for all subplots using figsize
and specifying individual sizes for subplots using gridspec_kw
and width_ratios
.
These methods help in creating a clear and concise visual representation of complex data, providing an effective means of communicating insights effectively. Overall, the importance of creating well-informed and visually engaging data visualizations cannot be overstated, and we hope this article has given you the tools to do so.