在Altair中为分层图添加图例

3
考虑以下例子:
    import altair as alt
    from vega_datasets import data

    df = data.seattle_weather()

    temp_max = alt.Chart(df).mark_line(color='blue').encode(
        x='yearmonth(date):T',
        y='max(temp_max)',
    )

    temp_min = alt.Chart(df).mark_line(color='red').encode(
        x='yearmonth(date):T',
        y='max(temp_min)',
    )

    temp_max + temp_min

在生成的图表中,我想添加一个图例,显示蓝线表示最高温度,红线表示最低温度。最简单的方法是什么?
我看到(例如在这个问题的解决方案中:Labelling Layered Charts in Altair (Python)),altair只有在编码中设置了颜色或大小等属性时才会添加图例,通常使用分类列,但在这里不可能,因为我正在绘制整个列,标签应该是列名(现在显示在y轴标签中)。
2个回答

8
我会进行折叠变换(fold transform),以便正确编码变量。
import altair as alt
from vega_datasets import data

df = data.seattle_weather()

alt.Chart(df).mark_line().transform_fold(
    fold=['temp_max', 'temp_min'], 
    as_=['variable', 'value']
).encode(
    x='yearmonth(date):T',
    y='max(value):Q',
    color='variable:N'
)

enter image description here


1
可以使用分层图表来实现这个吗?当数据在同一个数据框中时,建议的方法是可行的,但并非总是如此。 - undefined
@Karim 没有办法在不指定图例所代表的编码的情况下添加一个图例。该问题在这里进一步讨论:https://github.com/altair-viz/altair/issues/984 - undefined

0
如果您将两个具有相同列的图表叠加,并告诉它们按照相同的列进行着色,那么图例将会出现。不知道这是否有帮助,但是...
例如,我有:
范围,数量,类型
0_5,3,'私有'
5_10,5,'私有'

范围,数量,类型

0_5,3,'公共'

5_10,5,'公共'


我用 'color = 'Type'' 绘制了两个图表,并使用 alt.layer(chart1, chart2) 进行叠加,它显示了一个正确的图例。


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