首页 > 解决方案 > 如何在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”手术;

谁能帮我?

标签: pythonplothistogram

解决方案


您可以这样做,将 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.

推荐阅读