繁体   English   中英

在不使用大小/颜色的情况下将图例添加到线和条到 Altair 图表

[英]Add legend to line & bars to Altair chart without using size/color

我正在使用 Altair 创建一个包含多条线的图表,每条线都有多个波段(代表不同的 CI),我正在努力理解如何添加图例。 例如,在这个相当简单的例子中:

import altair as alt
import pandas as pd

df = pd.DataFrame(data={'col1': [1, 2,4,5,6], 'col2': [3, 4,7,4,4], 'col3': [1.5, 2.6,4.6,5.6,6.6], 'col4': [3.6, 4.6,7.6,4.6,4.4],'col5': [1.9, 2.9,4.9,5.9,6.9], 'col4': [3.9, 4.9,7.9,4.9,4.9]})


line = alt.Chart(df).mark_line(color='purple').encode(
    x=alt.X('col1', title='Day'),
    y=alt.Y('col2', title='Column 2')
)

band_90 = alt.Chart(df).mark_area(opacity=0.3, color='purple').encode(
    x=alt.X('col1', title='Day'),
    y='col3',
    y2='col4',
)

band_50 = alt.Chart(df).mark_area(opacity=0.2, color='purple').encode(
    x=alt.X('col1', title='Day'),
    y='col4',
    y2='col5',
)

alt.layer(
    line+band_90+band_50
).save('chart.html')

如何为线条和乐队添加图例? 我知道通常的方法是通过大小和颜色,但我使用的数据源和数据让我想尽可能这样做?

(请注意 - 乐队确实看起来很傻,这完全是假数据)

在 Altair/Vega-Lite 中向图表添加图例的唯一方法是添加将由图例表示的编码。 因此,您的问题“如何在不使用大小/颜色的情况下添加图例”的直接答案是您不能。

目前最好的方法是使用转换; 像这样的东西:

import altair as alt
import pandas as pd

df = pd.DataFrame(data={'col1': [1, 2,4,5,6], 'col2': [3, 4,7,4,4], 'col3': [1.5, 2.6,4.6,5.6,6.6], 'col4': [3.6, 4.6,7.6,4.6,4.4],'col5': [1.9, 2.9,4.9,5.9,6.9], 'col4': [3.9, 4.9,7.9,4.9,4.9]})


base = alt.Chart(df).transform_calculate(
    line="'line'",
    shade1="'shade1'",
    shade2="'shade2'",
)
scale = alt.Scale(domain=["line", "shade1", "shade2"], range=['red', 'lightblue', 'darkblue'])

line = base.mark_line(color='purple').encode(
    x=alt.X('col1', title='Day'),
    y=alt.Y('col2', title='Column 2'),
    color=alt.Color('line:N', scale=scale, title=''),
)

band_90 = base.mark_area(opacity=0.3, color='purple').encode(
    x=alt.X('col1', title='Day'),
    y='col3',
    y2='col4',
    color=alt.Color('shade1:N', scale=scale, title='')
)

band_50 = base.mark_area(opacity=0.2, color='purple').encode(
    x=alt.X('col1', title='Day'),
    y='col4',
    y2='col5',
    color=alt.Color('shade2:N', scale=scale, title='')
)

alt.layer(
    line+band_90+band_50
)

在此处输入图像描述

将来,当 Altair 支持 Vega-Lite 的 基准定义时,这种方法会不那么冗长。

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM