python - 使用条形图呈现来自 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”中输入什么来计算数据中的男性和女性人数?
解决方案
您可以像这样使用数据框绘图方法: df["SEX"].value_counts().plot(kind="bar")
否则, plt.bar() 期望的列表与 x 的组数 (0, 1) 和 y 的相关计数 (2, 1) 一样长。确保标签和计数以这种方式对齐有点困难,所以我建议使用数据框方法。您的解决方案没有为 x 提供正确的值。
推荐阅读
- android - 如何恢复已导出的 Room 数据库?
- python - 做什么而不是分配 np.ndarray.data?
- magento - Magento 2.3 显示带有运输选项的文本
- java - 如何遍历可选中的嵌套列表?
- powershell - 基于 PowerShell 注释的帮助不适用于脚本
- c# - C# 使用查询中的多行填充标签
- c++ - C++ 函数模板是否鼓励弱类型化?
- c# - 使用 c#/visual studio 在 Mac 上的 Docker 中访问/查询 SQLServer
- select - 如何从 bigquery 中的表中仅选择第一行 - 以降低成本
- c# - C# 将 JSON 字符串反序列化为对象