Best way to plot categorical data [closed]

大兔子大兔子 提交于 2019-12-11 17:07:06

问题


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?


回答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/2 for i in x])
ax.set_xticklabels(['male', 'female'])

plt.show()

Resulting chart:




回答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



来源:https://stackoverflow.com/questions/29508208/best-way-to-plot-categorical-data

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!