Search code examples
python-3.xvegaaltairvega-lite

Alt condition not working for choropleth missing values N.A


I am plotting a choropleth where I am using the color scheme "blues"
I want a default color for counties where I don't have any data i.e. N.A.
The default color has hex-code: #dbe9f6
I am using alt condition for this but it is not working.

Here is my code:

from altair import Scale,Color

fg = alt.Chart(us_counties).mark_geoshape(
stroke='black',
strokeWidth=0.05
).project(
    type='albersUsa'
).transform_lookup(
    lookup='id',
    from_=alt.LookupData(fdf1, 'fips', ['Pill_per_pop'])
).encode(
    color = alt.condition('datum.Pill_per_pop!==null',Color('Pill_per_pop:Q',scale=Scale(scheme='blues')),alt.value('#dbe9f6'))
).properties(
    width=700,
    height=400
)

My output is : Generated Output

Expected output is : Expected Output


Solution

  • I'm not sure why, but it seems like the null values are breaking the conditional encoding. I was able to get it working by using a calculate transform to turn nulls into negative numbers, and then conditioning on this instead:

    alt.Chart(us_counties).mark_geoshape(
        stroke='black',
        strokeWidth=0.05
    ).project(
        type='albersUsa'
    ).transform_lookup(
        lookup='id',
        from_=alt.LookupData(fdf1, 'fips', ['Pill_per_pop'])
    ).transform_calculate(
        Pill_per_pop='isValid(datum.Pill_per_pop) ? datum.Pill_per_pop : -1'  
    ).encode(
        color = alt.condition(
            'datum.Pill_per_pop > 0',
            alt.Color('Pill_per_pop:Q', scale=Scale(scheme='blues')),
            alt.value('#dbe9f6')
        )
    ).properties(
        width=700,
        height=400
    )