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

如何在Altair中修改坐标轴刻度标签,将数值替换为自定义文本?

问题原因

你定义的X、Y轴为定量数据类型(后缀:Q声明),轴的实际数值范围为0到1,你之前直接给values参数传入字符串标签,和轴的数值体系不匹配,因此配置不生效。你需要先指定刻度要显示的数值位置(即原刻度的0、0.5、1),再绑定对应的自定义文本标签。

修正后代码

alt.Chart(df).mark_circle().encode(
    alt.X('x:Q',
          axis=alt.Axis(
              values=[0, 0.5, 1],
              labels=['infrequent','average','frequent']
          ),
          title="A's frequency"),
    alt.Y('y:Q',
          axis=alt.Axis(
              values=[0, 0.5, 1],
              labels=['infrequent','average','frequent']
          ),
          title="B's frequency"),
    color=alt.Color('s:Q',scale=alt.Scale(domain=[0, 1],scheme="redyellowblue")),
    tooltip=['term',    
             alt.Tooltip('cat:Q', title="Occurence in A"),
             alt.Tooltip('ncat:Q', title="Occurence in B"),
             alt.Tooltip('s:Q', title="Score close to A",format='.2')]
).properties(
    width=300,
    height=300
)

旧版本兼容方案

如果你使用的Altair版本低于4.0,不支持直接传入labels参数,可以用labelExpr实现相同效果,对应轴的配置修改为:

alt.Axis(
    values=[0, 0.5, 1],
    labelExpr="datum.value === 0 ? 'infrequent' : datum.value === 0.5 ? 'average' : 'frequent'"
)

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.10.07 12:36:01