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

时间:2018-05-20 10:25:03

标签: python altair

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

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

encode()方法中,以下效果很好:

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

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

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

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

1 个答案:

答案 0 :(得分:4)

要获得多项选择,您自己的调色板和没有图例,只需在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
)

产生

enter image description here

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