Ik heb zo’n dataframe
import seaborn as sns
import pandas as pd
%pylab inline
df = pd.DataFrame({'a' :['one','one','two','two','one','two','one','one','one','two'],
'b': [1,2,1,2,1,2,1,2,1,1],
'c': [1,2,3,4,6,1,2,3,4,6]})
Een enkele boxplot is OK:
sns.boxplot(y="b", x="a", data=df, orient='v')
Maar ik wil een subplot maken voor alle variabelen. Ik heb geprobeerd:
names = ['b', 'c']
plt.subplots(1,2)
sub = []
for name in names:
ax = sns.boxplot( y=name, x= "a", data=df, orient='v' )
sub.append(ax)
maar het geeft uit:
Antwoord 1, autoriteit 100%
We maken de figuur met de subplots:
f, axes = plt.subplots(1, 2)
Waarbij assen een array is met elke subplot.
Vervolgens vertellen we elke plot in welke subplot we ze willen hebben met het argument ax
.
sns.boxplot( y="b", x= "a", data=df, orient='v' , ax=axes[0])
sns.boxplot( y="c", x= "a", data=df, orient='v' , ax=axes[1])
En het resultaat is:
Antwoord 2, autoriteit 2%
names = ['b', 'c']
fig, axes = plt.subplots(1,2)
for i,t in enumerate(names):
sns.boxplot(y=t, x="a", data=df, orient='v', ax=axes[i % 2])
Voorbeeld:
names = ['b', 'c']
fig, axes = plt.subplots(1,2)
sns.set_style("darkgrid")
flatui = ["#95a5a6", "#34495e"]
for i,t in enumerate(names):
sns.boxplot(y=t, x= "a", data=df, orient='v', ax=axes[i % 2], palette=flatui)
Antwoord 3
Gebruik plt.subplots
:
import matplotlib.pyplot as plt
# Creating subplot axes
fig, axes = plt.subplots(nrows,ncols)
# Iterating through axes and names
for name, ax in zip(names, axes.flatten()):
sns.boxplot(y=name, x= "a", data=df, orient='v', ax=ax)
Werkvoorbeeld:
import numpy as np
# example data
df = pd.DataFrame({'a' :['one','one','two','two','one','two','one','one','one','two'],
'b': np.random.randint(1,8,10),
'c': np.random.randint(1,8,10),
'd': np.random.randint(1,8,10),
'e': np.random.randint(1,8,10)})
names = df.columns.drop('a')
ncols = len(names)
fig, axes = plt.subplots(1,ncols)
for name, ax in zip(names, axes.flatten()):
sns.boxplot(y=name, x= "a", data=df, orient='v', ax=ax)
plt.tight_layout()