关于python:如何调整seaborn中的子图大小?

How to adjust subplot size in seaborn?

1
2
3
4
5
6
7
8
9
10
%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

这将根据需要输出子图。

Pandas

1
2
3
4
5
6
7
8
9
10
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

Seaborn


您对的调用正在创建一个新的空白图形,该图形与第一步中已声明的fig不同。将通话中的figsize设置为plt.subplots。由于未设置,它在绘图中默认为(6,4)。您已经创建了图形并将其分配给变量fig。如果要对该数字执行操作,则应该执行fig.set_size_inches(12, 5)来更改大小。

然后您可以简单地调用fig.tight_layout()来很好地拟合该图。

此外,通过在axes对象数组上使用flatten,还有一种遍历轴的简便方法。我也直接使用seaborn本身的数据。

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
# 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()

enter