How to plot multiple figures as subplots and multiples columns of a dataframe in seaborn?

Viewed 238

I’ve been attempting to plot all my columns of my dataframe in subplots but it does not work. is there a smart way to make it?

import padas as pd
import seaborn as sns
    df = pd.DataFrame({'TR':np.arange(1, 6).repeat(5), 'A': np.random.randint(1, 100,25), 'B':  np.random.randint(50, 100,25), 'C':  np.random.randint(50, 1000,25), 'D':  np.random.randint(5, 100,25), 'E':  np.random.randint(5, 100,25),
                   'F':  np.random.randint(5, 100,25), 'G':  np.random.randint(5, 100,25), 'H':  np.random.randint(5, 100,25), 'I':  np.random.randint(5, 100,25), 'J':  np.random.randint(5, 100,25) })
row = 2
col = 5
r = sorted(list(range(0, row))*5)
c = list(range(0, col))*2

fig, axes = plt.subplots(row, col, figsize=(20, 10))

for j, k,i in zip( r, c, df.columns):
    plt.figure()
    g = sns.boxenplot(x = 'TR', y = df[i], ax= axes[j, k], data=df)

    plt.show()
1 Answers

One thing is that you need to move plt.show out of the loop, and stop creating new figure instance with plt.figure.

Also,

  1. it's easier to flattern axes and zip
  2. it looks like you want to plot from columns 1, not column 0

All together:

row = 2
col = 5

fig, axes = plt.subplots(row, col, figsize=(20, 10))

# flattern `axes` with `.ravel()`    
# notice the `[1:]`
for ax,i in zip( axes.ravel(), df.columns[1:]):
    # remove this as well
    #  plt.figure()

    # you just need to pass y = i
    g = sns.boxenplot(x = 'TR', y = i, ax= ax, data=df)

# move `plt.show()` out of for loop:
plt.show()

Output:

enter image description here


Update probably a more seaborn way is to use FacetGrid:

fg = sns.FacetGrid(data=df.melt('TR'), 
                   col='variable', col_wrap=5, sharey=False)
fg.map(sns.boxenplot,'TR','value',order=df['TR'].unique)

Output:

enter image description here

Related