python - 如何在python中做与两列相关的多个直方图/条形图?
问题描述
我有一个包含多行和多列的数据集。简化:
A B
g 1
h 2
h 3
g 3
j 4
g 5
其中 A 是手术代码,B 是住院时间。因此,每一行对应一个患者。
我想对 A 列和 B 列做多个图(每个类别一个)。在这个例子中:
图 1:其中 x 代表每位接受“g”手术的患者,y 代表每位患者的住院时间。所以对于这个情节,必须存在 3 个条形,因为有 3 个患者进行了“g”手术;
图 2:其中 x 代表每位患者,接受“h”手术,y 代表每位患者的住院时间。所以对于这个情节,必须存在 2 条,因为有 2 名患者进行了“h”手术;
图 3:其中 x 代表每位患者,接受了“j”次手术,y 代表每位患者的住院时间。所以对于这个情节,必须存在 1 条,因为有 1 名患者进行了“j”手术;
谁能帮我?
解决方案
您可以这样做,将 pandas 中的数据集作为 df 获取:
>>> import pandas as pd
>>> import matplotlib.pyplot as plt
>>> df = pd.DataFrame({'A':['g', 'h', 'h', 'g', 'j', 'g'], 'B':[1, 2, 3, 3, 4, 5]})
>>> df
A B
0 g 1
1 h 2
2 h 3
3 g 3
4 j 4
5 g 5
>>> df.groupby('A').plot(kind = 'bar')
A
g AxesSubplot(0.125,0.11;0.775x0.77)
h AxesSubplot(0.125,0.11;0.775x0.77)
j AxesSubplot(0.125,0.11;0.775x0.77)
dtype: object
>>> plt.show() #you'll see 3 different figures for that.
推荐阅读
- git - 如何将文件从存储库移动到另一个存储库保留移动文件的历史记录
- awk - awk 更新 file1 中与 file2 中的另一个文件匹配的行的一部分
- jquery - 模态窗口中的 YouTube 播放器
- r - 我不想在我的 R 包中记录数据集
- embedded - 配置为使用外部振荡器的 STM32F3 器件上的 RCC 振荡器配置错误
- amazon-web-services - SNS 主题和 Lambda
- string - 将字符串转换为字母数字
- php - 需要 PHP 路由 preg_match 帮助
- algorithm - 序列列表之间的最长公共子序列
- java - 当我想拦截一个方法时,我只能使用接口子类吗?