如何在 Altair 中的一行中添加文本?

How to add text to a line in Altair?

我想向这些参考行添加文本,以下是我使用的代码:

double2 = alt.Chart(source2).mark_line().transform_calculate(
    double2='5*pow(2,(datum.x/2))'
).transform_fold(
    ['double2']
).encode(
    x='x:Q',
    y=alt.Y('value:Q', scale=alt.Scale(type='log')),
    color=alt.value('lightgray')
)

source5 = alt.sequence(start=0, stop=28, step=1, as_='x')

double5 = alt.Chart(source5).mark_line().transform_calculate(
    double5='5*pow(2,(datum.x/5))'
).transform_fold(
    ['double5']
).encode(
    x='x:Q',
    y='value:Q',
    color=alt.value('lightgray')
)

double2 + double5

output

我想沿着 "deaths double every 2 days" 和 "every 5 days" 行添加文本,如下面我们的数据世界中的图表所示:

our world in data

没有任何好的自动化方法来执行此操作,因为 Vega-Lite 中的文本角度无法绑定到数据坐标。但是通过一些调整,您可以使用文本层来完成此操作:

import altair as alt

source2 = alt.sequence(start=0, stop=28, step=1, as_='x')

double2 = alt.Chart(source2).mark_line().transform_calculate(
    double2='5*pow(2,(datum.x/2))'
).transform_fold(
    ['double2']
).encode(
    x='x:Q',
    y=alt.Y('value:Q', scale=alt.Scale(type='log')),
    color=alt.value('lightgray')
)

source5 = alt.sequence(start=0, stop=28, step=1, as_='x')

double5 = alt.Chart(source5).mark_line().transform_calculate(
    double5='5*pow(2,(datum.x/5))'
).transform_fold(
    ['double5']
).encode(
    x='x:Q',
    y='value:Q',
    color=alt.value('lightgray')
)

text5 = alt.Chart({'values':[{'x': 20, 'y': 100}]}).mark_text(
    text='doubles every 5 days', angle=346
).encode(
    x='x:Q', y='y:Q'
)

text2 = alt.Chart({'values':[{'x': 20, 'y': 7000}]}).mark_text(
    text='doubles every 2 days', angle=327
).encode(
    x='x:Q', y='y:Q'
)

double2 + double5 + text2 + text5

一旦 Altair 4.2 支持新的数据编码,这将更清晰一些。