首页 > 解决方案 > 使用条形图呈现来自 csv 文件的数据

问题描述

假设我有这个 csv 文件:

CODE     AGE GROUP     SEX     CITY      
----     ---------     ---     ----      
E101      25 to 29      M      Denver     
E102      25 to 29      F      Denver       
E105      25 to 29      M      Denver 

我希望使用条形图来呈现它,但我不确定如何计算其中的男性和女性人数。这是我到目前为止编码的内容:

import matplotlib.pyplot as plt

plt.style.use('bmh')

x = df['SEX']
y = # what should I put here?

plt.xlabel('Sex', fontsize=16)
plt.ylabel('Number of people', fontsize=16)
plt.bar(x, y)

我应该在“y”中输入什么来计算数据中的男性和女性人数?

标签: pythonpandascsvvisualization

解决方案


您可以像这样使用数据框绘图方法: df["SEX"].value_counts().plot(kind="bar")

否则, plt.bar() 期望的列表与 x 的组数 (0, 1) 和 y 的相关计数 (2, 1) 一样长。确保标签和计数以这种方式对齐有点困难,所以我建议使用数据框方法。您的解决方案没有为 x 提供正确的值。


推荐阅读