FoxRiver
FoxRiver

Reputation: 73

How to add legend to python altair

Can someone please help how to add legend for "Covid-19 Cases" and "Sales Volume" ? In the chart, red is "COVID-19 Cases" and blue is the "Sales Volume". Thanks in advance.

enter image description here

# Create the chart
chart1 = alt.Chart(df_county).mark_line(color='red').encode(
    x=alt.X('Date', title='Date'),
    y=alt.Y('Cases', title='COVID-19 Cases'))


chart2 = alt.Chart(df_county).mark_line(color='blue').encode(
    x=alt.X('Date', title='Date'),
    y=alt.Y('Sale Volume', title='Sale Volume'))

chart = chart1 + chart2

Upvotes: 4

Views: 11556

Answers (1)

eitanlees
eitanlees

Reputation: 1344

There is no way to add a legend without specifying an encoding that the legend will represent. The issue is discussed further here https://github.com/altair-viz/altair/issues/984

See Adding legend to layerd chart in altair for a similar question.

You can either use a Fold Transform if both values have the same units, or you could introduce a Dual Y Axis without a legend.

Upvotes: 2

Related Questions