Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Customize legend and color scale in interactive charts `altair`

Tags:

python

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?

like image 245
Primo Petri Avatar asked May 20 '18 10:05

Primo Petri


People also ask

How do I change my Altair scale?

By default Altair uses a linear mapping between the domain values (MIC) and the range values (pixels). To get a better overview of the data, we can apply a different scale transformation. To change the scale type, we'll set the scale attribute, using the alt. Scale method and type parameter.

How do I change the color of my Altair chart?

Customizing Colors If you don't like the colors chosen by Altair for your scatter plot, you can customize the colors. The default colors can be changed using the scale argument of the Color class, By passing the Scale class to the scale argument.

How to remove legend in altair?

Another thing you can do is move the legend to another position with the orient argument. You can remove the legend entirely by submitting a null value.

Is Altair interactive?

Altair's interactivity and grammar of selections are one of its unique features among available plotting libraries. In this section, we will walk through the variety of selection types that are available, and begin to practice creating interactive charts and dashboards.


1 Answers

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:

enter image description here

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.)

like image 52
Ram Narasimhan Avatar answered Sep 25 '22 12:09

Ram Narasimhan