Altair: Mark_rule legends with layered facets and another legend duplicate the legends

489 views Asked by At

I have a bar chart for NPS values with a gradient legend. I'd like to display some static values with a legended mark_rule simultaneously, and finally facet the results. However, I can't find a way to do this without duplicating the legends, or leaving out the gradient legend.

I'm not sure if this bug is related, it's similar but none of the examples are quite like mine: https://github.com/vega/vega-lite/issues/5996

Any help is greatly appreciated!

import pandas as pd
import altair as alt

df = pd.DataFrame({
    'Name': ['PlaceA', 'PlaceB', 'PlaceC', 'PlaceA', 'PlaceB', 'PlaceC', 'PlaceA', 'PlaceB', 'PlaceC'],
    'NPS': [58, 75, 100, 76, 80, 92, 90, 80, 72],
    'Month': [1, 1, 1, 2, 2, 2, 3, 3, 3],
    'Target': [75, 75, 75, 75, 75, 75, 75, 75, 75]
})

bars = alt.Chart(df).mark_bar().encode(
    y = alt.Y(
        'Month:N'
    ),
    x=alt.X(
        'NPS',
        axis=None
    ),
    color=alt.Color(
        'NPS',
        scale=alt.Scale(
            scheme='redyellowgreen',
            domain=[0, 100]
        ),
        legend=alt.Legend(
            title='NPS'
        )
    )
)

# All was fine with this setting, except for the missing legend
lines1 = alt.Chart(df).mark_rule(color='red').encode(
    x='Target'
)

# This otherwise optimal solution duplicates all the legends.
lines2 = alt.Chart(df).transform_fold(
    ['Target']
).mark_rule().encode(
    x='value:Q',
    color=alt.Color(
        'key:N',
        scale=alt.Scale(
            range=['red']
        ),
        legend=alt.Legend(
            title=None
        )
    )
)

# Most simple code for duplicating the legends.
lines3 = alt.Chart(df).mark_rule().encode(
    x='Target:Q',
    color='Target:N'
)

alt.layer(
    lines2, bars, width=200
).facet(
    facet=alt.Facet(
        'Name:N',
        title=None
    ),
    columns=3
)
0

There are 0 answers