在交互式图表 `altair` 中自定义图例和色标

Customize legend and color scale in interactive charts `altair`

我想要一个交互式图表,所以我先定义

click = selection_multi(fields=['species'])

encode() 方法中,以下方法运行良好:

color = condition(click, 
                  'species',
                  value('gray'))

但我宁愿使用我自己的颜色 palette 而我不想要 legend。我可以通过以下方式实现这一目标。

color = Color('species',
              scale=Scale(range=palette),
              legend=None)

但是现在我没有选择了!我可以同时拥有它们吗?

要获得多选、您自己的调色板且没有图例,只需在 color().

中指定所有这些即可

工作代码

import altair as alt
from vega_datasets import data
iris = data.iris()

click = alt.selection_multi(fields=['species'])
palette = alt.Scale(domain=['setosa', 'versicolor', 'virginica'],
                  range=['lightgreen', 'darkgreen', 'olive'])

alt.Chart(iris).mark_point().encode(
    x='petalWidth',
    y='petalLength',    
    color=alt.condition(click,
                        'species:N', alt.value('lightgray'), 
                        scale=palette,
                        legend=None)
).properties(
    selection=click
)

产生:

如果你点击任何一点,整个物种将被选中并根据颜色条件着色。 (选定的点采用 palette 的颜色,未选定的点显示为灰色。)