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

如何在Altair条件颜色编码的首个条件中添加配色方案?

解决Altair条件颜色中添加配色方案的问题

要在第一个条件中使用配色方案替代单一红色,你需要在条件条目里通过encoding嵌套完整的颜色编码定义,而不是直接把field和scale放在条件字典中——这正是触发SchemaValidationError的原因,因为条件条目不支持直接使用这些键。

修正后的字典写法

cutoff = 10
color_data = 'RME'
condition_test = {
    'condition': [
        {
            'test': f'{selection.name} && datum.{color_data} < {cutoff}',
            'encoding': {
                'color': {
                    'field': f'{color_data}:Q',
                    'scale': {'scheme': 'redpurple', 'domain': [0, cutoff]},
                    'legend': None
                }
            }
        },
        {'test': f'{selection.name} && datum.{color_data} >= {cutoff}', 'value': 'black'}
    ],
    'value': 'lightgray'
}

对应到完整示例代码的实现

下面是基于你提供的汽车数据集示例修改后的可运行代码,实现选中区域内马力小于100的点使用redpurple配色方案,大于等于100的点为黑色,未选中的点为浅灰色:

import altair as alt
from vega_datasets import data

# Load example data
source = data.cars()

# Define the selection
my_selection = alt.selection_interval(encodings=['x'])

cutoff = 100

base = alt.Chart(source).mark_point().encode(
    x='Horsepower:Q',
    y='Miles_per_Gallon:Q',
    color=alt.ColorValue('lightgray'))

# Create the scatter plot with color encoding
scatter = alt.Chart(source).mark_point().encode(
    x='Horsepower:Q',
    y='Miles_per_Gallon:Q',
    color={
        'condition': [
            {
                'test': f'{my_selection.name} && datum.Horsepower < {cutoff}',
                'encoding': {
                    'color': {
                        'field': 'Horsepower:Q',
                        'scale': {'scheme': 'redpurple', 'domain': [0, cutoff]},
                        'legend': None
                    }
                }
            },
            {'test': f'{my_selection.name} && datum.Horsepower >= {cutoff}', 'value': 'black'}
        ],
        'value': 'lightgray'
    }
).add_selection(my_selection)

# Apply the interval selection to the scatter plot
scatter = scatter.transform_filter(my_selection)

# Show the scatter plot
base + scatter

关键说明

  • 条件条目里必须用encoding来包裹完整的颜色编码规则,这样Altair才能识别基于字段的刻度和配色方案。
  • 未被条件匹配的点会使用value指定的浅灰色,符合你的初始需求。

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.07.17 05:07:41