Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

like image 460
FoxRiver Avatar asked Oct 25 '25 13:10

FoxRiver


1 Answers

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.

like image 52
eitanlees Avatar answered Oct 27 '25 03:10

eitanlees



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!