Linda
Linda

Reputation: 1123

Arrange boxplots as a grid with seaborn `FacetGrid`

I have a data frame with three columns Features, CV-fold, Accuracy, Network. I want to have a boxplot for each Network, grouped by the Features and the CV-fold for the axis (see example image).

Output right now

df = pd.read_csv(path)
df['Features'] = df["Features"].astype('category')
ordered_features = sorted(df.Network.value_counts().index)

df = df.loc[df['Accuracy'] > 0.1]
df.Accuracy = df.Accuracy*100

#sns.color_palette("husl", len(df['CV-fold'].value_counts().index))
#sns.set_palette('husl', len(df['CV-fold'].value_counts().index))

g = sns.FacetGrid(df, row="Network", row_order=ordered_features,
                  height=3, aspect=3, legend_out=True, despine=False)
g.map(sns.boxplot, x="CV-fold", y="Accuracy", hue="Features", data=df, palette='muted').add_legend()

g.set_axis_labels("", "Accuracy (%)")

Because I have 8 different networks, I would like to not have them all in a column or a row, but formatted in a grid (e.g. 2x4). Additionally, even though sharex is not enabled, the x-axis is only labeled at the very bottom graph.

How can I do that?

Upvotes: 4

Views: 5182

Answers (1)

mechanical_meat
mechanical_meat

Reputation: 169304

You would use the col_wrap keyword argument to get your plots on multiple rows with multiple columns.

For repeating the x-axis labels use ax.tick_params().

Example:

import seaborn as sns, matplotlib.pyplot as plt

tips = sns.load_dataset('tips')
ordered_days = sorted(tips['day'].unique())
g = sns.FacetGrid(tips,col='day',col_order=ordered_days,col_wrap=2)
#                                               change this to 4 ^
g.map(sns.boxplot,'sex','total_bill',palette='muted')
for ax in g.axes.flatten(): 
    ax.tick_params(labelbottom=True)
plt.tight_layout()
plt.show()

Result: enter image description here

Upvotes: 5

Related Questions