将值显示为文本,仅显示 altair 中具有最大高度的条形图

Display value as text, of only the bar with the maximum height in altair

我无法完成这个看似简单的任务,即仅在条形图本身上显示最大条形图的值 - 例如注释最大条形图。

对于下面的代码,我希望仅在栏上方看到值为 16 的文本。

data = pd.DataFrame({'time':[0,1,2,3,4,5,6,7,8,9], 'value':[1,2,4,8,16,11,9,7,5,3]})

bar = alt.Chart(data).mark_bar(opacity=1, width=15).encode(
    x='time:T',
    y='value:Q',
    color = alt.condition(alt.datum.time>7, alt.value('red'), alt.value('steelblue')) #hackey way to highlight last 'n' bars 
)

text = bar.mark_text(align='center', dy=-10).encode(
    text='value:Q'
)

bar+text

我尝试使用一些转换并使用 argmaxmax 但到目前为止似乎没有任何效果。要么全部显示值,要么全部为 Null.

您可以在 x 和 y 编码中使用 argmax 聚合来执行此操作:

import altair as alt
import pandas as pd

data = pd.DataFrame({'time':[0,1,2,3,4,5,6,7,8,9], 'value':[1,2,4,8,16,11,9,7,5,3]})

bar = alt.Chart(data).mark_bar(opacity=1, width=15).encode(
    x='time:T',
    y='value:Q',
    color = alt.condition(alt.datum.time>7, alt.value('red'), alt.value('steelblue')) #hackey way to highlight last 'n' bars 
)

text = bar.mark_text(align='center', dy=-10).encode(
    x=alt.X('time:T', aggregate={"argmax": "value"}),
    y=alt.Y('value:Q', aggregate={"argmax": "value"}),
    text='max(value):Q'
)

bar+text