【问题标题】:How to adjust subplot size in seaborn?如何调整seaborn中的子图大小?
【发布时间】:2017-05-30 06:37:47
【问题描述】:
%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

【问题讨论】:

  • 我的赞成票代表我同意这看起来很糟糕,我不知道如何解决它,我想看看其他人是否可以。

标签: python pandas boxplot seaborn


【解决方案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,这些情节会稍微被打碎在一起。见下文。

【讨论】:

  • 如何进行 2*2 子图,以便每个轴有两个箱线图?
猜你喜欢
  • 2020-06-18
  • 2019-09-14
  • 1970-01-01
  • 2021-10-02
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多