如何在Altair中向行添加文本?

2024-10-02 14:15:59 发布

您现在位置:Python中文网/ 问答频道 /正文

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

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

我想添加“死亡每2天翻一番”和“每5天翻一番”的文字,如下面数据中的世界图表所示:

our world in data


Tags: valuelinecharttransformfoldaltencodecolor
1条回答
网友
1楼 · 发布于 2024-10-02 14:15:59

没有任何好的自动化方法可以做到这一点,因为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

enter image description here

一旦Altair4.2支持了新的数据编码,它将更加简洁

相关问题 更多 >

    热门问题