02-09-2020, 03:51 AM
Matplotlib Subplots – A Helpful Illustrated Guide
Too much stuff happening in a single plot? No problem—use multiple subplots!
This in-depth tutorial shows you everything you need to know to get started with Matplotlib’s function.
If you want, just hit “play” and watch the explainer video. I’ll then guide you through the tutorial:
Let’s start with the short answer on how to use it—you’ll learn all the details later!
The function creates a and a Numpy array of / objects which you store in and respectively.
Specify the number of rows and columns you want with the and arguments.
This creates a and in a 3×1 grid. The Numpy array has shape the same shape as the grid, in this case (it’s a 1D array since one of or is 1). Access each using Numpy slice notation and call the method to plot a line graph.
Once all have been plotted, call to ensure no parts of the plots overlap. Finally, call to display your plot.
![[Image: img0.png]](https://raw.githubusercontent.com/theadammurphy/matplotlib_articles/master/subplots/final_html/img/img0.png)
Matplotlib Figures and Axes
Up until now, you have probably made all your plots with the functions in i.e. all the functions that start with .
These work nicely when you draw one plot at a time. But to draw multiple plots on one, you need to learn the underlying classes in matplotlib.
Let’s look at an image that explains the main classes from the AnatomyOfMatplotlib tutorial:
![[Image: img1.png]](https://raw.githubusercontent.com/theadammurphy/matplotlib_articles/master/subplots/final_html/img/img1.png)
To quote AnatomyOfMatplotlib:
The typical variable names for each object are:
The word refers to the area you plot on and is synonymous with . However, you can have multiple () on a . In speech and writing use the same word for the singular and plural form. In your code, you should make a distinction between each – you plot on a singular but will store all the in a Numpy array.
An refers to the or – the part that gets ticks and labels.
The module implicitly works on one and one at a time. When we work with , we work with multiple on one . So, it makes sense to plot with respect to the and it is much easier to keep track of everything.
The main differences between using methods and are:
Once you get the hang of this, you won’t want to go back to using. It’s much easier to create interesting and engaging plots this way. In fact, this is why most StackOverflow answers are written with this syntax.
All of the functions in have a corresponding method that you can call on objects, so you don’t have to learn any new functions.
Let’s get to it.
Matplotlib Subplots Example
The function creates a and a Numpy array of / objects which we store in and respectively.
Specify the number of rows and columns you want with the and arguments.
This creates a and in a 3×1 grid. The Numpy array is the same shape as the grid, in this case . Access each using Numpy slice notation and call the method to plot a line graph.
Once all have been plotted, call to ensure no parts of the plots overlap. Finally, call to display your plot.
![[Image: img2.png]](https://raw.githubusercontent.com/theadammurphy/matplotlib_articles/master/subplots/final_html/img/img2.png)
The most important arguments for are similar to the matplotlib subplot function but can be specified with keywords. Plus, there are more powerful ones which we will discuss later.
To create a with one object, call it without any arguments
Note: this is implicitly called whenever you use the module. All ‘normal’ plots contain one and one .
In advanced blog posts and StackOverflow answers, you will see a line similar to this at the top of the code. It is much more Pythonic to create your plots with respect to a and .
To create a of subplots, specify and – the number of rows and columns respectively
The variable is a numpy array with shape . Note that it is in the plural form to indicate it contains more than one object. Another common name is . Choose whichever you prefer. If you call without an argument name the variable as there is only one object returned.
I will select each object with slicing notation and plot using the appropriate methods. Since I am using Numpy slicing, the index of the first is 0, not 1.
![[Image: img3.png]](https://raw.githubusercontent.com/theadammurphy/matplotlib_articles/master/subplots/final_html/img/img3.png)
First I import the necessary modules, then create the and objects using . The object is a Numpy array with shape and I access each subplot via Numpy slicing before doing a line plot of the data. Then, I call to ensure the axis labels don’t overlap with the plots themselves. Finally, I call as you do at the end of all matplotlib plots.
Matplotlib Subplots Title
To add an overall title to the, use .
To add a title to each, you have two methods to choose from:
In general, you can set anything you want on an using either of these methods. I recommend using because you can pass any setter function to it as a keyword argument. This is faster to type, takes up fewer lines of code and is easier to read.
Let’s set the title, xlabel and ylabel for two using both methods for comparison
![[Image: img4.png]](https://raw.githubusercontent.com/theadammurphy/matplotlib_articles/master/subplots/final_html/img/img4.png)
Clearly using is the better choice.
Note that I unpacked the object into individual variables on the first line. You can do this instead of Numpy slicing if you prefer. It is easy to do with 1D arrays. Once you create grids with multiple rows and columns, it’s easier to read if you don’t unpack them.
Matplotlib Subplots Share X Axis
To share the x axis for subplots in matplotlib, set in your call.
![[Image: img5.png]](https://raw.githubusercontent.com/theadammurphy/matplotlib_articles/master/subplots/final_html/img/img5.png)
Here I created 3 line plots that show the linear, square root and exponential of the numbers 0-5.
As I used the same numbers, it makes sense to share the x-axis.
![[Image: img6.png]](https://raw.githubusercontent.com/theadammurphy/matplotlib_articles/master/subplots/final_html/img/img6.png)
Here I wrote the same code but set (the default behavior). Now there are unnecessary axis labels on the top 2 plots.
You can also share the y axis for plots by setting in your call.
Matplotlib Subplots Legend
To add a legend to each, you must
Let’s look at the same plot as above but add a legend to each.
![[Image: img7.png]](https://raw.githubusercontent.com/theadammurphy/matplotlib_articles/master/subplots/final_html/img/img7.png)
The legend now tells you which function has been applied to the data. I used a for loop to call on each of the . I could have done it manually instead by writing:
Instead of having 3 legends, let’s just add one legend to the that describes each line. Note that you need to change the color of each line, otherwise the legend will show three blue lines.
The matplotlib legend function takes 2 arguments
Get the by storing the output of you calls in a list. You need to create the list of yourself. Then call on the you want to add the legend to.
![[Image: img8.png]](https://raw.githubusercontent.com/theadammurphy/matplotlib_articles/master/subplots/final_html/img/img8.png)
First I generated the data and a 3×1 grid. Then I made three calls and applied different functions to the data.
Note that returns a of objects. You have to pass these objects to and so need to unpack them first.
Standard unpacking syntax in Python is:
However, each call returns a list of length 1. To unpack these lists, write
If you just wrote then would be a list and not the object inside the list.
After the calls, I created 2 lists of and which I passed to to draw it on the first plot.
![[Image: img9.png]](https://raw.githubusercontent.com/theadammurphy/matplotlib_articles/master/subplots/final_html/img/img9.png)
In the above plot, I changed the call to to plot it on the second (middle) .
Matplotlib Subplots Size
You have total control over the size of subplots in matplotlib.
You can either change the size of the entire or the size of the themselves.
First, let’s look at changing the.
Matplotlib Figure Size
If you are happy with the size of your subplots but you want the final image to be larger/smaller, change the.
If you’ve read my article on the matplotlib subplot function, you know to use the function to to change the . Fortunately, any arguments passed to are also passed to . So, you don’t have to add any extra lines of code, just keyword arguments.
Let’s change the size of the.
![[Image: img10.png]](https://raw.githubusercontent.com/theadammurphy/matplotlib_articles/master/subplots/final_html/img/img10.png)
I created a 2×1 plot and set the size with the argument. It accepts a tuple of 2 numbers – the of the image in inches.
So, I created a plot 3 inches wide and 6 inches long –.
![[Image: img11.png]](https://raw.githubusercontent.com/theadammurphy/matplotlib_articles/master/subplots/final_html/img/img11.png)
You can set a more general size with the matplotlib figaspect function. It lets you set the aspect ratio (height/width) of the .
Above, I created a twice as long as it is wide by setting .
Note: Remember the aspect ratio (height/width) formula by recalling that comes first in the alphabet before .
Matplotlib Subplots Different Sizes
If you have used before (I’ve written a whole tutorial on this too), you’ll know that the grids you create are limited. Each must be part of a regular grid i.e. of the form for some integer . If you create a 2×1 grid, you have 2 rows and each row takes up 1/2 of the space. If you create a 3×2 grid, you have 6 subplots and each takes up 1/6 of the space.
Using you can create a 2×1 plot with 2 rows that take up any fraction of space you want.
Let’s make a 2×1 plot where the top row takes up 1/3 of the space and the bottom takes up 2/3.
You do this by specifying the argument and passing a dictionaryof values. The main arguments we are interested in are and . They accept lists that specify the width ratios of columns and height ratios of the rows. In this example the top row is of the and the bottom is . Thus the height ratio is or as a list.
![[Image: img12.png]](https://raw.githubusercontent.com/theadammurphy/matplotlib_articles/master/subplots/final_html/img/img12.png)
The only difference between this and a regular 2×1 call is the argument. It accepts a dictionary of values. These are passed to the matplotlib GridSpec constructor (the underlying class that creates the grid).
Let’s create a 2×2 plot with the same height ratios but let’s make the left hand column take up 3/4 of the space.
![[Image: img13.png]](https://raw.githubusercontent.com/theadammurphy/matplotlib_articles/master/subplots/final_html/img/img13.png)
Everything is the same as the previous plot but now we have a 2×2 grid and have specified. Since the left column takes up of the space and the right takes up the ratios are .
Matplotlib Subplots Size
In the previous examples, there were white lines that cross over each other to separate the into a clear grid. But sometimes you will not have that to guide you. To create a more complex plot, you have to manually add to the grid.
You could do this using the function. But since we are focusing on and notation in this article, I’ll show you how to do it another way.
You need to use the method and it has the same notation as . Since it is a method, you first need to create one with the function.
The hardest part of creating a with different sized in matplotlib is figuring out what fraction of space each takes up.
So, it’s a good idea to know what you are aiming for before you start. You could sketch it on paper or draw shapes in PowerPoint. Once you’ve done this, everything else is much easier.
I’m going to create this shape.
![[Image: img14.png]](https://raw.githubusercontent.com/theadammurphy/matplotlib_articles/master/subplots/final_html/img/img14.png)
I’ve labeled the fraction each takes up as we need this for our calls.
I’ll create the biggest first and the others in descending order.
![[Image: img15.png]](https://raw.githubusercontent.com/theadammurphy/matplotlib_articles/master/subplots/final_html/img/img15.png)
The right hand side is half of the plot. It is one of two plots on a with 1 row and 2 columns. To select it with , you need to set .
Remember that indexing starts from 1 for the functions and .
In the image, the blue numbers are the index values each has.
As you are working with objects, you need to store the result of so that you can plot on it afterwards.
![[Image: img16.png]](https://raw.githubusercontent.com/theadammurphy/matplotlib_articles/master/subplots/final_html/img/img16.png)
Now, select the bottom left in a a 2×2 grid i.e.
![[Image: img17.png]](https://raw.githubusercontent.com/theadammurphy/matplotlib_articles/master/subplots/final_html/img/img17.png)
Lastly, select the top two on the left hand side of a 4×2 grid i.e. and .
When you put this altogether you get
![[Image: img18.png]](https://raw.githubusercontent.com/theadammurphy/matplotlib_articles/master/subplots/final_html/img/img18.png)
Perfect! Breaking the down into their individual parts and knowing the shape you want, makes everything easier.
Now, let’s do something you can’t do with. Let’s have 2 plots on the left hand side with the bottom plot twice the height as the top plot.
![[Image: img19.png]](https://raw.githubusercontent.com/theadammurphy/matplotlib_articles/master/subplots/final_html/img/img19.png)
Like with the above plot, the right hand side is half of a plot with 1 row and 2 columns. It is.
So, the first two lines are the same as the previous plot
![[Image: img20.png]](https://raw.githubusercontent.com/theadammurphy/matplotlib_articles/master/subplots/final_html/img/img20.png)
The top left takes up of the space of the left-hand half of the plot. Thus, it takes up of the total plot. So, it is of a 3×2 grid.
![[Image: img21.png]](https://raw.githubusercontent.com/theadammurphy/matplotlib_articles/master/subplots/final_html/img/img21.png)
The final subplot takes up 2/3 of the remaining space i.e. and of a 3×2 grid. But you can’t add both of these indexes as that would add two to the . You need a way to add one that spans two rows.
You need the matplotlib subplot2grid function –. It returns an object and adds it to the current .
Here are the most important arguments:
![[Image: img22.png]](https://raw.githubusercontent.com/theadammurphy/matplotlib_articles/master/subplots/final_html/img/img22.png)
From those definitions, you need to select the middle left and set so that it spans down 2 rows.
![[Image: img23.png]](https://raw.githubusercontent.com/theadammurphy/matplotlib_articles/master/subplots/final_html/img/img23.png)
Thus, the arguments you need for are:
This gives
Sidenote: why matplotlib chose 0-based indexing for when everything else uses 1-based indexing is a mystery to me. One way to remember it is that is similar to . This is like slicing Numpy arrays which use 0-indexing. Also, if you use , you will often use Numpy slicing to choose the number of rows and columns that span.
Putting this together, you get
![[Image: img24.png]](https://raw.githubusercontent.com/theadammurphy/matplotlib_articles/master/subplots/final_html/img/img24.png)
Matplotlib Subplots_Adjust
If you aren’t happy with the spacing between plots that provides, manually adjust the spacing with the matplotlib subplots_adjust function.
It takes 6 optional, self explanatory arguments. Each is a float in the range [0.0, 1.0] and is a fraction of the font size:
Let’s compare with .
![[Image: img25.png]](https://raw.githubusercontent.com/theadammurphy/matplotlib_articles/master/subplots/final_html/img/img25.png)
Here is a 2×2 grid with. I’ve set and to to remove unnecessary axis labels.
![[Image: img26.png]](https://raw.githubusercontent.com/theadammurphy/matplotlib_articles/master/subplots/final_html/img/img26.png)
Now I’ve decreased the height and width between to and there is hardly any space between them.
To avoid loads of similar examples, I recommend you play around with the arguments to get a feel for how this function works.
Matplotlib Subplots Colorbar
Adding a colorbar to each is similar to adding a legend. You store the call in a variable and pass it to .
Colorbars are methods since they are placed on the itself and not the . Yet, they do take up space from the they are placed on.
Let’s look at an example.
![[Image: img27.png]](https://raw.githubusercontent.com/theadammurphy/matplotlib_articles/master/subplots/final_html/img/img27.png)
First, I generated two 10×10 arrays of random numbers in the range [0.0, 1.0] using the function. Then I initialized the 1×2 grid with .
The keyword argument achieves a similar result to calling . However, only checks for tick labels, axis labels and titles. Thus, it ignores colorbars and legends and often produces bad looking plots. Fortunately, takes colorbars and legends into account. Thus, it should be your go-to when automatically adjusting these types of plots.
Finally, I set to ensure the plots aren’t too squashed together.
After that, I plotted the first heatmap, colored it blue and saved it in the variable. I passed that to and placed it on the first column – with the keyword argument. It’s a similar story for the second heatmap.
The more you have, the fancier you can be with placing colorbars in matplotlib. Now, let’s look at a 2×2 example with 4 but only 2 colorbars.
![[Image: img28.png]](https://raw.githubusercontent.com/theadammurphy/matplotlib_articles/master/subplots/final_html/img/img28.png)
If you pass a list of to , matplotlib places the colorbar along those . Moreover, you can specify where the colorbar is with the keyword argument. It accepts the strings , , , or .
The code is similar to the 1×2 plot I made above. First, I set the seed to 1 so that you can reproduce the results – you will soon plot this again with the colorbars in different places.
I used a list comprehension to generate 4 samples of the same dataset. Then I created a 2×2 grid with and set to ensure nothing overlaps.
Then I made the plots for the first column – and – and saved their output. I passed one of them to . It doesn’t matter which one of or I pass since they are just different samples of the same dataset. I set using Numpy slicing notation, that is all rows and the first column .
It’s a similar process for the second column but I added 1 to and to give a range of numbers in [1.0, 2.0] instead. Lastly, I set to make the colorbar half its default size.
Now, let’s plot the same data with the same colors on each row rather than on each column.
![[Image: img29.png]](https://raw.githubusercontent.com/theadammurphy/matplotlib_articles/master/subplots/final_html/img/img29.png)
This code is similar to the one above but the plots of the same color are on the same row rather than the same column. I also shrank the colorbars to 80% of their default size by setting.
Finally, let’s set the blue colorbar to be on the bottom of the heatmaps.
![[Image: img30.png]](https://raw.githubusercontent.com/theadammurphy/matplotlib_articles/master/subplots/final_html/img/img30.png)
You can change the location of the colorbars with the keyword argument in . The only difference between this plot and the one above is this line
If you increase the argument, this plot will look much better – at the moment it’s quite cramped.
I recommend you play around with matplotlib colorbar placement. You have total control over how many colorbars you put on the, their location and how many rows and columns they span. These are some basic ideas but check out the docs to see more examples of how you can place colorbars in matplotlib.
Matplotlib Subplot Grid
I’ve spoken about a few times in this article. It is the underlying class that specifies the geometry of the grid that a subplot can be placed in.
You can create any shape you want using and . But some of the more complex shapes are easier to create using . If you want to become a total pro with matplotlib, check out the docs and look out for my article discussing it in future.
Summary
You can now create any shape you can imagine in matplotlib. Congratulations! This is a huge achievement. Don’t worry if you didn’t fully understand everything the first time around. I recommend you bookmark this article and revisit it from time to time.
You’ve learned the underlying classes in matplotlib:, , and and how to plot with respect to them. You can write shorter, more readable code by using these methods and to add titles, xlabels and many other things to each . You can create more professional looking plots by sharing the x-axis and y-axis and add legends anywhere you like.
You can create of any size that include of any size – you’re no longer restricted to those that take up th of the plot. You know that to make the best plots, you should plan ahead and figure out the shape you are aiming for.
You know when to use (ticks, labels and titles) and (legends and colorbars) and how to manually adjust spacing between plots with .
Finally, you can add colorbars to as many as you want and place them wherever you’d like.
You’ve done everything now. All that is left is to practice these plots so that you can quickly create amazing plots whenever you want.
Where To Go From Here?
Do you wish you could be a programmer full-time but don’t know how to start?
Check out my pure value-packed webinar where I teach you to become a Python freelancer in 60 days or your money back!
https://tinyurl.com/become-a-python-freelancer
It doesn’t matter if you’re a Python novice or Python pro. If you are not making six figures/year with Python right now, you will learn something from this webinar.
These are proven, no-BS methods that get you results fast.
This webinar won’t be online forever. Click the link below before the seats fill up and learn how to become a Python freelancer, guaranteed.
https://tinyurl.com/become-a-python-freelancer
Too much stuff happening in a single plot? No problem—use multiple subplots!
This in-depth tutorial shows you everything you need to know to get started with Matplotlib’s
Code:
subplots()If you want, just hit “play” and watch the explainer video. I’ll then guide you through the tutorial:
Let’s start with the short answer on how to use it—you’ll learn all the details later!
The
Code:
plt.subplots()Code:
FigureCode:
SubplotCode:
AxesCode:
figCode:
axesSpecify the number of rows and columns you want with the
Code:
nrowsCode:
ncolsCode:
fig, axes = plt.subplots(nrows=3, ncols=1)This creates a
Code:
FigureCode:
SubplotsCode:
axesCode:
(nrows, ncols)Code:
(3,)Code:
nrowsCode:
ncolsCode:
SubplotCode:
plot()Once all
Code:
SubplotsCode:
plt.tight_layout()Code:
plt.show()Code:
# Import necessary modules and (optionally) set Seaborn style
import matplotlib.pyplot as plt
import seaborn as sns; sns.set()
import numpy as np # Generate data to plot
linear = [x for x in range(5)]
square = [x**2 for x in range(5)]
cube = [x**3 for x in range(5)] # Generate Figure object and Axes object with shape 3x1
fig, axes = plt.subplots(nrows=3, ncols=1) # Access first Subplot and plot linear numbers
axes[0].plot(linear) # Access second Subplot and plot square numbers
axes[1].plot(square) # Access third Subplot and plot cube numbers
axes[2].plot(cube) plt.tight_layout()
plt.show()![[Image: img0.png]](https://raw.githubusercontent.com/theadammurphy/matplotlib_articles/master/subplots/final_html/img/img0.png)
Matplotlib Figures and Axes
Up until now, you have probably made all your plots with the functions in
Code:
matplotlib.pyplotCode:
plt.These work nicely when you draw one plot at a time. But to draw multiple plots on one
Code:
FigureLet’s look at an image that explains the main classes from the AnatomyOfMatplotlib tutorial:
![[Image: img1.png]](https://raw.githubusercontent.com/theadammurphy/matplotlib_articles/master/subplots/final_html/img/img1.png)
To quote AnatomyOfMatplotlib:
Quote:Theis the top-level container in this hierarchy. It is the overall window/page that everything is drawn on. You can have multiple independent figures andCode:Figures can contain multipleCode:Figure.Code:Axes
Most plotting ocurs on an. The axes is effectively the area that we plot data on and any ticks/labels/etc associated with it. Usually we’ll set up an Axes with a call toCode:Axes(which places Axes on a regular grid), so in most cases,Code:subplotsandCode:Axesare synonymous.Code:Subplot
Eachhas anCode:Axesand aCode:XAxis. These contain the ticks, tick locations, labels, etc. In this tutorial, we’ll mostly control ticks, tick labels, and data limits through other mechanisms, so we won’t touch the individualCode:YAxispart of things all that much. However, it is worth mentioning here to explain where the termCode:Axiscomes from.Code:Axes
The typical variable names for each object are:
- –Code:
FigureorCode:fig,Code:f
- (plural) –Code:
AxesorCode:axes,Code:axs
- (singular) –Code:
AxesorCode:axCode:a
The word
Code:
AxesCode:
SubplotCode:
AxesCode:
SubplotsCode:
FigureCode:
AxesCode:
AxesAn
Code:
AxisCode:
XAxisCode:
YAxisThe
Code:
pyplotCode:
FigureCode:
AxesCode:
SubplotsCode:
AxesCode:
FigureCode:
AxesThe main differences between using
Code:
AxesCode:
pyplot- Always create a andCode:
Figureobjects on the first lineCode:Axes
- To plot, write instead ofCode:
ax.plot().Code:plt.plot()
Once you get the hang of this, you won’t want to go back to using
Code:
pyplotAll of the functions in
Code:
pyplotCode:
AxesLet’s get to it.
Matplotlib Subplots Example
The
Code:
plt.subplots()Code:
FigureCode:
SubplotsCode:
AxesCode:
figCode:
axesSpecify the number of rows and columns you want with the
Code:
nrowsCode:
ncolsCode:
fig, axes = plt.subplots(nrows=3, ncols=1)This creates a
Code:
FigureCode:
SubplotsCode:
axesCode:
(3,)Code:
SubplotCode:
plot()Once all
Code:
SubplotsCode:
plt.tight_layout()Code:
plt.show()Code:
fig, axes = plt.subplots(nrows=2, ncols=2) plt.tight_layout()
plt.show()![[Image: img2.png]](https://raw.githubusercontent.com/theadammurphy/matplotlib_articles/master/subplots/final_html/img/img2.png)
The most important arguments for
Code:
plt.subplots()To create a
Code:
FigureCode:
AxesCode:
fig, ax = plt.subplots()Note: this is implicitly called whenever you use the
Code:
pyplotCode:
FigureCode:
AxesIn advanced blog posts and StackOverflow answers, you will see a line similar to this at the top of the code. It is much more Pythonic to create your plots with respect to a
Code:
FigureCode:
AxesTo create a
Code:
GridCode:
nrowsCode:
ncolsCode:
fig, axes = plt.subplots(nrows=2, ncols=2)The variable
Code:
axesCode:
(nrows, ncols)Code:
AxesCode:
axsCode:
plt.subplots()Code:
axCode:
AxesI will select each
Code:
AxesCode:
AxesCode:
# Create Figure and 2x2 gris of Axes objects
fig, axes = plt.subplots(nrows=2, ncols=2) # Generate data to plot. data = np.array([1, 2, 3, 4, 5]) # Access Axes object with Numpy slicing then plot different distributions
axes[0, 0].plot(data)
axes[0, 1].plot(data**2)
axes[1, 0].plot(data**3)
axes[1, 1].plot(np.log(data)) plt.tight_layout()
plt.show()![[Image: img3.png]](https://raw.githubusercontent.com/theadammurphy/matplotlib_articles/master/subplots/final_html/img/img3.png)
First I import the necessary modules, then create the
Code:
FigureCode:
AxesCode:
plt.subplots()Code:
AxesCode:
(2, 2)Code:
plt.tight_layout()Code:
plt.show()Matplotlib Subplots Title
To add an overall title to the
Code:
FigureCode:
plt.suptitle()To add a title to each
Code:
Axes- Code:
ax.set_title('bar')
- Code:
ax.set(title='bar')
In general, you can set anything you want on an
Code:
AxesCode:
ax.set()Let’s set the title, xlabel and ylabel for two
Code:
SubplotsCode:
# Unpack the Axes object in one line instead of using slice notation
fig, (ax1, ax2) = plt.subplots(nrows=1, ncols=2) # First plot - 3 lines
ax1.set_title('many')
ax1.set_xlabel('lines')
ax1.set_ylabel('of code') # Second plot - 1 line
ax2.set(title='one', xlabel='line', ylabel='of code') # Overall title
plt.suptitle('My Lovely Plot')
plt.tight_layout()
plt.show()![[Image: img4.png]](https://raw.githubusercontent.com/theadammurphy/matplotlib_articles/master/subplots/final_html/img/img4.png)
Clearly using
Code:
ax.set()Note that I unpacked the
Code:
AxesMatplotlib Subplots Share X Axis
To share the x axis for subplots in matplotlib, set
Code:
sharex=TrueCode:
plt.subplots()Code:
# Generate data
data = [0, 1, 2, 3, 4, 5] # 3x1 grid that shares the x axis
fig, axes = plt.subplots(nrows=3, ncols=1, sharex=True) # 3 different plots
axes[0].plot(data)
axes[1].plot(np.sqrt(data))
axes[2].plot(np.exp(data)) plt.tight_layout()
plt.show()![[Image: img5.png]](https://raw.githubusercontent.com/theadammurphy/matplotlib_articles/master/subplots/final_html/img/img5.png)
Here I created 3 line plots that show the linear, square root and exponential of the numbers 0-5.
As I used the same numbers, it makes sense to share the x-axis.
![[Image: img6.png]](https://raw.githubusercontent.com/theadammurphy/matplotlib_articles/master/subplots/final_html/img/img6.png)
Here I wrote the same code but set
Code:
sharex=FalseYou can also share the y axis for plots by setting
Code:
sharey=TrueCode:
plt.subplots()Matplotlib Subplots Legend
To add a legend to each
Code:
Axes- Label it using the keywordCode:
label
- Call on theCode:
ax.legend()you want the legend to appearCode:Axes
Let’s look at the same plot as above but add a legend to each
Code:
AxesCode:
# Generate data, 3x1 plot with shared XAxis
data = [0, 1, 2, 3, 4, 5]
fig, axes = plt.subplots(nrows=3, ncols=1, sharex=True) # Plot the distributions and label each Axes
axes[0].plot(data, label='Linear')
axes[1].plot(np.sqrt(data), label='Square Root')
axes[2].plot(np.exp(data), label='Exponential') # Add a legend to each Axes with default values
for ax in axes: ax.legend() plt.tight_layout()
plt.show()![[Image: img7.png]](https://raw.githubusercontent.com/theadammurphy/matplotlib_articles/master/subplots/final_html/img/img7.png)
The legend now tells you which function has been applied to the data. I used a for loop to call
Code:
ax.legend()Code:
AxesCode:
axes[0].legend()
axes[1].legend()
axes[2].legend()Instead of having 3 legends, let’s just add one legend to the
Code:
FigureThe matplotlib legend function takes 2 arguments
Code:
ax.legend(handles, labels)- – the lines/plots you want to add to the legend (list)Code:
handles
- – the labels you want to give each line (list)Code:
labels
Get the
Code:
handlesCode:
ax.plot()Code:
labelsCode:
legend()Code:
AxesCode:
# Generate data and 3x1 grid with a shared x axis
data = [0, 1, 2, 3, 4, 5]
fig, axes = plt.subplots(nrows=3, ncols=1, sharex=True) # Store the output of our plot calls to use as handles
# Plot returns a list of length 1, so unpack it using a comma
linear, = axes[0].plot(data, 'b')
sqrt, = axes[1].plot(np.sqrt(data), 'r')
exp, = axes[2].plot(np.exp(data), 'g') # Create handles and labels for the legend
handles = [linear, sqrt, exp]
labels = ['Linear', 'Square Root', 'Exponential'] # Draw legend on first Axes
axes[0].legend(handles, labels) plt.tight_layout()
plt.show()![[Image: img8.png]](https://raw.githubusercontent.com/theadammurphy/matplotlib_articles/master/subplots/final_html/img/img8.png)
First I generated the data and a 3×1 grid. Then I made three
Code:
ax.plot()Note that
Code:
ax.plot()Code:
listCode:
matplotlib.line.Line2DCode:
Line2DCode:
ax.legend()Standard unpacking syntax in Python is:
Code:
a, b = [1, 2]
# a = 1, b = 2However, each
Code:
ax.plot()Code:
x, = [5]
# x = 5If you just wrote
Code:
x = [5]Code:
xAfter the
Code:
plot()Code:
handlesCode:
labelsCode:
axes[0].legend()![[Image: img9.png]](https://raw.githubusercontent.com/theadammurphy/matplotlib_articles/master/subplots/final_html/img/img9.png)
In the above plot, I changed the
Code:
legendCode:
axes[1].legend(handles, labels)Code:
AxesMatplotlib Subplots Size
You have total control over the size of subplots in matplotlib.
You can either change the size of the entire
Code:
FigureCode:
SubplotsFirst, let’s look at changing the
Code:
FigureMatplotlib Figure Size
If you are happy with the size of your subplots but you want the final image to be larger/smaller, change the
Code:
FigureIf you’ve read my article on the matplotlib subplot function, you know to use the
Code:
plt.figure()Code:
FigureCode:
plt.subplots()Code:
plt.figure()Let’s change the size of the
Code:
FigureCode:
# Create 2x1 grid - 3 inches wide, 6 inches long
fig, axes = plt.subplots(nrows=2, ncols=1, figsize=(3, 6))
plt.show()![[Image: img10.png]](https://raw.githubusercontent.com/theadammurphy/matplotlib_articles/master/subplots/final_html/img/img10.png)
I created a 2×1 plot and set the
Code:
FigureCode:
figsizeCode:
(width, height)So, I created a plot 3 inches wide and 6 inches long –
Code:
figsize=(3, 6)Code:
# 2x1 grid - twice as long as it is wide
fig, axes = plt.subplots(nrows=2, ncols=1, figsize=plt.figaspect(2))
plt.show()![[Image: img11.png]](https://raw.githubusercontent.com/theadammurphy/matplotlib_articles/master/subplots/final_html/img/img11.png)
You can set a more general
Code:
FigureCode:
FigureAbove, I created a
Code:
FigureCode:
figsize=plt.figaspect(2)Note: Remember the aspect ratio (height/width) formula by recalling that
Code:
heightCode:
widthMatplotlib Subplots Different Sizes
If you have used
Code:
plt.subplot()Code:
SubplotCode:
1/xCode:
xUsing
Code:
plt.subplots()Let’s make a 2×1 plot where the top row takes up 1/3 of the space and the bottom takes up 2/3.
You do this by specifying the
Code:
gridspec_kwCode:
width_ratiosCode:
height_ratiosCode:
1/3Code:
FigureCode:
2/3Code:
1:2Code:
[1, 2]Code:
# 2 x1 grid where top is 1/3 the size and bottom is 2/3 the size
fig, axes = plt.subplots(nrows=2, ncols=1, gridspec_kw={'height_ratios': [1, 2]}) plt.tight_layout()
plt.show()![[Image: img12.png]](https://raw.githubusercontent.com/theadammurphy/matplotlib_articles/master/subplots/final_html/img/img12.png)
The only difference between this and a regular 2×1
Code:
plt.subplots()Code:
gridspec_kwLet’s create a 2×2 plot with the same
Code:
[1, 2]Code:
# Heights: Top row is 1/3, bottom is 2/3 --> [1, 2]
# Widths : Left column is 3/4, right is 1/4 --> [3, 1]
ratios = {'height_ratios': [1, 2], 'width_ratios': [3, 1]} fig, axes = plt.subplots(nrows=2, ncols=2, gridspec_kw=ratios) plt.tight_layout()
plt.show()![[Image: img13.png]](https://raw.githubusercontent.com/theadammurphy/matplotlib_articles/master/subplots/final_html/img/img13.png)
Everything is the same as the previous plot but now we have a 2×2 grid and have specified
Code:
width_ratiosCode:
3/4Code:
1/4Code:
[3, 1]Matplotlib Subplots Size
In the previous examples, there were white lines that cross over each other to separate the
Code:
SubplotsCode:
SubplotsYou could do this using the
Code:
plt.subplot()Code:
FigureCode:
AxesYou need to use the
Code:
fig.add_subplot()Code:
plt.subplot()Code:
FigureCode:
plt.figure()Code:
fig = plt.figure()Code:
<Figure size 432x288 with 0 Axes>The hardest part of creating a
Code:
FigureCode:
SubplotsCode:
SubplotSo, it’s a good idea to know what you are aiming for before you start. You could sketch it on paper or draw shapes in PowerPoint. Once you’ve done this, everything else is much easier.
I’m going to create this shape.
![[Image: img14.png]](https://raw.githubusercontent.com/theadammurphy/matplotlib_articles/master/subplots/final_html/img/img14.png)
I’ve labeled the fraction each
Code:
SubplotCode:
fig.add_subplot()I’ll create the biggest
Code:
Subplot![[Image: img15.png]](https://raw.githubusercontent.com/theadammurphy/matplotlib_articles/master/subplots/final_html/img/img15.png)
The right hand side is half of the plot. It is one of two plots on a
Code:
FigureCode:
fig.add_subplot()Code:
index=2Remember that indexing starts from 1 for the functions
Code:
plt.subplot()Code:
fig.add_subplot()In the image, the blue numbers are the index values each
Code:
SubplotCode:
ax1 = fig.add_subplot(122)As you are working with
Code:
AxesCode:
fig.add_subplot()![[Image: img16.png]](https://raw.githubusercontent.com/theadammurphy/matplotlib_articles/master/subplots/final_html/img/img16.png)
Now, select the bottom left
Code:
SubplotCode:
index=3Code:
ax2 = fig.add_subplot(223)![[Image: img17.png]](https://raw.githubusercontent.com/theadammurphy/matplotlib_articles/master/subplots/final_html/img/img17.png)
Lastly, select the top two
Code:
SubplotsCode:
index=1Code:
index=3Code:
ax3 = fig.add_subplot(423)
ax4 = fig.add_subplot(421)When you put this altogether you get
Code:
# Initialise Figure
fig = plt.figure() # Add 4 Axes objects of the size we want
ax1 = fig.add_subplot(122)
ax2 = fig.add_subplot(223)
ax3 = fig.add_subplot(423)
ax4 = fig.add_subplot(421) plt.tight_layout(pad=0.1)
plt.show()![[Image: img18.png]](https://raw.githubusercontent.com/theadammurphy/matplotlib_articles/master/subplots/final_html/img/img18.png)
Perfect! Breaking the
Code:
SubplotsNow, let’s do something you can’t do with
Code:
plt.subplot()![[Image: img19.png]](https://raw.githubusercontent.com/theadammurphy/matplotlib_articles/master/subplots/final_html/img/img19.png)
Like with the above plot, the right hand side is half of a plot with 1 row and 2 columns. It is
Code:
index=2So, the first two lines are the same as the previous plot
Code:
fig = plt.figure()
ax1 = fig.add_subplot(122)![[Image: img20.png]](https://raw.githubusercontent.com/theadammurphy/matplotlib_articles/master/subplots/final_html/img/img20.png)
The top left takes up
Code:
1/3Code:
1/3 x 1/2 = 1/6Code:
index=1Code:
ax2 = fig.add_subplot(321)![[Image: img21.png]](https://raw.githubusercontent.com/theadammurphy/matplotlib_articles/master/subplots/final_html/img/img21.png)
The final subplot takes up 2/3 of the remaining space i.e.
Code:
index=3Code:
index=5Code:
SubplotsCode:
FigureCode:
SubplotYou need the matplotlib subplot2grid function –
Code:
plt.subplot2grid()Code:
AxesCode:
FigureHere are the most important arguments:
Code:
ax = plt.subplot2grid(shape, loc, rowspan, colspan)- – tuple of 2 integers – the shape of the overall grid e.g. (3, 2) has 3 rows and 2 columns.Code:
shape
- – tuple of 2 integers – the location to place theCode:
locin the grid. It uses 0-based indexing so (0, 0) is first row, first column and (1, 2) is second row, third column.Code:Subplot
- – integer, default 1- number of rows for theCode:
rowspanto span to the rightCode:Subplot
- – integer, default 1 – number of columns for theCode:
colspanto span downCode:Subplot
![[Image: img22.png]](https://raw.githubusercontent.com/theadammurphy/matplotlib_articles/master/subplots/final_html/img/img22.png)
From those definitions, you need to select the middle left
Code:
SubplotCode:
rowspan=2![[Image: img23.png]](https://raw.githubusercontent.com/theadammurphy/matplotlib_articles/master/subplots/final_html/img/img23.png)
Thus, the arguments you need for
Code:
subplot2grid- – 3×2 gridCode:
shape=(3, 2)
- – second row, first colunn (0-based indexing)Code:
loc=(1, 0)
- – span down 2 rowsCode:
rowspan=2
This gives
Code:
ax3 = plt.subplot2grid(shape=(3, 2), loc=(1, 0), rowspan=2)Sidenote: why matplotlib chose 0-based indexing for
Code:
locCode:
locCode:
locatingCode:
GridSpecCode:
AxesPutting this together, you get
Code:
fig = plt.figure() ax1 = fig.add_subplot(122)
ax2 = fig.add_subplot(321)
ax3 = plt.subplot2grid(shape=(3, 2), loc=(1, 0), rowspan=2) plt.tight_layout()
plt.show()![[Image: img24.png]](https://raw.githubusercontent.com/theadammurphy/matplotlib_articles/master/subplots/final_html/img/img24.png)
Matplotlib Subplots_Adjust
If you aren’t happy with the spacing between plots that
Code:
plt.tight_layout()It takes 6 optional, self explanatory arguments. Each is a float in the range [0.0, 1.0] and is a fraction of the font size:
- ,Code:
left,Code:rightandCode:bottomis the spacing on each side of theCode:topCode:Suplots
- – the width betweenCode:
wspaceCode:Subplots
- – the height betweenCode:
hspaceCode:Subplots
Let’s compare
Code:
tight_layoutCode:
subplots_adjustCode:
fig, axes = plt.subplots(nrows=2, ncols=2, sharex=<strong>True</strong>, sharey=<strong>True</strong>) plt.tight_layout()
plt.show()![[Image: img25.png]](https://raw.githubusercontent.com/theadammurphy/matplotlib_articles/master/subplots/final_html/img/img25.png)
Here is a 2×2 grid with
Code:
plt.tight_layout()Code:
sharexCode:
shareyCode:
TrueCode:
fig, axes = plt.subplots(nrows=2, ncols=2, sharex=<strong>True</strong>, sharey=<strong>True</strong>) plt.subplots_adjust(wspace=0.05, hspace=0.05)
plt.show()![[Image: img26.png]](https://raw.githubusercontent.com/theadammurphy/matplotlib_articles/master/subplots/final_html/img/img26.png)
Now I’ve decreased the height and width between
Code:
SubplotsCode:
0.05To avoid loads of similar examples, I recommend you play around with the arguments to get a feel for how this function works.
Matplotlib Subplots Colorbar
Adding a colorbar to each
Code:
AxesCode:
ax.plot()Code:
fig.colorbar()Colorbars are
Code:
FigureCode:
FigureCode:
AxesCode:
AxesLet’s look at an example.
Code:
# Generate two 10x10 arrays of random numbers in the range [0.0, 1.0]
data1 = np.random.random((10, 10))
data2 = np.random.random((10, 10)) # Initialise Figure and Axes objects with 1 row and 2 columns
# Constrained_layout=True is better than plt.tight_layout()
# Make twice as wide as it is long with figaspect
fig, axes = plt.subplots(nrows=1, ncols=2, constrained_layout=True, figsize=plt.figaspect(1/2)) pcm1 = axes[0].pcolormesh(data1, cmap='Blues')
# Place first colorbar on first column - index 0
fig.colorbar(pcm1, ax=axes[0]) pcm2 = axes[1].pcolormesh(data2, cmap='Greens')
# Place second colorbar on second column - index 1
fig.colorbar(pcm2, ax=axes[1]) plt.show()![[Image: img27.png]](https://raw.githubusercontent.com/theadammurphy/matplotlib_articles/master/subplots/final_html/img/img27.png)
First, I generated two 10×10 arrays of random numbers in the range [0.0, 1.0] using the
Code:
np.random.random()Code:
plt.subplots()The keyword argument
Code:
constrained_layout=TrueCode:
plt.tight_layout()Code:
tight_layoutCode:
constrained_layoutFinally, I set
Code:
figsize=plt.figaspect(1/2)After that, I plotted the first heatmap, colored it blue and saved it in the variable
Code:
pcm1Code:
fig.colorbar()Code:
axes[0]Code:
axThe more
Code:
AxesCode:
SubplotsCode:
# Set seed to reproduce results
np.random.seed(1) # Generate 4 samples of the same data set using a list comprehension # and assignment unpacking
data1, data2, data3, data4 = [np.random.random((10, 10)) for _ in range(4)] # 2x2 grid with constrained layout
fig, axes = plt.subplots(nrows=2, ncols=2, constrained_layout=True) # First column heatmaps with same colormap
pcm1 = axes[0, 0].pcolormesh(data1, cmap='Blues')
pcm2 = axes[1, 0].pcolormesh(data2, cmap='Blues') # First column colorbar - slicing selects all rows, first column
fig.colorbar(pcm1, ax=axes[:, 0]) # Second column heatmaps with same colormap
pcm3 = axes[0, 1].pcolormesh(data3+1, cmap='Greens')
pcm4 = axes[1, 1].pcolormesh(data4+1, cmap='Greens') # Second column colorbar - slicing selects all rows, second column
# Half the size of the first colorbar
fig.colorbar(pcm3, ax=axes[:, 1], shrink=0.5) plt.show()![[Image: img28.png]](https://raw.githubusercontent.com/theadammurphy/matplotlib_articles/master/subplots/final_html/img/img28.png)
If you pass a list of
Code:
AxesCode:
axCode:
AxesCode:
locationCode:
'bottom'Code:
'left'Code:
'right'Code:
'top'Code:
'center'The code is similar to the 1×2 plot I made above. First, I set the seed to 1 so that you can reproduce the results – you will soon plot this again with the colorbars in different places.
I used a list comprehension to generate 4 samples of the same dataset. Then I created a 2×2 grid with
Code:
plt.subplots()Code:
constrained_layout=TrueThen I made the plots for the first column –
Code:
axes[0, 0]Code:
axes[1, 0]Code:
fig.colorbar()Code:
pcm1Code:
pcm2Code:
ax=axes[:, 0]Code:
:It’s a similar process for the second column but I added 1 to
Code:
data3Code:
data4Code:
shrink=0.5Now, let’s plot the same data with the same colors on each row rather than on each column.
Code:
# Same as above
np.random.seed(1)
data1, data2, data3, data4 = [np.random.random((10, 10)) for _ in range(4)]
fig, axes = plt.subplots(nrows=2, ncols=2, constrained_layout=True) # First row heatmaps with same colormap
pcm1 = axes[0, 0].pcolormesh(data1, cmap='Blues')
pcm2 = axes[0, 1].pcolormesh(data2, cmap='Blues') # First row colorbar - placed on first row, all columns
fig.colorbar(pcm1, ax=axes[0, :], shrink=0.8) # Second row heatmaps with same colormap
pcm3 = axes[1, 0].pcolormesh(data3+1, cmap='Greens')
pcm4 = axes[1, 1].pcolormesh(data4+1, cmap='Greens') # Second row colorbar - placed on second row, all columns
fig.colorbar(pcm3, ax=axes[1, :], shrink=0.8) plt.show()![[Image: img29.png]](https://raw.githubusercontent.com/theadammurphy/matplotlib_articles/master/subplots/final_html/img/img29.png)
This code is similar to the one above but the plots of the same color are on the same row rather than the same column. I also shrank the colorbars to 80% of their default size by setting
Code:
shrink=0.8Finally, let’s set the blue colorbar to be on the bottom of the heatmaps.
![[Image: img30.png]](https://raw.githubusercontent.com/theadammurphy/matplotlib_articles/master/subplots/final_html/img/img30.png)
You can change the location of the colorbars with the
Code:
locationCode:
fig.colorbar()Code:
fig.colorbar(pcm1, ax=axes[0, :], shrink=0.8, location='bottom')If you increase the
Code:
figsizeI recommend you play around with matplotlib colorbar placement. You have total control over how many colorbars you put on the
Code:
FigureMatplotlib Subplot Grid
I’ve spoken about
Code:
GridSpecYou can create any shape you want using
Code:
plt.subplots()Code:
plt.subplot2grid()Code:
GridSpecSummary
You can now create any shape you can imagine in matplotlib. Congratulations! This is a huge achievement. Don’t worry if you didn’t fully understand everything the first time around. I recommend you bookmark this article and revisit it from time to time.
You’ve learned the underlying classes in matplotlib:
Code:
FigureCode:
AxesCode:
XAxisCode:
YAxisCode:
ax.set()Code:
AxesYou can create
Code:
FiguresCode:
SubplotsCode:
1/xYou know when to use
Code:
plt.tight_layout()Code:
constrained_layout=TrueCode:
plt.subplots_adjust()Finally, you can add colorbars to as many
Code:
AxesYou’ve done everything now. All that is left is to practice these plots so that you can quickly create amazing plots whenever you want.
Where To Go From Here?
Do you wish you could be a programmer full-time but don’t know how to start?
Check out my pure value-packed webinar where I teach you to become a Python freelancer in 60 days or your money back!
https://tinyurl.com/become-a-python-freelancer
It doesn’t matter if you’re a Python novice or Python pro. If you are not making six figures/year with Python right now, you will learn something from this webinar.
These are proven, no-BS methods that get you results fast.
This webinar won’t be online forever. Click the link below before the seats fill up and learn how to become a Python freelancer, guaranteed.
https://tinyurl.com/become-a-python-freelancer

