如何从 Altair 中选定的数据中检索属性?

cry*_*ick 6 python altair

我有一个 Streamlit 仪表板,可让我使用 Altair 图以交互方式探索 t-SNE 嵌入。我试图弄清楚如何访问所选数据的元数据,以便我可以可视化相应的图像。换句话说,给定:

selector = alt.selection_single()
chart = (
    alt.Chart(df)
    .mark_circle()
    .encode(x="tSNE_dim1", y="tSNE_dim2", color="predicted class", tooltip=["image url", "predicted class"])
    .add_selection(selector)
)
Run Code Online (Sandbox Code Playgroud)

...有类似的东西吗

selected_metadata = selector.tooltip
update_dashboard_img(img=selected_metadata["image url"], caption=selected_metadata["predicted class"])
Run Code Online (Sandbox Code Playgroud)

我知道图像标记,但图像位于 S3 上,并且图像太多,无法融入情节中。

jak*_*vdp 5

不幸的是,Altair 没有提供任何机制将信息从 javascript 渲染传递回 Python 内核,因此通常无法执行您想要执行的操作。

(编辑:如果您使用他们的平台,streamlit 似乎有一个解决方案,但我不知道有任何普遍适用的解决方案)。


cry*_*ick 3

我不想不同意 Altair 的创建者的观点,但我能够使用 Streamlit-vega-lite 包来实现这一点。这是通过使用以下方式包装对图表创建函数的调用来实现的altair_component()

    from streamlit_vega_lite import altair_component
    ...

    event_dict = altair_component(altair_chart=create_tsne_chart(tsne_df))
    # note: works with selector = alt.selection_interval(), not selection_single()
    dim1_bounds, dim2_bounds = event_dict.get("dim1"), event_dict.get("dim2")
    if dim1_bounds:
        (dim1_min, dim1_max), (dim2_min, dim2_max) = dim1_bounds, dim2_bounds
        selected_images = tsne_df[
            (tsne_df.dim1 >= dim1_min)
            & (tsne_df.dim1 <= dim1_max)
            & (tsne_df.dim2 >= dim2_min)
            & (tsne_df.dim2 <= dim2_max)
        ]
        st.write("Selected Images")
        st.write(selected_images)

        if len(selected_images) > 0:
            for _index, row in selected_images.iterrows():
                img = get_img(row["image url"])
                st.image(img, caption=f"{row['image url']} {row['predicted class']}", use_column_width=True)
Run Code Online (Sandbox Code Playgroud)

唯一event_dict包含有关selector边界的信息。因此,您必须使用这些值来重新选择在交互式图表中选择的数据。

请注意,此包是 POC,有各种限制。请对 的作者创建的Streamlit 功能请求streamlit_vega_lite进行投票。

  • 感谢更新!然而,这似乎只适用于 Streamlit 的平台。所以不幸的是,我仍然认为这个问题没有任何通用的解决方案。 (4认同)