Reputation: 9708
I try to fit four images using matplotlib.pyplot
like the following:
| plot1 | plot2|
| plot3 |
| plot4 |
Most examples I found cover three plots like these:
ax1 = plt.subplot(221)
ax2 = plt.subplot(222)
ax3 = plt.subplot(212)
And this plots the three plots successfully (However, I don't get how it is done for ax3
). Now, I want to add the plot 4 to this arrangement. Whatever I tried, I couldn't succeed.
Could you please guide me how can I achieve it?
Upvotes: 10
Views: 8402
Reputation: 9708
In newer versions of matplotlib you can use subplot_mosaic
like:
fig, axes = plt.subplot_mosaic("AB;CC;DD")
It gives you four subplots in this structure:
AB | A | B |
AB;CC;DD -> CC -> | C |
DD | D |
To avoid overlapping labels, enable constrained_layout
:
fig, axes = plt.subplot_mosaic("AB;CC;DD", constrained_layout=True)
Upvotes: 3
Reputation: 39072
You can use subplot2grid. It is really convenient.
The docs say
Create a subplot in a grid. The grid is specified by shape, at location of loc, spanning rowspan, colspan cells in each direction. The index for loc is 0-based.
First you define the size in terms of number of rows and columns (3,2)
here. Then you define the starting (row, column) position for a particular subplot. Then you assign the number of rows/columns spanned by that particular subplot. The keywords for row and column spans are rowspan
and colspan
respectively.
import matplotlib.pyplot as plt
ax1 = plt.subplot2grid((3, 2), (0, 0), colspan=1)
ax2 = plt.subplot2grid((3, 2), (0, 1), colspan=1)
ax3 = plt.subplot2grid((3, 2), (1, 0), colspan=2)
ax4 = plt.subplot2grid((3, 2), (2, 0), colspan=2)
plt.tight_layout()
Upvotes: 13
Reputation: 1895
The integer that you provide to subplot is actually 3 parts:
So for each call to subplots we specify how the plot area should be divided (using rows and cols) and then which area to put the plot in (using index), see images below.
ax1 = plt.subplot(321) # 3 rows, 2 cols, index 1: col 1 on row 1
ax2 = plt.subplot(322) # 3 rows, 2 cols, index 2: col 2 on row 1
ax3 = plt.subplot(312) # 3 rows, 1 cols, index 2: col 1 on row 2
ax4 = plt.subplot(313) # 3 rows, 1 cols, index 3: col 1 on row 3
From the docs:
Either a 3-digit integer or three separate integers describing the position of the subplot. If the three integers are nrows, ncols, and index in order, the subplot will take the index position on a grid with nrows rows and ncols columns. index starts at 1 in the upper left corner and increases to the right.
pos is a three digit integer, where the first digit is the number of rows, the second the number of columns, and the third the index of the subplot. i.e. fig.add_subplot(235) is the same as fig.add_subplot(2, 3, 5). Note that all integers must be less than 10 for this form to work.
Upvotes: 1