Seaborn Distplot和Barplot

时间:2017-06-03 22:31:56

标签: python seaborn

我的数据框包含的列值是' A' B'' C'' D' D'这只是一些种类的分组。我想生成一个包含列值与其计数的直方图。

import seaborn as sns
sns.distplot(dfGroupingWithoutNan['patient_group'])

这产生了一个错误:

TypeError: unsupported operand type(s) for /: 'str' and 'int'

我想也许是因为我不熟悉distplot,我没有以正确的方式使用它。我在想,我可以将一个系列传递给它,它将能够确定每个值的计数并相应地在直方图中显示它们。

无论如何,我想到了其他解决方案,这就是我想出的。

series1 = dfGroupingWithoutNan['patient_group'].value_counts()
dfPatientGroup = pd.DataFrame( {'levels' : series1.index, 'level_values' : series1.values})

sns.set_style("whitegrid")
sns.barplot(x="levels", y="level_values", data=dfPatientGroup)

这次我能够使用条形图生成每个值与其计数的关系图。

我只是想问,有没有其他方法可以做到这一点,比如如果我使用distplot它会如何工作?另外,我真的需要创建一个新的数据帧,只是为了拥有一些存储值和计数的存储库吗?我在想,如果不经历创建新数据帧的麻烦,distplot是否可以自动确定计数?

1 个答案:

答案 0 :(得分:1)

我会使用Counter来执行此操作。逻辑与您正在做的非常相似,但您不需要创建额外的数据帧:

from collections import Counter
cnt = Counter(dfGroupingWithoutNan.patient_group)
sns.barplot(x=cnt.keys(), y=cnt.values())

我不知道任何解决方案会自动处理seabornmatplotlib直方图中的字符串值。