【问题标题】:How to plot proportions of datapoints using seaborn python如何使用 seaborn python 绘制数据点的比例
【发布时间】:2021-08-30 06:39:08
【问题描述】:

我使用代码创建了一个绘图,结果如下所示:

代码:

%matplotlib inline
sns.histplot(x = 'time_class', hue = 'Det_poiResult',data = df, multiple="dodge", shrink=.8)

结果:

我想转换此图以显示结果的比例。

  1. 在 x 上为每个类别计算的色调(赢、输、平)的结果是什么。 (例如:在类闪电战中赢得所有数据点的一小部分)
  2. 色调比例的结果是什么(通过将色调计数作为 x 上所有类的所有数据点的一部分来计算)

我应该修改我的数据框以计算比例结果然后绘制它还是有什么简单的方法可以使用内置类来做到这一点?

预期结果-1

on Y-axis I have proportions computed for each category of X instead of counts. 

proportions computation:
for the blitz on X.
  win= count(wins)/count(blitz)
  loss= count(loss)/count(blitz)
  draw= count(draw)/count(blitz)....

预期结果 2

on Y-axis I have proportions computed as a fraction of datapoints in the entire dataset instead of counts. 

proportions computation:
for the blitz on X.
  win= count(wins)/count(all datapoints of df)
  loss= count(loss)/count(all datapoints of df)
  draw= count(draw)/count(all datapoints of df)....

【问题讨论】:

  • sns.histplot(...., multiple='fill')是你想要达到的目的吗?
  • 我在 Y 上编辑了带有预期结果的问题。我希望这会有所帮助
  • fill 实现了与预期结果 1 相同的效果,但我希望它像闪避一样表示。
  • 有没有办法用比例值注释multiple=fill 图?这解决了我的要求-1

标签: python pandas numpy matplotlib seaborn


【解决方案1】:

您可以使用 pandas 的 groupby 来计算总和,然后再计算百分比。然后,sns.barplot 可以创建情节。

import matplotlib.pyplot as plt
import seaborn as sns
import pandas as pd
import numpy as np

df = pd.DataFrame({'time_class': np.random.choice(['blitz', 'rapid', 'bullit'], 5000, p=[.6, .1, .3]),
                   'Det_poiResult': np.random.choice(['win', 'loss', 'draw'], 5000, p=[.49, .48, .03])})
df_counts = df.groupby(['time_class', 'Det_poiResult']).size()

df_pcts1 = (df_counts.groupby(level=0).apply(lambda x: 100 * x / float(x.sum()))).to_frame(name="Percent").reset_index()
df_pcts2 = (df_counts.groupby(level=1).sum() * 100 / len(df)).to_frame(name="Percent").reset_index()
df_pcts2['time_class'] = "overall"

ax = sns.barplot(data=df_pcts1.append(df_pcts2), y='Percent',
                 x='time_class', order=['blitz', 'rapid', 'bullit', 'overall'],
                 hue='Det_poiResult', hue_order=['win', 'loss', 'draw'], palette=['dodgerblue', 'tomato', 'chartreuse'])
ax.legend(loc='upper left', bbox_to_anchor=(1.02, 1.02))
ax.axvline(2.5, ls='--', color='0.4')
plt.tight_layout()
plt.show()

【讨论】:

  • 我在做同样的事情。我想知道是否有任何带有 matplotlip/seaborn 的内置方法来实现这一点。 Plotly 有一个方法,但是太费时间和资源了
  • 除了 histplot 的填充选项,我认为没有更自动的东西了。如果您已经在做完全相同的事情,为什么不在问题中提及?为什么不将代码添加到问题的帖子中?
猜你喜欢
  • 2018-07-05
  • 2019-09-26
  • 2017-02-21
  • 2020-06-22
  • 2020-12-02
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2020-06-22
相关资源
最近更新 更多