How can I make seaborn distribution subplots in a loop?

Viewed 23408

I have a 5D array called data

for i in range(10):
     sns.distplot(data[i,0,0,0], hist=False)

But I want to make them inside subplots instead. How can I do it?

Tried this:

plt.rc('figure', figsize=(4, 4))  
fig=plt.figure()
fig, ax = plt.subplots(ncols=4, nrows=3)

for i in range(10):
    ax[i].sns.distplot(data[i,0,0,0], hist=False)
plt.show()

This obviously doesn't work.

2 Answers

You would want to use the ax argument of the seaborn distplot function to supply an existing axes to it. Looping can be simplified by looping over the flattened array of axes.

fig, axes = plt.subplots(ncols=4, nrows=3)

for i, ax in zip(range(10), axes.flat):
    sns.distplot(data[i,0,0,0], hist=False, ax=ax)
plt.show()

Specify which subplot each distplot should fall on:

f = plt.figure()
for i in range(10):
    f.add_subplot(4, 3, i+1)
    sns.distplot(data[i,0,0,0], hist=False)
plt.show()
Related