使用 pandas 调整子图布局

Adjusting subplot layout with pandas

我开始意识到 matplotlibtight_layout() 不能应用于 pandas 生成的图.

这是我的代码 运行:

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

我最终遇到以下错误:

AttributeError: 'NoneType' object has no attribute 'is_bbox'

我也认为这与 github 上发布的类似问题有关: DataFrame.hist() does not get along with matplotlib.pyplot.tight_layout() #9351

因此,我正在寻找基于 subplots_adjust(*args, **kwargs) 的解决方法。最重要的是,我试图调整 hspace 参数。但是,调用 pandas.

plot 函数时不接受这些关键字参数

有什么建议吗?

正如 piRSquared 所指出的 tight_layout() 绝对有效。但是,布局应该与子图的数量完全一致。

Pandas 自动删除空的子图,因此具有超过所需子图数量的图形布局将导致上述错误。

这是我自己解决问题的方法。越简单越好。

使用plt.subplots_adjust()可以在绘制图形后轻松调整所需的参数。

tight_layout() 绝对适用于 pandas!

没有tight_layout()

df.T.plot(kind='bar', subplots=True, width=0.7, legend=False, 
                             layout=(3, 2), sharex=True, sharey=True)
# plt.tight_layout()


tight_layout()

df.T.plot(kind='bar', subplots=True, width=0.7, legend=False, 
                             layout=(3, 2), sharex=True, sharey=True)
plt.tight_layout()