如何在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
相关产品推荐
相关产品推荐

