I am trying to write some text inside the figure to highlight something in my plot (equivalent to 'annotate' in matplotlib). Any idea? Thanks
Asked
Active
Viewed 8,448 times
1 Answers
9
You can get annotations into your Altair plots in two steps:
- Use
mark_text()
to specify the annotation's position, fontsize etc. - Use
transform_filter()
fromdatum
to select the points (data subset) that needs the annotation. Note the linefrom 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
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