Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to do annotations with Altair?

I am trying to write some text inside the figure to highlight something in my plot (equivalent to 'annotate' in matplotlib). Any idea? Thanks

like image 726
Yiti Avatar asked Jun 20 '17 14:06

Yiti


1 Answers

You can get annotations into your Altair plots in two steps:

  1. Use mark_text() to specify the annotation's position, fontsize etc.
  2. Use transform_filter() from datum to select the points (data subset) that needs the annotation. Note the line from altair import datum.

Code:

import altair as alt
from vega_datasets import data
alt.renderers.enable('notebook')

from altair import datum #Needed for subsetting (transforming data)


iris = data.iris()

points = alt.Chart(iris).mark_point().encode(
    x='petalLength',
    y='petalWidth',
    color='species')

annotation = alt.Chart(iris).mark_text(
    align='left',
    baseline='middle',
    fontSize = 20,
    dx = 7
).encode(
    x='petalLength',
    y='petalWidth',
    text='petalLength'
).transform_filter(
    (datum.petalLength >= 5.1) & (datum.petalWidth < 1.6)
)


points + annotation

which produces: Annotations in an Altair Plot

These are static annotations. You can also get interactive annotations by binding selections to the plots.

like image 177
Ram Narasimhan Avatar answered Sep 23 '22 21:09

Ram Narasimhan