簡體   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