Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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.

Pandas Boxplots

But when trying to achieve it through seaborn, subplots are stacked close to each other, how do I change size of each subplot?

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

like image 527
DSG Avatar asked Jan 15 '17 08:01

DSG


1 Answers

Your call to plt.figure(figsize=(12,5)) is creating a new empty figure different from your already declared fig from the first step. Set the figsize in 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.

You can then simply call fig.tight_layout() to get the plot fitted nicely.

Also, there is a much easier way to iterate through axes by using flatten on your array of axes objects. I am also using data directly from seaborn itself.

# 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_layout the plots are slightly smashed together. See below.

enter image description here

like image 67
Ted Petrou Avatar answered Oct 05 '22 06:10

Ted Petrou