Pandas 绘制每组值计数的直方图

问题描述 投票:0回答:1

我有一个数据集:

game_id year
100     2020
100     2020
100     2020
100     2020
227     2022
227     2022
228     2023
228     2023
228     2023
...
300     2023
300     2023
301     2023
301     2023
301     2023

我想使用 pandas 2.0.3 为唯一

year
值的 distribution(所以
game_id
)的每个
df['game_id'].value_counts()
生成一个直方图。

我可以使用例如手动执行此操作

years = df'groupby('year')
,然后每年使用
years.get_group(2023).value_counts().hist()
,但我觉得应该有一个简单的单行代码以正确的形状将数据传递到
hist()
,以获得一个小的倍数图。

pandas histogram
1个回答
2
投票

假设您想要计数的直方图

pd.crosstab(df['game_id'], df['year']).plot.hist(alpha=0.5)

输出:

对于单独的图表,您可以使用

seaborn.displot
:

import seaborn as sns

sns.displot(data=df.value_counts().reset_index(name='count'),
            x='count', col='year', kind='hist')

输出:

© www.soinside.com 2019 - 2024. All rights reserved.