如何用Altair做注释?

时间:2017-06-20 14:40:02

标签: python text annotate altair

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

1 个答案:

答案 0 :(得分:1)

您可以通过两个步骤获取Altair图注释:

  1. 使用mark_text()指定注释的位置,fontsize等。
  2. 使用trasform_filter()中的datum 选择需要注释的点(数据子集)。请注意第from altair import datum.
  3. 代码:

    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
    

    产生: Annotations in an Altair Plot

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