我有一个这样的清单:
gender = ['male','female','male','female']
使用matplotlib将此列表的计数绘制为条形图的最简单方法是什么?
答案 0 :(得分:5)
使用collections.Counter()
,您可以轻松计算列表中元素的频率。
然后,您可以使用以下代码创建bar plot:
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()
结果图表:
答案 1 :(得分:1)
uValues = list( set( gender))
xVals = range( 0, len( uValues))
yVals = map( lambda x: gender.count( uValues[x]), xVals)
import pylab
pylab.bar( xVals, yVals)
当然你在x-ticks上没有文字,但情节是正确的