Reputation: 1135
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?
Upvotes: 2
Views: 2863
Reputation: 86310
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)
)
Upvotes: 3