如何使用Altai显示百分比直方图而不是计数

2024-10-01 11:21:33 发布

您现在位置:Python中文网/ 问答频道 /正文

如何使用Altair和Pandas获得总百分比的直方图而不是计数的直方图?在

我现在有这个:

Histogram of values

我这样做得到的:

d = {'age': ['12', '32', '43', '54', '32', '32', '12']}
dfTest = pd.DataFrame(data=d)

alt.Chart(dfTest).mark_bar().encode(
    alt.X("age:Q", bin=True),
    y='count()',
)

Tags: dataframepandasagedatachartbar直方图alt
1条回答
网友
1楼 · 发布于 2024-10-01 11:21:33

可以使用Join Aggregate transform后跟Calculate transform来完成此操作:

import pandas as pd
import altair as alt

source = pd.DataFrame({'age': ['12', '32', '43', '54', '32', '32', '12']})

alt.Chart(source).transform_joinaggregate(
    total='count(*)'
).transform_calculate(
    pct='1 / datum.total'
).mark_bar().encode(
    alt.X('age:Q', bin=True),
    alt.Y('sum(pct):Q', axis=alt.Axis(format='%'))
)

enter image description here


编辑:这是我最初的回答,这要复杂得多:

这并不完全是直接的,因为它需要手动指定编码当前隐含的bin和aggregate转换,然后是计算转换来计算百分比。下面是一个例子:

^{pr2}$

enter image description here

我希望将来我们能够简化转换API。在

相关问题 更多 >