I came to realize that matplotlib's tight_layout()
cannot be applied to plots generated by pandas.
This is the code I am running:
0 1 2 3 4
A 0.039895 0.960105 NaN NaN NaN
D 0.030418 0.969582 NaN NaN NaN
E 0.037345 0.962655 NaN NaN NaN
F 0.061522 0.938478 NaN NaN NaN
G 0.047163 0.952837 NaN NaN NaN
H 0.026423 0.000000 0.000000 0.973577 NaN
df.T.plot(kind='bar', subplots=True, width=0.7, legend=False,
layout=(2,4), sharex=True, sharey=True)
plt.tight_layout()
I end up with the following error:
AttributeError: 'NoneType' object has no attribute 'is_bbox'
I also believe that this is related to a similar issue posted on github: DataFrame.hist() does not get along with matplotlib.pyplot.tight_layout() #9351
Therefore, I am looking for a workaround based on subplots_adjust(*args, **kwargs)
. Most importantly, I was trying to adjust the hspace
parameter. However, these keyword arguments are not accepted when calling the plot
function of pandas.
Any suggestions?
tight_layout()
definitely works with pandas!without tight_layout()
df.T.plot(kind='bar', subplots=True, width=0.7, legend=False,
layout=(3, 2), sharex=True, sharey=True)
# plt.tight_layout()
with tight_layout()
df.T.plot(kind='bar', subplots=True, width=0.7, legend=False,
layout=(3, 2), sharex=True, sharey=True)
plt.tight_layout()
As pointed out by piRSquared pointed out tight_layout()
definitely works. However, the layout should be exactly agreeing with the number of subplots.
Pandas automatically removes empty subplots and thus figure layouts with more than the required number of subplots will cause the error stated above.
Here is my own solution to the problem. As simple as it gets.
Using plt.subplots_adjust()
one can easily adjust the required parameters after plotting the figure.
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