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

如何在Altair中设置相对条形图宽度?

在Altair中设置相对条形图宽度

要在Altair里实现Vega-Lite中width: {"band": 0.7}的相对条形宽度效果,不能直接在mark_bar()里传字典形式的width,需要用以下两种方法实现:

方法一:通过X轴编码的band参数设置

当X轴是分类型或时间分箱字段时,直接在X编码中设置band属性,控制条形占据对应分栏的比例:

import altair as alt
from vega_datasets import data

source = data.seattle_weather()

alt.Chart(source).mark_bar().encode(
    x=alt.X('month(date):O', band=0.7),  # 设置band参数为0.7,即占据分栏70%宽度
    y='mean(precipitation):Q'
)

方法二:用configure_bar()全局配置条形宽度

如果需要统一设置图表中所有条形的相对宽度,可以使用configure_bar()结合alt.BandSize类:

import altair as alt
from vega_datasets import data

source = data.seattle_weather()

alt.Chart(source).mark_bar().encode(
    x='month(date):O',
    y='mean(precipitation):Q'
).configure_bar(
    width=alt.BandSize(0.7)  # 指定相对宽度为分栏的70%
)

报错原因说明

Altair的mark_bar()方法默认要求width参数传入像素数值,而字典形式的相对宽度配置不属于数值类型,因此直接传width={'band':0.7}会触发“width不是数字”的错误,必须通过上述编码参数或配置类来传递相对宽度规则。

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.08.22 04:06:18