如何调整seaborn中的子图大小?

How to adjust subplot size in seaborn?

%matplotlib inline
fig, axes = plt.subplots(nrows=2, ncols=4)
m = 0
l = 0
for i in k: 
    if l == 4 and m==0:
        m+=1
        l = 0
    data1[i].plot(kind = 'box', ax=axes[m,l], figsize = (12,5))
    l+=1

这会根据需要输出子图。

但是当尝试通过 seaborn 实现时,子图彼此堆叠得很近,我该如何更改每个子图的大小?

fig, axes = plt.subplots(nrows=2, ncols=4)
m = 0
l = 0
plt.figure(figsize=(12,5))
for i in k: 
    if l == 4 and m==0:
        m+=1
        l = 0
    sns.boxplot(x= data1[i],  orient='v' , ax=axes[m,l])
    l+=1

您对 plt.figure(figsize=(12,5)) 的调用正在创建一个新的空图形,该图形与您在第一步中已声明的 fig 不同。将调用中的 figsize 设置为 plt.subplots。它默认为 (6,4) 在您的情节中,因为您没有设置它。您已经创建了图形并分配给了变量 fig。如果您想根据该数字采取行动,您应该 fig.set_size_inches(12, 5) 而不是更改尺寸。

然后您只需调用 fig.tight_layout() 即可很好地拟合绘图。

此外,通过在 axes 对象数组上使用 flatten 可以更轻松地遍历轴。我也直接使用 seaborn 本身的数据。

# I first grab some data from seaborn and make an extra column so that there
# are exactly 8 columns for our 8 axes
data = sns.load_dataset('car_crashes')
data = data.drop('abbrev', axis=1)
data['total2'] = data['total'] * 2

# Set figsize here
fig, axes = plt.subplots(nrows=2, ncols=4, figsize=(12,5))

# if you didn't set the figsize above you can do the following
# fig.set_size_inches(12, 5)

# flatten axes for easy iterating
for i, ax in enumerate(axes.flatten()):
    sns.boxplot(x= data.iloc[:, i],  orient='v' , ax=ax)

fig.tight_layout()

如果没有 tight_layout,情节会稍微有些混乱。见下文。