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?
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.
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.
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.
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.
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.)
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With