7

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?

T.C. Proctor
  • 6,096
  • 6
  • 27
  • 37
  • 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 Feb 21 '15 at 17:17
  • Related: https://stackoverflow.com/questions/64642855/how-to-obtain-a-fixed-height-in-pixels-fixed-data-x-y-aspect-ratio-and-automati – Ciro Santilli OurBigBook.com Nov 02 '20 at 09:31

2 Answers2

7

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.

Community
  • 1
  • 1
jonchar
  • 6,183
  • 1
  • 14
  • 19
  • According to the docs you mentioned, using 'equal' simply makes the aspect ratio the same as the aspect ratio of the data, ie going one unit on the x axis is the same as going one unit on the y. I think you're right that "axes automatically fill to the size of the figure". – T.C. Proctor Feb 21 '15 at 17:09
2

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"]]
T.C. Proctor
  • 6,096
  • 6
  • 27
  • 37
  • 1
    Or `plt.figure(figsize=[2*x for x in plt.rcParams["figure.figsize"]])` to apply to the following plot only. – Ben Usman May 10 '19 at 16:53