如何使用 Altair 进行注释?

Yit*_*iti 6 python text annotate altair

我试图在图中写一些文本以突出显示我的情节中的某些内容(相当于 matplotlib 中的“注释”)。任何的想法?谢谢

Ram*_*han 6

您可以通过两个步骤在 Altair 图中获得注释:

  1. 使用mark_text()指定标注的位置,字体大小等。
  2. 使用transform_filter()来自datum选择需要注释的点(数据子集)。注意行from altair import datum.

代码:

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
Run Code Online (Sandbox Code Playgroud)

它产生: Altair 图中的注释

这些是静态注释。您还可以通过绑定selections到绘图来获得交互式注释。