How to display different values of the same column in plot graph/chart

Viewed 137

The column class has 2 options for the value, either 'b' or 's'. I am trying to display a graph/chart that shows how many are 'b' and how many are 's'. I can't figure out how to do this when they are both in the same column.

The current code shows a scatter plot, but I'd like to use the data from column 'class'.

import pandas as pd
import matplotlib.pylab as plt
import numpy as np

#df = df.groupby('class')['class'].count()
#print(df)

df = pd.DataFrame(np.random.randint(0,10,size=(5, 2)), columns=['x','y'])
df['class'] = ['Benign','Malware','Benign','Malware','Malware']

# plot groupby results on the same canvas 
fig, ax = plt.subplots(figsize=(8,6))

for n, grp in df.groupby('class'):
    ax.scatter(x = "x", y = "y", data=grp, label=n)
ax.legend(title="Label")

plt.show()
1 Answers

Don't group by class and loop, rather aggregate (with value_counts) then plot:

df['class'].value_counts().plot.bar()

or with matplotlib's functions:

s = df['class'].value_counts()
ax.bar(s.index, s)

output:

enter image description here

Related