在Altair中将图例分成多列

时间:2019-06-25 16:59:37

标签: python altair

很抱歉,无法提供大量代码,所有内容都已互连,目前无法实现。

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

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 个答案:

答案 0 :(得分:1)

您可以指定编码的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编码来显示这样的详细信息。

答案 1 :(得分:1)

查看以下示例:

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