Skip to content Skip to sidebar Skip to footer

Best Way To Plot Categorical Data

I have a list like this: gender = ['male','female','male','female'] What would be the simplest way to plot the count of this list as a bar plot using matplotlib?

Solution 1:

Using collections.Counter() you can easily count the frequency of elements in your list.

Then you can create a bar plot using the code below:

gender = ['male','male','female','male','female']

import matplotlib.pyplot as plt
from collections import Counter

c = Counter(gender)

men = c['male']
women = c['female']

bar_heights = (men, women)
x = (1, 2)

fig, ax = plt.subplots()
width = 0.4

ax.bar(x, bar_heights, width)

ax.set_xlim((0, 3))
ax.set_ylim((0, max(men, women)*1.1))

ax.set_xticks([i+width/2for i in x])
ax.set_xticklabels(['male', 'female'])

plt.show()

Resulting chart:

enter image description here

Solution 2:

uValues = list( set( gender))
xVals = range( 0, len( uValues))
yVals = map( lambda x: gender.count( uValues[x]), xVals)

import pylab
pylab.bar( xVals, yVals)

of course you won't have text on x-ticks, but the plot will be correct

Post a Comment for "Best Way To Plot Categorical Data"