简体   繁体   中英

Altair - how to use datum to format a tooltip

I am trying to format a tooltip using datum but, so far, without any success. The tooltip I need is the something like "INV: 174,000.00". How can I do it?

This is where I supposed to use datum:

text = line.mark_text(align='right', dx=-10, dy=-10).encode(
        text=alt.condition(nearest, f'Revenue:Q', alt.value(' '))
    ).transform_calculate(label='"INV: " + datum.Revenue')

Full code:

import altair as alt
from altair import datum
import pandas as pd
import numpy as np
import os



def areaChart():


    df = {
        'Stat': ['INV'],
        'Revenue': [474147.84, 2170326.05, 2184077.88, 3957965.97]
    }

    source = pd.DataFrame(np.cumsum(df, 0),
                        columns='Revenue', index=pd.RangeIndex(len(df['Stat']), name='Revenue'))
    print(source)
    source = source.reset_index().melt('Revenue', var_name='Analyzing', value_name='Revenue')

    nearest = alt.selection(type='single', nearest=True, on='mouseover',
                            fields=['Revenue'], empty='none')

    line = alt.Chart(source).mark_area(opacity=0.60).encode(
        x=alt.X(f'Stat:Q', axis=alt.AxisConfig()),
        y=f'Revenue:Q',
        color='Analyzing:N'
    )

    selectors = alt.Chart(source).mark_point().encode(
        x=f'Stat:Q',
        opacity=alt.value(0),
    ).add_selection(
        nearest
    )

    points = line.mark_point().encode(
        opacity=alt.condition(nearest, alt.value(1), alt.value(0))
    ).properties(
        title=f'Stat     x     INV'
    )

    text = line.mark_text(align='right', dx=-10, dy=-10).encode(
        text=alt.condition(nearest, f'Revenue:Q', alt.value(' '))
    ).transform_calculate(label='"INV: " + datum.Revenue')


    rules = alt.Chart(source).mark_rule(color='black', size=0.70).encode(
        x=f'Stat:Q',
    ).transform_filter(
        nearest
    )

    chart = alt.layer(
        line, selectors, points, rules, text
    )

    return chart

It looks like you are calculating the label, but never actually using it in an encoding. Try this instead:

text = line.mark_text(align='right', dx=-10, dy=-10).encode(
        text=alt.condition(nearest, 'label:N', alt.value(' '))
    ).transform_calculate(label='"INV: " + datum.Revenue')

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM