Create a bar chart using seaborn/matplotlib with specific characteristics

Viewed 144

I would like to create, instead of the line plot generated by the following code:

import pandas as pd
import seaborn as sns

d = {'P': {0: 'BO', 1: 'BO', 2: 'BO', 3: 'BO', 4: 'BO'},
     'M': {0: 'NB', 1: 'LR', 2: 'SVM', 3: 'SGD', 4: 'RF'},
     'PP': {0: '0.72', 1: '0.71', 2: '0.85', 3: '0.54', 4: '0.75'},
     'R': {0: '0.82', 1: '0.62', 2: '0.64', 3: '0.54', 4: '0.70'},
     'F': {0: '0.71', 1: '0.52', 2: '0.76', 3: '0.73', 4: '0.65'},
     'A': {0: '0.91', 1: '0.91', 2: '0.92', 3: '0.92', 4: '0.92'},
     'D': {0: 'A', 1: 'A', 2: 'A', 3: 'B', 4: 'B'}}


df = pd.DataFrame(d)
df2 = df.melt(['P', 'M', 'D'])
g = sns.relplot(data=df2, 
            x='M', 
            y="value", 
            hue='P', 
            style='D', 
            col="variable", 
            col_wrap=2,
            col_order = ['PP', 'R', 'F', 'A'],
            kind="line",
            facet_kws={'sharey': False, 'sharex': False},
            height=3,
           )
g._legend.set_bbox_to_anchor([0.9, 1])
g._legend._loc=2

a bar plot, with the same characteristics (the only difference would be having bars instead of lines). I cannot do it using seaborn as the only kind values accepted are lines and scatter. If I use matplotlib, I get an error because I cannot set style='D'. I hope you can provide some suggestion on how to create a such plot.

1 Answers

Seaborn has catplot() which is like relplot() but for categorical plots including kind='bar':

df2.value = df2.value.astype(float)
g = sns.catplot(
    data=df2,
    x='M',
    y='value',
    hue='P',
    col='variable',
    col_wrap=2,
    col_order = ['PP', 'R', 'F', 'A'],
    kind='bar',
    facet_kws={'sharey': False, 'sharex': False},
    height=3,
)
Related