在Altair中将图例拆分成多列

6

很抱歉无法提供大量代码,因为所有内容都是相互关联的,现在不可能。

我的问题是我创建了一个作为“交互式图例”的点图表。

legend = alt.Chart(source).mark_point().encode(
    y=alt.Y('STATE', axis=alt.Axis(orient='right')),
).add_selection(
    select_state
)

问题在于50个州都被列在了一起,导致图表变得非常长,无法在单个屏幕上显示。

  • 有没有办法将此图表以多列形式展示?但我认为这是不可能的,因为图例是一个单列点状图表。

  • 有没有办法将其转换为Altair中的某种结构,使其能够分成多列而不是图表?

enter image description here

或者,有没有办法重新定位我的滑块?它出现在底部,如果它出现在顶部,我认为它就能和其他所有内容一样出现在同一个屏幕上,因此图例图表就不会成为问题。

slider = alt.binding_range(min=1992, max=2016, step=1)
# 1st selection filter
select_year = alt.selection_single(name="YEAR", fields=['YEAR'],
                                   bind=slider, init={'YEAR': 1992})

enter image description here

2个回答

6
你可以指定编码的legend.columns属性来控制图例中列的数量。例如,使用汽车数据集:
import altair as alt
from vega_datasets import data

alt.Chart(data.cars.url).mark_point().encode(
    x='Horsepower:Q',
    y='Miles_per_Gallon:Q',
    color=alt.Color('Name:N', legend=alt.Legend(columns=8))
).properties(
    # Adjust chart width and height to match size of legend
    width=600,
    height=600
)

enter image description here

然而,由于有这么多属性,实际上传说并不是很有用。您可以考虑使用tooltip编码来显示此类详细信息。


2
嘿,谢谢这个有用的信息。我希望保持互动性,但从这个方式来看好像失去了。例如,在这个例子中 https://altair-viz.github.io/user_guide/interactions.html#selection-targets-fields-and-encodings 创建了一个小图表作为交互式图例,而这正是我最终想要的。 - Evan Kim
3
好的,我会尽力为您翻译以下内容:啊,我明白了……那不是传说,那是一张图表。我建议在您的“传说”图表中尝试添加x编码或列编码,以改变其布局方式。 - jakevdp
1
你能想到任何相关的例子,可以为我指明正确的方向,以便进行进一步的实验吗? - Evan Kim
检查一下这个例子:https://towardsdatascience.com/interactive-election-visualisations-with-altair-85c4c3a306f9 - Avinash

1

Check out this example:

import altair as alt
from vega_datasets import data

source = data.unemployment_across_industries.url

selection = alt.selection_multi(fields=['series'], bind='legend')

alt.Chart(source).mark_area().encode(
    alt.X('yearmonth(date):T', axis=alt.Axis(domain=False, format='%Y', tickSize=0)),
    alt.Y('sum(count):Q', stack='center', axis=None),
    alt.Color('series:N', scale=alt.Scale(scheme='category20b')),
    opacity=alt.condition(selection, alt.value(1), alt.value(0.2))
).add_selection(
selection
)

参考资料: https://altair-viz.github.io/gallery/interactive_legend.html


网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接