'Adding dynamic tooltip and title to Choropleth (with slider) in Altair

In a previous post, @jakevdp produced the very nice choropleth in Altair using a slider (pasted below for convenience):

import altair as alt
import pandas as pd
from vega_datasets import data

us_counties = alt.topo_feature(data.us_10m.url, 'counties')
fdf = pd.read_csv('https://raw.githubusercontent.com/sdasara95/Opioid-Crisis/master/sample_data.csv')
fdf['year'] = fdf['year'].astype(str)
fdf = fdf.pivot(index='fips', columns='year', values='Pill_per_pop').reset_index()
columns = [str(year) for year in range(2006, 2013)]

slider = alt.binding_range(min=2006, max=2012, step=1)
select_year = alt.selection_single(name="year", fields=['year'],
                                   bind=slider, init={'year': 2006})

alt.Chart(us_counties).mark_geoshape(
    stroke='black',
    strokeWidth=0.05
).project(
    type='albersUsa'
).transform_lookup(
    lookup='id',
    from_=alt.LookupData(fdf, 'fips', columns)
).transform_fold(
    columns, as_=['year', 'Pill_per_pop']
).transform_calculate(
    year='parseInt(datum.year)',
    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=alt.Scale(scheme='blues')),
        alt.value('#dbe9f6')
    )).add_selection(
    select_year
).properties(
    width=700,
    height=400
).transform_filter(
    select_year
)

I'm new to Altair, and wanted to understand how to make a few modifications to this plot:

  1. How can we add a title to this plot that varies with the slider value i.e. "Number of Pills in year {slider_value_here}"?
  2. How can we change the slider label to be customized to yr rather than the current year_year value?
  3. How can we add a hover tooltip to each county i.e. fips value, with the following values, {year: {slider_year_value}, fips: {fips_code_value_on_hover}, number_pills: {Pill_per_pop}}?
  4. How can we add an animation widget to this slider e.g. have a play button that automatically varies the slider value (where the timing can be controlled in the code)?

Any help with the modifications to this code would be extremely helpful. I did try inserting tooltip in various places to make query 3 work, but couldn't make it happen.

Any help appreciated



Solution 1:[1]

Thanks for including a clear and reproducible example! Just a heads up for the future that it can be a good idea to break your bullet points into separate question so that it is easier for others to find them when searching. I don't believe everything you want is achievable in Altair/Vegalite currently, but here is my best attempt at answering:

  1. How can we add a title to this plot that varies with the slider value i.e. "Number of Pills in year {slider_value_here}"?

    I found this comment mentioning that this is not possible for axis titles, so I would believe it is not possible for chart titles either (not sure though). An alternative approach would be to insert a small chart instead of a title and use mark_text to update the year, similar to this example

  2. How can we change the slider label to be customized to yr rather than the current year_year value?

    Set the name parameter in the binding_range instead of the selection_single, e.g. slider = alt.binding_range(name='yr ', min=2006, max=2012, step=1) (extra space for not having the slider right next to the name.

  3. How can we add a hover tooltip to each county i.e. fips value, with the following values, {year: {slider_year_value}, fips: {fips_code_value_on_hover}, number_pills: {Pill_per_pop}}?

    First change the lookup to also fetch the fips column:

     from_=alt.LookupData(fdf, 'fips', columns + ['fips'])
    

    Then pass a list to tooltip indicating the column types since they come from the lookup and are not in in the main dataframe you passed to the chart.

     tooltip=['year:O', 'fips:Q', 'Pill_per_pop:Q']
    
  4. How can we add an animation widget to this slider e.g. have a play button that automatically varies the slider value (where the timing can be controlled in the code)?

    Animations are not yet supported in vegalite

Sources

This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.

Source: Stack Overflow

Solution Source
Solution 1