Search code examples
altair

Is there a way to keep the gradient scale constant in an dynamic Altair chart?


I have the following code in Altair which generates a dynamic chloropleth map:

columns = [str(year) for year in range(20200307, 20200331)]
slider = alt.binding_range(min=20200307, max=20200330, step=1)
select_date = alt.selection_single(name="date_num", fields=['date_num'],
                                   bind=slider, init={'date_num': 20200307})

alt.Chart(states).mark_geoshape(
    stroke='black',
    strokeWidth=0.05
).project(
    type='albersUsa'
).transform_lookup(
    lookup='id',
    from_=alt.LookupData(data_of_interest, 'id', columns)
).transform_fold(
    columns, as_=['date_num', 'case_to_pop_ratio']
).transform_calculate(
    date_num='parseInt(datum.date_num)',
    case_to_pop_ratio='datum.case_to_pop_ratio'  
).encode(
    color = alt.condition(
        'datum.case_to_pop_ratio > 0',
        alt.Color('case_to_pop_ratio:Q', scale=alt.Scale(scheme='lightgreyred')),
        alt.value('#dbe9f6')
    )
).add_selection(
    select_date
).properties(
    width=700,
    height=450
).transform_filter(
    select_date
).resolve_scale(
    color='shared'
)

However, the resulting chart changes the scale of the color gradient as I move through the slider, making the results very hard to interpret. Is there a way to keep the scale consistent?

My data file is too large to link, but it is formatted in the exact same way as this data file, from a separate Stack OverFlow question: https://github.com/sdasara95/Opioid-Crisis/blob/master/sample_data.csv


Solution

  • You can set a constant color range in Altair by adjusting the domain of the scale:

    import altair as alt
    from vega_datasets import data
    
    alt.Chart(data.cars.url).mark_point().encode(
        x='Acceleration:Q',
        y='Horsepower:Q',
        color=alt.Color('Acceleration:Q',scale=alt.Scale(domain=(1, 15))),
    )
    

    enter image description here