简体   繁体   English

如何调整seaborn中的subplot大小?

[英]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

This outputs subplots as desired. 这会根据需要输出子图。

熊猫箱图

But when trying to achieve it through seaborn, subplots are stacked close to each other, how do I change size of each subplot? 但是当试图通过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

Seaborn Boxplots

Your call to plt.figure(figsize=(12,5)) is creating a new empty figure different from your already declared fig from the first step. 你对plt.figure(figsize=(12,5))调用plt.figure(figsize=(12,5))正在创建一个与你从第一步中已经声明的fig不同的新空图。 Set the figsize in your call to plt.subplots . 设置figsize在您的来电plt.subplots It defaults to (6,4) in your plot since you did not set it. 由于您没有设置,因此在您的绘图中默认为(6,4)。 You already created your figure and assigned to variable fig . 你已经创建了你的数字并分配给变量fig If you wanted to act on that figure you should have done fig.set_size_inches(12, 5) instead to change the size. 如果你想对这个数字采取行动你应该完成fig.set_size_inches(12, 5)而不是改变大小。

You can then simply call fig.tight_layout() to get the plot fitted nicely. 然后,您可以简单地调用fig.tight_layout()以使绘图很好地拟合。

Also, there is a much easier way to iterate through axes by using flatten on your array of axes objects. 此外,通过在axes对象数组上使用flatten ,可以更轻松地迭代axes I am also using data directly from seaborn itself. 我也直接使用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()

在此输入图像描述

Without the tight_layout the plots are slightly smashed together. 没有tight_layout ,情节会被轻微粉碎在一起。 See below. 见下文。

在此输入图像描述

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM