I'd like to choose the width of a figure, while still letting matplotlib choose the aspect ratio that it finds suitable. Every method I know to change the figure size requires a (width, height) tuple, which forces a certain aspect ratio. Is there any way to specify just the width (or just the height) and allow matplotlib to choose a suitable aspect ratio?
- I think I didn't quite understand is that the aspect ratio/size of the figure has a default, constant value, not something that is flexible and based on the axes inside the figure. I think that the default figure aspect ratio is just the golden ratio, but I'm not sure. I've just been defining my figure sizes using the golden ratio, and I like the results.T.C. Proctor– T.C. Proctor2015-02-21 17:17:45 +00:00Commented Feb 21, 2015 at 17:17
- Related: stackoverflow.com/questions/64642855/…Ciro Santilli OurBigBook.com– Ciro Santilli OurBigBook.com2020-11-02 09:31:19 +00:00Commented Nov 2, 2020 at 9:31
2 Answers
From what I understand, matplotlib does not "choose" a suitable aspect ratio per se. Instead, axes automatically fill to the size of the figure. Thus by setting the figure size with a (width, height) tuple you are also setting it's aspect ratio (taking into account the number of subplot axes within the figure as well). Perhaps the axes method set_aspect will help you? It lets you explicitly set the aspect ratio for an axes object within a figure.
For example, the following will produce a 4"x2" figure but the axes within it will have a 1:1 aspect ratio:
fig, ax = plt.subplots(figsize=(4,2)) ax.set_aspect('equal') The method set_aspect can also take a height:width number instead. You could use this to force the axes within to keep a specific aspect ratio regardless of the figure dimensions you choose.
EDIT: This post may also be helpful.
1 Comment
I've learned that matplotlib actually just uses a constant default figure size for all figures. This value is stored in the rcParams, and can be viewed with
plt.rcParams["figure.figsize"] This returns [6.0, 4.0] for me.
If you want to keep the same width to height ratio (ie "aspect ratio"), you can, for example, double it with:
plt.rcParams["figure.figsize"] = [2 * i for i in plt.rcParams["figure.figsize"]] 1 Comment
plt.figure(figsize=[2*x for x in plt.rcParams["figure.figsize"]]) to apply to the following plot only.