2

I have multiple data frames consist of three main columns: 1)the categories (c1, c2, c3), one includes the data values, and one includes different time-periods (AA, BB, CC, DD).

what I am trying to generate is to generate boxplots of the data for all dataframe, at once, and in one figure ! I did try with different enumerate options and "ax" argument, but still it generates the boxplot separately, I couldn't figure it out.

allCN=[df1, df2, df3]
fig, axs = plt.subplots(nrows = 3, ncols=4, figsize = (30,54))
axes = axes.flatten()

for i, x in enumerate(allCN):

    sns.set(style="ticks", palette='Set2')
    sns.set_context("paper", font_scale=1.1, rc={"lines.linewidth": 1.1})

    g=sns.catplot(x="Cat", y="Data", ax=axs[i,0],
                   col="Period", data=x, kind="box", height=4, aspect=10/18,
                     width=0.6,fliersize=2.5,showfliers=False, linewidth=1.1,
                     notch=False,orient="v"))
    g.set_ylabels("test", size=12)
    g.set_xlabels("")

example output

1

2 Answers 2

3

One way is to stack your data frames and use the row= argument inside catplot. First to create something like your data:

import pandas as pd
import numpy as np
import seaborn as sns

df1 = pd.DataFrame({'Cat':np.random.choice(['C1','C2','C3'],50),
                    'Data':np.random.uniform(0,1,50),"Period":np.random.choice(['AA','CC','DD'],50)})

df2 = pd.DataFrame({'Cat':np.random.choice(['C1','C2','C3'],50),
                    'Data':np.random.uniform(0,1,50),"Period":np.random.choice(['AA','CC','DD'],50)})

df3 = pd.DataFrame({'Cat':np.random.choice(['C1','C2','C3'],50),
                    'Data':np.random.uniform(0,1,50),"Period":np.random.choice(['AA','CC','DD'],50)})

Then concat the dataframes and add another column (i used source below) to annotate the dataframe:

allCN=pd.concat([df1,df2,df3])
allCN['source'] = np.repeat(['df1','df2','df3'],[len(df1),len(df2),len(df3)])

sns.catplot(x="Cat", y="Data",
            col="Period", row = "source", 
            data=allCN, kind="box", height=2,aspect=1.6)

enter image description here

3
  • Thanks, that works! is there anyway to reduce the 'h space or w space' like the Mathplotlib?
    – Seji
    Jan 29, 2021 at 17:24
  • 1
    allCN['source'] = np.repeat(['df1','df2','df3'],[len(df1),len(df2),len(df3)]) is so much nicer than iterating through the dataframe to add a new column, and then doing pd.concat. It deserves more upvotes. Jul 6, 2022 at 19:19
  • Even better df = pd.concat((df.assign(source=f'df{i}') for i, df in enumerate([df1, df2, df3]))) using .assign, which I found as a comment to this answer Jul 11, 2022 at 3:44
2

What about the hue parameter in sns.boxplot? Would that give you the result you want?

enter image description here

import seaborn as sns
import matplotlib.pyplot as plt

tips = sns.load_dataset("tips")
box_plot = sns.boxplot(x="day", y="total_bill", data=tips, hue="smoker")
plt.show()
0

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge that you have read and understand our privacy policy and code of conduct.

Not the answer you're looking for? Browse other questions tagged or ask your own question.