Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Adjusting subplot layout with pandas

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?

like image 766
Fourier Avatar asked Oct 28 '16 12:10

Fourier


2 Answers

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()

enter image description here


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()

enter image description here

like image 95
piRSquared Avatar answered Sep 26 '22 20:09

piRSquared


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.

like image 23
Fourier Avatar answered Sep 26 '22 20:09

Fourier