gpt4 book ai didi

python - 在 Altair 中获取选择总和

转载 作者:行者123 更新时间:2023-12-02 00:05:10 25 4
gpt4 key购买 nike

我有一个时间序列的成本值,我想获得选定日期范围内的成本总和。间隔选择工作正常,但我如何访问所选日期?

brush = alt.selection(type='interval', encodings=['x'])

chart = alt.Chart(forecast).mark_bar().encode(
x='dates:T',
y='costs:Q',
color='type:N',
).add_selection(
brush
)

enter image description here

最佳答案

您可以将文本标记与 filter transform 一起使用以显示选择范围内的值的总和。例如:

import altair as alt
import pandas as pd
import numpy as np

data = pd.DataFrame({
"dates": pd.date_range('2019-04-01', freq='M', periods=20),
"costs": np.linspace(1000, 5000, 20),
})

brush = alt.selection(type='interval', encodings=['x'])

chart = alt.Chart(data).mark_bar().encode(
x='dates:T',
y='costs:Q',
).add_selection(
brush
)

text = alt.Chart(data).transform_filter(brush).mark_text(
align='left',
baseline='top',
).encode(
x=alt.value(5),
y=alt.value(5),
text=alt.Text('sum(costs):Q', format='.1f'),
)

chart + text

enter image description here


编辑:如果你想在文本中显示选择范围,这并不完全简单,但你可以使用 calculate transform 来实现。连同适当的 vega expression按名称引用选择的字符串。

例如:

brush = alt.selection(type='interval', encodings=['x'], name='sel')

chart = alt.Chart(data).mark_bar().encode(
x='dates:T',
y='costs:Q',
).add_selection(
brush
)

text = alt.Chart(data).transform_filter(
brush
).transform_aggregate(
total='sum(costs)'
).transform_calculate(
date_range="sel.dates ? monthAbbrevFormat(month(sel.dates[0])) + ' to ' + monthAbbrevFormat(month(sel.dates[1])) : 'all'",
text="'Total for ' + datum.date_range + ': ' + format(datum.total, '.0f')"
).mark_text(
align='left',
baseline='top',
).encode(
x=alt.value(5),
y=alt.value(5),
text=alt.Text('text:N'),
)

chart + text

enter image description here

关于python - 在 Altair 中获取选择总和,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/60893866/

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