I have a problem with plotting multiple subplots. I would like to set the PHYSICAL aspect ratio of the subplots to a fixed value. In my example I have 12 subplots (4 rows and 3 columns) on a landscape A4 figure. There all subplots are nicely placed on the whole figure, and for all subplots the height is nearly equal to the width.
But if I change the layout of my figure to portrait, the subplots are stretched vertically. And this is exactly what should not happen. I would like to have the same height and width of the subplots as on the landscape figure. Is there a possibility that the aspect ratio of the subplots stay the same?
Thanks in advance, Peter
EDIT: I have found a workaround. But this just works for non-logarithmic axes...
aspectratio=1.0 ratio_default=(ax.get_xlim()[1]-ax.get_xlim()[0])/(ax.get_ylim()[1]-ax.get_ylim()[0]) ax.set_aspect(ratio_default*aspectratio)
set_aspect() to Make a Square Plot With Equal Axes Axes. set_aspect() function. If we use "equal" as an aspect ratio in the function, we get a plot with the same scaling from data points to plot units for X-axis and Y-axis. It sets both X-axis and Y-axis to have the same range.
figure() − Creates a new figure or activates an existing figure. plt. subplots() − Creates a figure and a set of subplots.
Actually, what you're wanting is quite simple... You just need to make sure that adjustable
is set to 'box'
on your axes, and you have a set aspect ratio for the axes (anything other than 'auto'
).
You can either do this with the adjustable
kwarg when you create the subplots. Alternatively, you can do this after their creation by calling ax.set_adjustable('box')
, or by calling ax.set_aspect(aspect, adjustable='box')
(where aspect is either 'equal'
or a number).
Now, regardless of how the figure is resized, the subplots will maintain the same aspect ratio.
For example:
import matplotlib.pyplot as plt fig = plt.figure() ax1 = fig.add_subplot(2,1,1, adjustable='box', aspect=0.3) ax2 = fig.add_subplot(2,1,2) ax1.plot(range(10)) ax2.plot(range(10)) plt.show()
Now, compare how the top subplot responds to resizing, vs. how the bottom subplot responds:
The initial plot
Resized to a vertical layout:
Resized to a horizontal layout:
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With