Warning: file_get_contents(/data/phpspider/zhask/data//catemap/2/python/295.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
Python 绘制分类数据的最佳方法_Python_Matplotlib_Bar Chart - Fatal编程技术网

Python 绘制分类数据的最佳方法

Python 绘制分类数据的最佳方法,python,matplotlib,bar-chart,Python,Matplotlib,Bar Chart,我有这样一份清单: gender = ['male','female','male','female'] 使用matplotlib将此列表的计数绘制为条形图的最简单方法是什么 uValues = list( set( gender)) xVals = range( 0, len( uValues)) yVals = map( lambda x: gender.count( uValues[x]), xVals) import pylab pylab.bar( xVals, yVals)

我有这样一份清单:

 gender = ['male','female','male','female']
使用matplotlib将此列表的计数绘制为条形图的最简单方法是什么

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记号上显示文本,但绘图将是正确的


当然,您不会在x-ticks上显示文本,但使用集合可以正确绘制。Counter()您可以轻松计算列表中元素的频率

然后,您可以使用以下代码创建:

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()
结果图表:


使用
collections.Counter()
您可以轻松计算列表中元素的频率

然后,您可以使用以下代码创建:

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()
结果图表:


如果希望类别显示在y轴上该怎么办?@FC84用于水平条形图,@FC84还检查
orientation='horizontal'
。如果希望类别显示在y轴上该怎么办?@FC84用于水平条形图,@FC84还检查
orientation='horizontal'