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

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/41659188/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-09-14 02:46:42  来源:igfitidea点击:

How to adjust subplot size in seaborn?

pythonpandasboxplotseaborn

提问by DSG

%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.

这会根据需要输出子图。

Pandas Boxplots

Pandas箱线图

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

Seaborn 箱线图

回答by Ted Petrou

Your call to plt.figure(figsize=(12,5))is creating a new empty figure different from your already declared figfrom the first step. Set the figsizein your call to plt.subplots. It defaults to (6,4) in your plot since you did not set it. You already created your figure and assigned to variable fig. If you wanted to act on that figure you should have done fig.set_size_inches(12, 5)instead to change the size.

您对 的调用plt.figure(figsize=(12,5))正在创建一个新的空图,与您fig在第一步中已经声明的不同。将figsize通话中的设置为plt.subplots。由于您没有设置它,它在您的图中默认为 (6,4)。您已经创建了图形并分配给了变量fig。如果你想对那个数字采取行动,你应该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 flattenon your array of axesobjects. I am also using data directly from seaborn itself.

此外,通过flattenaxes对象数组上使用,还有一种更简单的方法来遍历轴。我也直接使用来自 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()

enter image description here

在此处输入图片说明

Without the tight_layoutthe plots are slightly smashed together. See below.

没有tight_layout地块被轻微地砸在一起。见下文。

enter image description here

在此处输入图片说明