简体   繁体   中英

Customize legend and color scale in interactive charts `altair`

I want an interactive chart, so I first define

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

Inside the encode() method the following works well:

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

But I'd rather use my own color palette and I do not want a legend . I can achieve this with the following.

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

But now I have no selection! Can I have them both?

To get a multi-selection, your own palette and no legend, simply specify all of these inside color().

Working Code

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
)

produces:

在此处输入图片说明

And if you click on any point, that whole species will get selected and colored according to the color condition. (Selected points assume color from the palette and the unselected ones are shown in grey.)

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM