import altair as alt
from vega_datasets import data
import panel as pn
pn.extension('vega')
A simple example demonstrating how to use a reactive function depending on a single widget, to render Altair/Vega plots. In this case the Select
widget allows selecting between various quantities that can be plotted on a choropleth map.
altair_logo = 'https://altair-viz.github.io/_static/altair-logo-light.png'
states = alt.topo_feature(data.us_10m.url, 'states')
states['url'] = 'https://raw.githubusercontent.com/vega/vega/master/docs/data/us-10m.json'
source = 'https://raw.githubusercontent.com/vega/vega/master/docs/data/population_engineers_hurricanes.csv'
variable_list = ['population', 'engineers', 'hurricanes']
def get_map(variable):
return alt.Chart(states).mark_geoshape().encode(
alt.Color(variable, type='quantitative')
).transform_lookup(
lookup='id',
from_=alt.LookupData(source, 'id', [variable])
).properties(
width="container",
height=300,
).project(
type='albersUsa'
).repeat(
row=[variable]
)
variable = pn.widgets.Select(options=variable_list, name='Variable', width=250)
logo = pn.panel(altair_logo, height=150, align="center")
vega_panel = pn.pane.Vega(sizing_mode="stretch_width", margin=(10,100,10,5))
@pn.depends(variable.param.value, watch=True)
def update_vega_pane(variable):
vega_panel.object = get_map(variable)
update_vega_pane(variable.value)
pn.Row(
pn.Column('# Altair Choropleth Maps', logo, variable),
vega_panel
)
Lets wrap it into nice template that can be served via panel serve altair_chropleth.ipynb
pn.template.FastListTemplate(
site="Panel",
title="Altair Choropleth Maps",
sidebar=[logo, variable],
main=["A simple example demonstrating **how to use a *reactive function* depending on a single widget**, to render Altair/Vega plots.", vega_panel]
).servable();