简体   繁体   中英

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 = df

line1 = alt.Chart(source).mark_line().encode(
    x='Date:T', 
    y='FeatureOne:Q', 
    color= alt.value('gold')
)

line2 = alt.Chart(source).mark_line().encode(
    x='Date:T', 
    y=alt.Y('FeatureTwo:Q', title='Value'), 
    color= alt.value('red')
)

line1 + line2

Here's the viz:

在此处输入图像描述

I wanted to add a legend to this and thankfully, there was a good answer on this previously.

However, what I can't figure out is how to use the legend, while also keeping the custom color. I can only do one or the other. Is there a way to do both? For instance, if I follow the code in the answer linked above, my code looks like this:

source = df

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

line2 = alt.Chart(source).mark_line().transform_fold(
    fold=['FeatureTwo'], 
    as_=['variable', 'value']
).encode(
    x='Date:T', 
    y=alt.Y('FeatureTwo:Q', title='Value'), 
#     color= alt.value('red')
    color='variable:N'
)

line1 + line2

That gives me a layered line chart with a legend, but I can't set the color of the lines. So it looks a bit like this:

在此处输入图像描述

How would I change this, so that I get my custom line colors in my 1st example:

color= alt.value('red')

While also doing the legend:

color='variable:N'

Is there a good way to do both at the same time?

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)
)

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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