Altair折线图中的工具提示

问题描述 投票:2回答:2

为折线图指定工具提示时,工具提示仅在沿着一条线悬停在点上时显示,而不是在沿线的任何其他位置悬停时显示。当使用非线性插值时,这尤其成问题...有没有办法在线本身上明确设置工具提示?

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'
)

enter image description here

python altair
2个回答
2
投票

我怀疑目前有直接的技术解决方案:-(

一种解决方法是在行顶部明确添加点,以便更容易悬停。我通常会让它们相对较大,但隐藏到悬停事件,如here作为顶部的樱桃,可以使用Voronoi来显示任何给定点的最近点,就像它们在这个tutorial中一样

让我知道如果你需要Altair代码示例,我使用原始vega,但实现Altair版本应该是相对琐碎的


1
投票

延伸@ Philipp_Kats的回答和@ dominik的评论(以及任何偶然发现这个帖子并希望看到Altair代码示例的人),当前实现“工具提示”效果的方法是:

  1. 创建线(mark_line()
  2. 创建一个选择最近点的选择并根据x值进行选择
  3. 在整个线上捕捉一些透明选择器,通知线的不同位置的x值
  4. 层(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

结果情节:

enter image description here

© www.soinside.com 2019 - 2024. All rights reserved.