1

I'm using seaborn to draw some boxplot. Here is my code

fig, axs = plt.subplots(nrows = 8, ncols=2, figsize = (70,50))
plt.subplots_adjust(hspace = 0.8)

i = 0
j = 0

for item in items:
    ...
    # create dist as a list
    sns.boxplot(data = dist, ax = axs[i][j])

    j += 1

    if j == 2:
        i += 1
        j = 0

I'm changing the length and width in figsize() but it does not change the width of my subplots! what's wrong here?

Gustav Rasmussen
  • 3,720
  • 4
  • 23
  • 53
HHH
  • 6,085
  • 20
  • 92
  • 164
  • Does this answer your question? [Resize subplots using seaborn](https://stackoverflow.com/questions/42179048/resize-subplots-using-seaborn) – Trenton McKinney Jul 27 '20 at 23:23

2 Answers2

2

You also set the aspect ratio by changing the figsize, so it may be better to use something like figsize = (20, 80) in your example rather than the current (70, 50).

Otherwise, you may need to separately set the aspect ratio. (for example by adding axs[i][j].set_aspect(1) inside your for loop)

hoomant
  • 455
  • 2
  • 12
1

Your call to plt.figure(figsize=(60,50)) 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()
Ujjwal Dash
  • 767
  • 1
  • 4
  • 8