8

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

Trenton McKinney
  • 56,955
  • 33
  • 144
  • 158
Yiti
  • 281
  • 3
  • 9

1 Answers1

9

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.

Simon
  • 5,464
  • 6
  • 49
  • 85
Ram Narasimhan
  • 22,341
  • 5
  • 49
  • 55
  • How would you align all the text annotations at the bottom of the chart? – getup8 Oct 20 '18 at 04:08
  • You can add `.transform_calculate(petalWidth="0.2")` at the end of the annotation graph to set the petalWidth to 0.2 and be at the bottom of the graph. Note that this must be given as a string – FlorianGD Nov 06 '18 at 16:26