C. Braun
C. Braun

Reputation: 5201

Format Altair choropleth map color scale

I am trying to encode percentage with a color scale on a choropleth map. How can I format the scale to show percent values (ex. 10%) rather than fraction values (ex. 0.1)? I know for a regular X or Y axis you could do axis=alt.Axis(format='.0%'), but I can't see how to use formatting for this color scale.

import altair as alt
import pandas as pd
from vega_datasets import data
alt.renderers.enable('notebook')

airports = pd.read_csv(data.airports.url)
airports = airports.groupby('state').agg({'iata': 'count'})
airports['id'] = range(1, len(airports) + 1)
airports['pct'] = airports['iata'] / airports['iata'].sum()

states = alt.topo_feature(data.us_10m.url, feature='states')

alt.Chart(states).mark_geoshape().encode(
    color='pct:Q'
).transform_lookup(
    lookup='id',
    from_=alt.LookupData(airports, 'id', ['pct'])
).project('albersUsa')

enter image description here

Upvotes: 3

Views: 1349

Answers (1)

jakevdp
jakevdp

Reputation: 86328

The legend attribute of the color encoding accepts a format argument that controls the format of the legend's scale:

alt.Chart(states).mark_geoshape().encode(
    color=alt.Color('pct:Q', legend=alt.Legend(format=".0%"))
).transform_lookup(
    lookup='id',
    from_=alt.LookupData(airports, 'id', ['pct'])
).project('albersUsa')

enter image description here

More info in the alt.Legend documentation.

Upvotes: 4

Related Questions