pythonpandasseaborn

Plotting each row in a pandas DataFrame as a bar with seaborn


Given such a dataframe,

data = pd.DataFrame({'a':[1,2],'b':[2,3],'c':[3,4],'d':[1,2],'code':[1,2]})

a   b   c   d   code
0   1   2   3   1   1
1   2   3   4   2   2

I want to have a barplot with a 2 bars for each column (one for each row...)

this one

sns.barplot(data.iloc[0])

works just fine,

barplot 1 column

but when i try to doit for 2 columns,

sns.barplot(data,hue='code')

claims:

ValueError: The following variable cannot be assigned with wide-form data: hue


Solution

  • You can set_index on "code", transpose, then plot.bar:

    data.set_index('code').T.plot.bar()
    

    Output:

    pandas barplot

    With , you would first need to melt the data:

    sns.barplot(data.melt('code'), x='variable', y='value', hue='code')
    

    Output:

    seaborn pandas melt barplot