Skip to content Skip to sidebar Skip to footer

Altair: Layered Line Chart With Legend And Custom Colors

I'm creating a layered line chart with 2 lines in Altair, each with a custom color. I want to add a legend to this. My original code, without the legend, looks like this: source =

Solution 1:

You can define a custom color scale like this:

scale = alt.Scale(domain=['FeatureOne', 'FeatureTwo'], range=['gold', 'red'])

Then pass this scale to one or both of the color encodings in your chart:

color=alt.Color('variable:N', scale=scale)

But note that if you're already using a fold transform, there's no reason to do the layering manually; this should work to draw both lines at once:

alt.Chart(source).mark_line().transform_fold(
    fold=['FeatureOne', 'FeatureTwo'], 
    as_=['variable', 'value']
).encode(
    x='Date:T', 
    y='value:Q',
    color=alt.Color('variable:N', scale=scale)
)

Post a Comment for "Altair: Layered Line Chart With Legend And Custom Colors"