在 Altair 中格式化 mark_text 的文本

Format text of mark_text in Altair

我正在尝试按照 Multi-Line Tooltip example 的思路创建图表,但我想格式化正在打印的字符串,以便在末尾添加一些文本。我正在尝试修改这部分:

# Draw text labels near the points, and highlight based on selection
text = line.mark_text(align='left', dx=5, dy=-5).encode(
    text=alt.condition(nearest, 'y:Q', alt.value(' '))
)

具体来说,我想要 'y:Q' + " 后缀",而不是 'y:Q'。我试过这样做:

# Draw text labels near the points, and highlight based on selection
text = line.mark_text(align='left', dx=5, dy=-5).encode(
    text=alt.condition(nearest, 'y:Q', alt.value(' '), format=".2f inches")
)

或者,我试过:

# Draw text labels near the points, and highlight based on selection
y_fld = 'y'
text = line.mark_text(align='left', dx=5, dy=-5).encode(
    text=alt.condition(nearest, f"{y_fld:.2f} inches", alt.value(' '))
)

我想我明白为什么这些不起作用,但我不知道如何拦截 y 的值并通过格式字符串传递它。谢谢!

我认为最简单的方法是使用 transform_calculate 计算一个新字段来计算您想要的标签。

使用文档中的示例,我会像这样更改文本图表:

text = line.mark_text(align='left', dx=5, dy=-5).encode(
    text=alt.condition(nearest, 'label:N', alt.value(' '))
).transform_calculate(label='datum.y + " inches"')

这导致这张图表:

如果你想要更多的控制,你可以预先用 pandas 改变数据集。请务必将类型设置为标称(而不是定量),否则您会在工具提示中看到 NaNs。