为折线图指定工具提示时,工具提示仅在沿着一条线悬停在点上时显示,而不是在沿线的任何其他位置悬停时显示。当使用非线性插值时,这尤其成问题...有没有办法在线本身上明确设置工具提示?
import altair as alt
from vega_datasets import data
source = data.jobs.url
alt.Chart(source).mark_line(interpolate="basis").encode(
alt.X('year:O'),
alt.Y('perc:Q', axis=alt.Axis(format='%')),
color='sex:N',
tooltip='sex:N'
).properties(
title='Percent of work-force working as Welders'
).transform_filter(
alt.datum.job == 'Welder'
)
延伸@ Philipp_Kats的回答和@ dominik的评论(以及任何偶然发现这个帖子并希望看到Altair代码示例的人),当前实现“工具提示”效果的方法是:
mark_line()
)mark_text()
)在上面的1 - 3之上一个真实的例子就是这个line chart on a simple Flask app I made。唯一的区别是我没有使选择器透明(opacity=alt.value(0)
),但是否则它是一个折叠有工具提示的折线图。
这是使用OP原始数据集的可重现示例:
# 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
结果情节: