awakenting
awakenting

Reputation: 173

Adding legend to layerd chart in altair

Consider the following example:

    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

In the resulting chart, I would like to add a legend that shows, that the blue line shows the maximum temperature and the red line the minimum temperature. What would be the easiest way to achieve this?

I saw (e.g. in the solution to this question: Labelling Layered Charts in Altair (Python)) that altair only adds a legend if in the encoding, you set the color or size or so, usually with a categorical column, but that is not possible here because I'm plotting the whole column and the label should be the column name (which is now shown in the y-axis label).

Upvotes: 3

Views: 13240

Answers (2)

S F
S F

Reputation: 13

If you layer two charts with the same columns and tell them to color by the same one, the legend will appear. Don't know is this helps but..

For example, i had:


Range, Amount, Type

0_5, 3, 'Private'

5_10, 5, 'Private'


Range, Amount, Type

0_5, 3, 'Public'

5_10, 5, 'Public'


and I charted both with 'color = 'Type'' and said alt.layer(chart1, chart2) and it showed me a proper legend

Upvotes: 0

eitanlees
eitanlees

Reputation: 1344

I would do a fold transform such that the variables could be encoded correctly.

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

Upvotes: 8

Related Questions