2 回答

TA貢獻(xiàn)1884條經(jīng)驗(yàn) 獲得超4個(gè)贊
從@Philipp_Kats 的回答和@dominik 的評(píng)論(以及偶然發(fā)現(xiàn)此線程并希望查看 Altair 代碼示例的其他任何人)擴(kuò)展,當(dāng)前實(shí)現(xiàn)“工具提示”效果的方法是:
創(chuàng)建線 (
mark_line()
)創(chuàng)建一個(gè)選擇最近的點(diǎn)并根據(jù) x 值進(jìn)行選擇的選擇
跨行捕捉一些透明選擇器,通知跨行不同位置的 x 值
mark_text()
上面 1 - 3層的 ( )層
一個(gè)真實(shí)的例子是我制作的一個(gè)簡單 Flask 應(yīng)用程序上的折線圖。唯一的區(qū)別是我沒有將選擇器設(shè)置為透明 ( opacity=alt.value(0)
),否則它是一個(gè)折線圖,上面有工具提示。
這是一個(gè)使用 OP 原始數(shù)據(jù)集的可重現(xiàn)示例:
# Step 1: create the line
line = alt.Chart().mark_line(interpolate="basis").encode(
x=alt.X("year:O"),
y=alt.Y("perc:Q", axis=alt.Axis(format='%')),
color='sex:N'
).transform_filter(
alt.datum.job == 'Welder'
)
# Step 2: Selection that chooses nearest point based on value on x-axis
nearest = alt.selection(type='single', nearest=True, on='mouseover',
fields=['year'])
# Step 3: Transparent selectors across the chart. This is what tells us
# the x-value of the cursor
selectors = alt.Chart().mark_point().encode(
x="year:O",
opacity=alt.value(0),
).add_selection(
nearest
)
# Step 4: Add text, show values in Sex column when it's the nearest point to
# mouseover, else show blank
text = line.mark_text(align='left', dx=3, dy=-3).encode(
text=alt.condition(nearest, 'sex:N', alt.value(' '))
)
# Layer them all together
chart = alt.layer(line, selectors, text, data=source, width=300)
chart
結(jié)果圖:
添加回答
舉報(bào)