首页 > 解决方案 > 交互式 Altair 绘图轴上方的文本

问题描述

一段时间以来,我一直在遵循有关问题的建议,各种提示/信息放在我在 Altair 的地块上。但是,如果 Altair 绘图设置为 interactive(),则此建议不起作用 - 在我看来,启用比例绑定可防止任何绘图对象出现在矩形轴之外。

这是一个基于该链接的复制示例:比较生成的图有/没有最后注释的 interactive() 行。

    import altair as alt
    import pandas as pd
    import numpy as np

    df = pd.DataFrame({'x': np.linspace(0, 4, 1000)})
    df['y'] = np.sin(2 * np.pi * df['x'])

    select_point = alt.selection_single(fields=('x',), nearest=True, on='mouseover', empty='none')
    line = alt.Chart(df).mark_line().encode(
        x='x:Q',
        y='y:Q',
    )
    points = line.mark_point(filled=True, size=100).encode(
        opacity=alt.condition(select_point, alt.value(1.0), alt.value(0.0)),
    ).add_selection(select_point)
    text1 = alt.Chart(df, width=600, height=400).mark_text(
        align='left', baseline='bottom', dx=+5, fontSize=12,
    ).encode(
        x=alt.value(0.0),
        y=alt.value(-1),
        text='_label:N',
        opacity=alt.condition(select_point, alt.value(1.0), alt.value(0.0)),
    ).transform_calculate(
        _label='"ABOVE AXES x = " + format(datum.x, ".2f") + ", y = " + format(datum.y, ".2f")',
    )
    text2 = alt.Chart(df, width=600, height=400).mark_text(
        align='left', baseline='bottom', dx=+5, fontSize=12,
    ).encode(
        x=alt.value(0.0),
        y=alt.value(12),
        text='_label:N',
        opacity=alt.condition(select_point, alt.value(1.0), alt.value(0.0)),
    ).transform_calculate(
        _label='"INSIDE AXES x = " + format(datum.x, ".2f") + ", y = " + format(datum.y, ".2f")',
    )
    chart = alt.layer(line, points, text1, text2)
    # chart = chart.interactive()

互动关 互动开

附加信息,以防有帮助/相关:

底线问题:当绘图设置为交互式时,如何让文本出现在 Altair 的轴边界之外?

标签: pythonaltair

解决方案


传递clip=Falsemark_text(),文本将在轴外可见。

对于非绑定比例和绑定比例,该clip参数默认为。FalseTrue


推荐阅读