gpt4 book ai didi

python - 在一张图上绘制多个密度

转载 作者:行者123 更新时间:2023-12-01 04:58:17 25 4
gpt4 key购买 nike

我有一个带有 MultiIndex 的数据框(支出、groupid):

                        coef    stderr    N
expenditure groupid
TOTEXPCQ 176 3745.124 858.1998 81
358 -1926.703 1036.636 75
109 239.3678 639.373 280
769 6406.512 1823.979 96
775 2364.655 1392.187 220

我可以使用 df['coef'].plot(kind='density') 获得密度。我想按 MultiIndex(支出)的外部级别对这些密度进行分组,并将不同支出级别的不同密度绘制到同一图中。

我该如何实现这一目标?奖励:用“支出”值标记不同的支出图表

回答

我最初的方法是通过生成一个 ax 来合并不同的 kdes对象并传递它,但接受的答案启发我宁愿生成一个 df ,并将组标识符作为列:

n = 25
df = pd.DataFrame({'expenditure' : np.random.choice(['foo','bar'], n),
'groupid' : np.random.choice(['one','two'], n),
'coef' : np.random.randn(n)})
df2 = df[['expenditure', 'coef']].pivot_table(index=df.index, columns='expenditure', values='coef')
df2.plot(kind='kde')

enter image description here

最佳答案

哇,这比我预想的要困难得多。概念上看起来很简单,但(再一次)概念和实践确实不同。

设置一些玩具数据:

n = 25
df = pd.DataFrame({'expenditure' : np.random.choice(['foo','bar'], n),
'groupid' : np.random.choice(['one','two'], n),
'coef' : randn(n)})

然后按支出分组,迭代每项支出,透视数据,并绘制 kde:

gExp = df.groupby('expenditure')
for exp in gExp:
print exp[0]
gGroupid = exp[1].groupby('groupid')
g = exp[1][['groupid','coef']].reset_index(drop=True)
gpt = g.pivot_table(index = g.index, columns='groupid', values='coef')
gpt.plot(kind='kde').set_title(exp[0])
show()

结果:

enter image description here enter image description here

经过一些尝试和错误才发现在绘图之前必须对数据进行旋转。

关于python - 在一张图上绘制多个密度,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/26870403/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com