Streamlit `altair_chart` 图表不可交互

Streamlit `altair_chart` chart not interactive

我正在尝试绘制一个交互式财务图表,但当我使用 st.altair_chart 时它不会变为动态(altair 图表的默认设置)。这是代码:

base = alt.Chart(df).encode(
    alt.X('Date:T', axis=alt.Axis(labelAngle=-45)),
    color=alt.condition("datum.Open <= datum.Close",
                        alt.value("#06982d"), alt.value("#ae1325"))
)

rule = base.mark_rule().encode(alt.Y('Low:Q', title='Price',
                                        scale=alt.Scale(zero=False)), alt.Y2('High:Q'))
bar = base.mark_bar().encode(alt.Y('Open:Q'), alt.Y2('Close:Q'))
st.altair_chart(rule + bar, use_container_width=True)

这段代码的结果如下:

(供参考,original题)

基本上,您必须显式地对标记进行分层并调用 .interactive() 以使轴交互:

base = alt.Chart(df).encode(
    alt.X('Date:T', axis=alt.Axis(labelAngle=-45)),
    color=alt.condition("datum.Open <= datum.Close",
                        alt.value("#06982d"), alt.value("#ae1325"))
)

chart = alt.layer(
    base.mark_rule().encode(alt.Y('Low:Q', title='Price',
                                    scale=alt.Scale(zero=False)), alt.Y2('High:Q')),
    base.mark_bar().encode(alt.Y('Open:Q'), alt.Y2('Close:Q')),
).interactive()
st.altair_chart(chart, use_container_width=True)