You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

如何在Altair的transform_calculate函数中修改小数格式

解决Altair回归方程文本小数位数过多的问题

要在Altair的transform_calculate里格式化小数位数,得用Vega表达式语言的format函数,而非Python语法。以下是修正后的完整代码:

params = alt.Chart(df).transform_regression(
    axe_x, axe_y, params=True
).transform_calculate(
    intercept='datum.coef[0]',
    slope='datum.coef[1]'
).transform_calculate(
    # 使用Vega的format函数保留两位小数
    text='"y = " + format(datum.intercept, ".2f") + "x + " + format(datum.slope, ".2f")'
).mark_text(
    baseline="top",
    align="left"
).encode(
    x=alt.value(20),  # 距离左侧像素
    y=alt.value(20),  # 距离顶部像素
    text='text:N',
)

关键说明:

  • transform_calculate中的字符串是Vega表达式,不是Python代码,需遵循Vega语法:
    • 字符串拼接用+,字符串字面量要加双引号
    • 格式化数字用format(数值, 格式字符串),.2f表示保留两位小数
  • 之前尝试的Python f-string、alt.Text均不适用,因为transform_calculate是在前端执行,而非Python端

内容的提问来源于stack exchange,提问作者grymlin

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.08.04 15:55:25