10

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?

2
  • 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. Commented Feb 21, 2015 at 17:17
  • Related: stackoverflow.com/questions/64642855/… Commented Nov 2, 2020 at 9:31

2 Answers 2

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.

Sign up to request clarification or add additional context in comments.

1 Comment

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".
3

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

Or plt.figure(figsize=[2*x for x in plt.rcParams["figure.figsize"]]) to apply to the following plot only.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.