为什么 Altair 条形图中最左边的条不符合选择画笔位置?

Why does the leftmost bar in an Altair Bar Chart not respect the selection brush location?

我根据合成数据创建了一个简单的条形图,在下面的代码中生成 (generate_dataframe)。该图像有一个带有数据的顶部图表和一个允许我沿水平轴拖动选择的下方图表。似乎有一个错误:最左边的条不受我在下图中选择的运动的影响。我使用 streamlit 来显示情节。这是正在发生的事情的图像。我在图片下方列出了代码。感谢您的任何建议。

Image produced when running the code, enhanced to illustrate the issue described above.

import streamlit as st
import pandas as pd
import altair as alt
import numpy.random as random

def generate_dataframe():
    nrows = 400
    name = [ 'n' + str(i) for i in range(300) ]
    names = random.choice(name, nrows)

    centrality = random.rand(nrows)
    multiplier = random.choice([.3, 1., 300.], nrows)
    centrality *= multiplier
    df = pd.DataFrame({'x':names, 'y':centrality})
    return df

df = generate_dataframe()
#----------------------------------

brush = alt.selection(type="interval", encodings=['x'])
axis = alt.Axis(labels=False)

base = alt.Chart(df, title="Base view").mark_bar().encode(
    x=alt.X('x:N', axis=axis),
    y='y:Q'
).add_selection(
    brush
).properties(
    width=850,
    height=50
)

zoomed = alt.Chart(df).mark_bar().encode(
    x=alt.X('x:N', scale=alt.Scale(domain=brush), axis=axis),
    y='y:Q'
).properties(
    width=850,
    height=400
)

chart = zoomed & base
st.altair_chart(chart)

Binding an interval selection to a scale's domain is currently not supported for ordinal and nominal domains. 解决方法是改用 .transform_filter(),因此请将您的代码更改为此,您将不再看到左侧的堆叠条:

zoomed = alt.Chart(df).mark_bar().encode(
    x=alt.X('x:N', axis=axis),
    y='y:Q'
).properties(
    width=850,
    height=400
).transform_filter(
    brush
)