解决此问题的最佳方法类似于Dynamically Change Y-Axis Field in Encoding Based on Selection Vega-Lite 中的 Vega-Lite 答案
选择不能过滤列标题,只能过滤列值。幸运的是,您可以使用fold transform 堆叠多个列并将这些列名转换为列值。
下面是一个折叠变换的例子,它结合一个选择框来选择要着色的列:
import altair as alt
import pandas as pd
import numpy as np
df = pd.DataFrame({
'x': np.random.randn(100),
'y': np.random.randn(100),
'c1': np.random.randint(0, 3, 100),
'c2': np.random.randint(0, 3, 100),
'c3': np.random.randint(0, 3, 100),
})
selector = alt.selection_single(
name='Color by',
fields=['column'],
bind=alt.binding_select(options=['c1', 'c2', 'c3']),
init={'column': 'c1'}
)
alt.Chart(df).transform_fold(
['c1', 'c2', 'c3'], as_=['column', 'value']
).transform_filter(
selector
).mark_point().encode(
x='x:Q',
y='y:Q',
color='value:Q',
column='column:N'
).add_selection(
selector
)
对于您的数据,它可能看起来像这样(尽管我无法对其进行测试,因为数据未包含在问题中)
selection = alt.selection_single(
fields=['column'],
bind=alt.binding_select(
name="Color by: ",
options=['Brand','Function','Category']
),
init={'column':'Function'}
)
alt.Chart(df_PCs).transform_fold(
["Brand", "Function", "Category"],
as_=['column', 'value']
).transform_filter(
selection
).mark_point().encode(
x="PC1:Q",
y="PC2:Q",
color="value:N",
column="column:N",
tooltip=['Name:N']
).add_selection(selection)