我今天开始与Altair一起玩,对选择有疑问。我创建了3个不同颜色的条形图,如下所示。现在,每当我单击一个条形图时,我都希望在其他两个条形图中突出显示该条形图。如果我不使用任何颜色,并且默认为蓝色,则效果很好,但是我不知道如何将颜色保留在选择中,而不是对所有三个图表使用相同的颜色。
df = pd.DataFrame({"Name":["Bulbasaur", "Charizard", "Mewtwo"],
"HP":[45, 80, 100],
"Attack":[30, 50, 60],
"Defense":[40, 38, 42],
"Type":["Grass", "Fire", "Psychic"]})
selection = alt.selection_single(fields=["Type 1"])
# This doesn't do much as I don't have a column named #73a1eb. But it's the colour code I'd like to use.
color1 = alt.condition(selection,
alt.Color("#73a1eb:N", legend=None),
alt.value('lightgray'))
color2 = alt.condition(selection,
alt.Color("#73b9c7:N", legend=None),
alt.value('lightgray'))
color3 = alt.condition(selection,
alt.Color("#d7abf5:N", legend=None),
alt.value('lightgray'))
# The mark bar colour is overriden by color in encode
chart1 = alt.Chart(df, title="Average HP by Type")
.mark_bar(color="#73a1eb", size = 12)
.encode(x = 'mean(HP):Q',
y = alt.Y('Type 1:N', sort='-x'),
tooltip=["Type 1", "mean(HP):Q"],
color=color1)
.properties(height=320,
width=300)
.add_selection(selection)
chart2 = alt.Chart(df, title="Average Attack by Type")
.mark_bar(color="#73a1eb", size = 12)
.encode(x = 'mean(Attack):Q',
y = alt.Y('Type 1:N', sort='-x'),
tooltip=["Type 1", "mean(HP):Q"],
color=color1)
.properties(height=320,
width=300)
.add_selection(selection)
chart2 = alt.Chart(df, title="Average Defense by Type")
.mark_bar(color="#73a1eb", size = 12)
.encode(x = 'mean(Defense):Q',
y = alt.Y('Type 1:N', sort='-x'),
tooltip=["Type 1", "mean(HP):Q"],
color=color1)
.properties(height=320,
width=300)
.add_selection(selection)
alt.hconcat(chart1, chart2, chart3).configure_axis(grid=False).configure_axisBottom().resolve_scale(x = 'shared')
答案 0 :(得分:1)
在编写alt.Color("#73a1eb:N")
时,这意味着您希望根据名为"#73a1eb"
的具有名义("N"
)类型的列对颜色进行编码。
似乎您要指定颜色值而不是颜色编码,在这种情况下,您可以编写alt.value("#73a1eb")
。因此您的情况将如下所示:
color1 = alt.condition(selection,
alt.value("#73a1eb"),
alt.value('lightgray'))