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

如何为Altair下拉菜单中的特定变量设置自定义数值刻度?

解决Altair图表尺寸刻度动态适配问题

要让不同下拉选项对应不同的尺寸刻度范围,你可以用Altair的条件编码结合选择器实现动态适配,具体修改如下:

修改后的完整代码

dropdown = alt.binding_select(options=["Square Feet", "Year built", "Rooms"], name="Select a size variable:")

# 创建动态查询选择器
selection = alt.selection(type="single", fields=['column'], bind=dropdown, init={'column':'Square Feet'})

alt.Chart(altdat, title='Washington, D.C. condos, by price').transform_fold(
    ["Square Feet", "Year built", "Rooms"],
    as_=['column', 'value']
).transform_filter(
    selection
).mark_circle().encode(
    x = alt.X('Longitude', scale=alt.Scale(domain=[altdat['Longitude'].min(), altdat['Longitude'].max()])),
    y = alt.Y("Latitude", scale=alt.Scale(domain=[altdat['Latitude'].min(), altdat['Latitude'].max()])),
    color=alt.Color('Price (city appraisal)', scale=alt.Scale(scheme='redyellowgreen', reverse=True)),
    # 核心修改:用条件编码动态设置尺寸刻度
    size=alt.Size('value:Q', scale=alt.Scale(
        domain=alt.condition(
            alt.datum.column == 'Year built',
            [1800, 2000],
            [0, 2000]
        )
    )),
    tooltip=["WARD", "Square Feet", "Year built", "Rooms"]
).add_selection(selection
).properties(
    width=600,
    height=600
).interactive()

关键说明

  • 核心改动在size编码部分:通过alt.condition判断当前选中的列(alt.datum.column),如果是"Year built"就用[1800, 2000]作为刻度域,其他选项保持[0, 2000]
  • 切换下拉选项时,尺寸刻度会自动匹配对应变量的合理范围,解决"Year built"刻度从0开始的展示问题

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.08.02 03:40:20