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

如何强制Altair分层图表使用指定的自定义颜色数组

Altair分层图表自定义颜色不生效问题解决

问题现象

和《Setting colors in Altair charts》描述场景类似,使用Altair绘制分层图表时希望显式指定颜色,但参考对应方案实现后,图表始终显示随机颜色,未使用预设的颜色数组。

复现代码

import altair as alt
from vega_datasets import data

source = data.movies()
colors = ['#170c3b', '#fa8d0b']


plot = alt.Chart(source).mark_line().encode(
    x=alt.X("IMDB_Rating", bin=True),
    y=alt.Y(
        alt.repeat("layer"), aggregate="mean", title="Mean of US and Worldwide Gross"
    ),
    color=alt.datum(alt.repeat("layer")),
).repeat(
    layer=["US_Gross", "Worldwide_Gross"]
).configure_range(
        category=alt.RangeScheme(scheme=colors)
)

plot.show()

效果对比

  • 目标自定义颜色:
    #170c3b#fa8d0b
    目标颜色1示例目标颜色2示例
  • 实际生成效果:颜色偏移,未匹配指定色值
    异常颜色图表示例

问题原因

代码中RangeScheme用法错误:

  • alt.RangeScheme仅用于引用Vega内置的命名配色方案,比如"category10"、"dark2"这类官方预设的配色标识,不支持直接传入自定义颜色数组。
  • 传入自定义颜色列表时,不需要用RangeScheme包裹,直接赋值给category参数即可。

修复方案

修改configure_range部分的逻辑,直接传入自定义颜色数组,修正后代码如下:

import altair as alt
from vega_datasets import data

source = data.movies()
colors = ['#170c3b', '#fa8d0b']


plot = alt.Chart(source).mark_line().encode(
    x=alt.X("IMDB_Rating", bin=True),
    y=alt.Y(
        alt.repeat("layer"), aggregate="mean", title="Mean of US and Worldwide Gross"
    ),
    color=alt.datum(alt.repeat("layer")),
).repeat(
    layer=["US_Gross", "Worldwide_Gross"]
).configure_range(
        category=colors
)

plot.show()

补充:如果要使用RangeScheme,必须传入Vega内置的合法配色名称,例如alt.RangeScheme(scheme="category20")为正确写法,自定义色值不属于内置scheme范畴,直接传列表即可生效。


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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.09.03 09:15:36