I'm trying to create a subplot figure in matplotlib, specifying only the width (using figwidth(float)
rather than figsize(float, float)
), assuming that the height will have some default value. When calling pyplot.subplots()
, the **fig_kw
parameter is passed to the pyplot.figure()
call:
All additional keyword arguments are passed to the pyplot.figure call.
which in turn passes any additional keyword arguments to the Figure
constructor. One of the valid Figure constructor keyword arguments is figwidth=float
. However, when this is done via the passing mentioned above (subplots(figwidth) --> figure(figwidth) --> Figure(figwidth)) an AttributeError is raised:
AttributeError: 'Figure' object has no attribute 'bbox_inches'
The MWE to recreate this is:
import matplotlib.pyplot as plt
f, ax = plt.subplots(figwidth=4)
I thought perhaps this was due to needing to set the height and width together so I tried calling pyplot.figure()
directly with parameters figheight=3
and figwidth=4
, but got the same AttirbuteError.
What am I missing here?
CodePudding user response:
The problem is that figwidth
and figheight
are initialized in the superclass through the kwargs
. This results in the call of the method set_figwidth
(source) that look like this:
def set_figwidth(self, val, forward=True):
self.set_size_inches(val, self.get_figheight(), forward=forward)
It calls self.get_figheight()
(source) which looks like this:
def get_figheight(self):
return self.bbox_inches.height
And this is the line that throws the error when it tries to access self.bbox_inches
which is initialized after the superclass (here).
So it's not possible to pass the value in the constructor, but you can set them on the initialized object:
f, ax = plt.subplots()
f.set_figwidth(10)
CodePudding user response:
I actually get the same error when I try to run plt.figure(figwidth=2)
.
Just use figsize
, which works with both plt.figure()
and plt.subplots()
. You can simply pass the default value:
fig, ax_list = plt.subplots(2, 1, figsize=(plt.rcParams['figure.figsize'][0], 3))