Search code examples
altair

Is there a way to display the value of a mark next to the mark in Altair


I was playing around with the following example from the Altair Gallery:

https://altair-viz.github.io/gallery/airports_count.html

As of right now, the only way to display the actual count appears to be via the tooltip, as the example shows. However, I am trying to code a static visualization for which it would be very helpful if the exact value was displayed right next to the mark itself, without the user having to hover or interact in any way. Is there a way to achieve this?


Solution

  • You can do this by manually calculating offsets for text labels, though this is admittedly difficult when the points become crowded:

    import altair as alt
    from vega_datasets import data
    
    airports = data.airports.url
    states = alt.topo_feature(data.us_10m.url, feature='states')
    
    # US states background
    background = alt.Chart(states).mark_geoshape(
        fill='lightgray',
        stroke='white'
    ).properties(
        width=500,
        height=300
    ).project('albersUsa')
    
    # airport positions on background
    base = alt.Chart(airports).transform_aggregate(
        latitude='mean(latitude)',
        longitude='mean(longitude)',
        count='count()',
        groupby=['state']
    ).encode(
        longitude='longitude:Q',
        latitude='latitude:Q',
    )
    
    points = base.mark_circle().encode(
        size=alt.Size('count:Q', title='Number of Airports'),
        color=alt.value('steelblue'),
        tooltip=['state:N','count:Q']
    ).properties(
        title='Number of airports in US'
    )
    
    text = base.mark_text(
        dx=15, dy=10
    ).encode(
        text='count:Q'
    )
    
    background + points + text
    

    enter image description here

    Long-term, a better solution will be to use vega-label, which will be able to do this automatically once it's part of the Vega-Lite package. For Altair, this feature is tracked in this bug: https://github.com/altair-viz/altair/issues/1731