Plotting variables by classes

Viewed 546

I would need to plot as bar chart the following columns

    %_Var1 %_Var2   %_Val1  %_Val2     Class
2   0.00    0.00    0.10    0.01        1
3   0.01    0.01    0.07    0.05        0
17  0.00    0.00    0.02    0.01        0
24  0.00    0.00    0.11    0.04        0
27  0.00    0.00    0.02    0.03        1
44  0.00    0.00    0.05    0.02        0
53  0.00    0.00    0.03    0.01        1
67  0.00    0.00    0.06    0.02        0
87  0.00    0.00    0.22    0.01        1
115 0.00    0.00    0.03    0.02        0

comparing the values having Class 1 and Class 0 respectively (i.e. bars which show each column of the dataframe, putting one beside the other the column for only Class 1 ad the column for Class 0. So I should have 8 bars: 4 where 4 bars are for Class 1 and the remaining 4 for Class 0. One column of Class 1 should be beside the same column for Class 0. I tried as follows:

ax = df[["%_Var1", "%_Var2", "%_Var3" , "%_Var4"]].plot(kind='bar')

but the output is completely wrong, also writing ax = df[["%_Var1", "%_Var2", "%_Var3" , "%_Var4"]].Label.plot(kind='bar')

I think I should consider a groupby in my code, in order to group by Classes, but I do not know how to set the order (plots are not my top skill)

2 Answers

If you want to try the seaborn way, melt the dataframe to long format and then hue on the class.

data = df.melt(id_vars=['class'], value_vars=['var1','var2','val1','val2'])

import seaborn as sns
sns.barplot(x='variable', y='value', hue='class', data=data, ci=0)

gives:

enter image description here

Or if you want to get the plot based on the class, simply change the hue and x axis..

sns.barplot(x='class', y='value', hue='variable', data = data, ci=0)

gives:

enter image description here

Using groupby:

df.groupby('Class').mean().plot.bar()

With pivot_table method you can summarise the data per group as well.

df.pivot_table(index='Class').plot.bar()
# df.pivot_table(columns='Class').plot.bar() # invert order

By default, it calculates the mean of your target-columns, but you can specify another aggregation method with aggfunc='myfunc' parameter.

Related