I want to create two plots, with the second plot generally being about 1/2 or less the size of the main plot. However, when trying to do this with one row and two columns I get an error
fig, axs=plt.subplots(1,2, figsize=(12,10), gridspec_kw={'height_ratios': [2,1],
'width_ratios':[3,1]})
(ValueError: Expected the given number of height ratios to match the number of rows of the grid
).
If I only put in one argument in the list for height ratios
then I get two plots that are of the same size.
fig, axs=plt.subplots(1,2, figsize=(12,10), gridspec_kw={'height_ratios': [3],
'width_ratios':[3,1]})
That plot is shown below. How can I make the plot on the right half the size of the one on the left, while placing it in the bottom right (not top right)?
CodePudding user response:
The trick here is that height_ratios
depends on the number of rows. A ratio is a relationship between 2 things so you cannot introduce a ratio between height subplots if there is only one row (aka one 'height' for the subplots) - no matter how many columns there are. However, you can trick plt.subplots
using fig.add_gridspec
to introduce more rows and columns but never call on them. Here is how you can go about it:
import matplotlib.pyplot as plt
if __name__ == "__main__":
fig = plt.figure(figsize=(12, 10))
gs = fig.add_gridspec(nrows=2, ncols=2, width_ratios=[3, 1])
fig.suptitle('An overall title')
# Add left subplot
# gs[top and bottom rows, first column (the 'left' subplot))]
ax_left = fig.add_subplot(gs[:, 0])
ax_left.set_xlabel("Left X label")
ax_left.set_ylabel("Left Y label")
# Add bottom right subplot - gs[bottom row, last column (the 'left' subplot)]
# We do not add the upper right subplot
ax_right_bottom = fig.add_subplot(gs[-1, -1])
ax_right_bottom.set_xlabel("Right Bottom X label")
ax_right_bottom.set_ylabel("Right Bottom Y label")
plt.tight_layout()
plt.show()
If you wanted to make the bottom right subplot smaller or bigger in relation to the left subplot, now you could use height_ratios
because now there are two rows and you can implement a ratio.
You can read more about it in Arranging multiple Axes in a Figure - it's full of useful tips for wrangling axes and subplots. Cheers!