【发布时间】:2015-04-08 07:13:00
【问题描述】:
我有一个这样的列表:
gender = ['male','female','male','female']
使用 matplotlib 将此列表的计数绘制为条形图的最简单方法是什么?
【问题讨论】:
标签: python matplotlib bar-chart
我有一个这样的列表:
gender = ['male','female','male','female']
使用 matplotlib 将此列表的计数绘制为条形图的最简单方法是什么?
【问题讨论】:
标签: python matplotlib bar-chart
使用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()
结果图表:
【讨论】:
orientation='horizontal' here。
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 上有文字,但情节是正确的
【讨论】: