【问题标题】:Seaborn Distplot and BarplotSeaborn Distplot 和 Barplot
【发布时间】:2017-06-03 22:31:56
【问题描述】:

我有一个数据框,其中包含“A”、“B”、“C”、“D”的列值...这只是某种分组。我想生成一个包含列值与其计数的直方图。

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

这产生了一个错误:

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

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

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

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 是否可以自动确定计数而无需经历创建新数据框的麻烦?

【问题讨论】:

    标签: python seaborn


    【解决方案1】:

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

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

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

    【讨论】:

    • 只做df['patient_group'].value_counts()会更容易
    • @PaulH 想详细说明您的评论吗?
    猜你喜欢
    • 2020-07-26
    • 2016-08-05
    • 2019-08-03
    • 2021-11-26
    • 2017-08-30
    • 2017-10-12
    • 2015-10-20
    • 2019-12-02
    • 1970-01-01
    相关资源
    最近更新 更多