绘制分类数据的最佳方法 [英] Best way to plot categorical data

查看:47
本文介绍了绘制分类数据的最佳方法的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个这样的列表:

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

使用matplotlib以条形图的形式绘制此列表的计数的最简单方法是什么?

What would be the simplest way to plot the count of this list as a bar plot using matplotlib?

推荐答案

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

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()

结果图表:

这篇关于绘制分类数据的最佳方法的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆