【问题标题】:Format text of mark_text in AltairAltair中mark_text的格式文本
【发布时间】:2019-04-28 07:13:23
【问题描述】:

我正在尝试创建一个有点类似于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 的值并通过格式字符串传递它。谢谢!

【问题讨论】:

    标签: altair


    【解决方案1】:

    我认为最简单的方法是使用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。

    【讨论】:

    • 谢谢!我不太确定 datum 是什么,但它似乎是一个 altair 约定。我还想将我能够做的值四舍五入,因为其他人有点困惑:.transform_calculate(label=f'format(datum.{fld},".1f") + " inches"')
    • datum 是 vega 访问数据的方式。文档中有更多信息 altair-viz.github.io/user_guide/transform.html 格式化数据做得好!
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2021-07-06
    • 1970-01-01
    • 1970-01-01
    • 2020-01-21
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多