有没有办法在 Altair 中的标记旁边显示标记的值

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

我正在研究 Altair Gallery 中的以下示例:

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

截至目前,显示实际计数的唯一方法似乎是通过工具提示,如示例所示。但是,我正在尝试编写一个静态可视化代码,如果准确的值显示在标记本身旁边,用户不必以任何方式悬停或交互,这将非常有帮助。有办法实现吗?

您可以通过手动计算文本标签的偏移量来做到这一点,尽管当点变得拥挤时这确实很困难:

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

Long-term,更好的解决方案是使用 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