Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Filtering to State Level for Choropleth Maps in Altair

I've been playing around with Altair's map functionality. I'm very easily able to build US maps with state and county boundaries now. What I'm stuck on is filtering the maps down to a lower level. For instance, if I wanted to build a map of only the state of Georgia with the county boundaries, how would I do that?

I have a solution, but it's a bad solution. Curious if there's a better way. Here is my code:

states_data = alt.topo_feature(data.us_10m.url, "states")
counties = alt.topo_feature(data.us_10m.url, 'counties')

states = alt.Chart(states_data).mark_geoshape(
        stroke='black',
        strokeWidth=1
    ).transform_filter((alt.datum.id == 13))

cobb = alt.Chart(counties).mark_geoshape(
        stroke='black',
        strokeWidth=1
    ).transform_filter((alt.datum.id == 13067))

fulton = alt.Chart(counties).mark_geoshape(
        stroke='black',
        strokeWidth=1
    ).transform_filter((alt.datum.id == 13121))

dekalb = alt.Chart(counties).mark_geoshape(
        stroke='black',
        strokeWidth=1
    ).transform_filter((alt.datum.id == 13089))

states + cobb + fulton + dekalb

This code gives me this result:

enter image description here

I'm using the very common Albers USA data to create the state boundaries and county boundaries. I've used "states" to project the state of Georgia and then I used "cobb", "fulton", and "dekalb" to project 3 different metro Atlanta counties on top of that.

This works, but it's extremely inefficient, and it would be a pain a huge pain to do this for all 159 counties in the state. Is there an easier way to filter the counties than the one I'm using? Or some good automated way to read in all 159 counties without 1,000+ lines of code!?

Edit: Also for the record, I tried doing the counties and then filtering by state, but that didn't work. Code is below:

states = alt.Chart(states_data).mark_geoshape(
        stroke='black',
        strokeWidth=1
    ).transform_filter((alt.datum.id == 13))

counties = alt.Chart(counties).mark_geoshape(
        stroke='black',
        strokeWidth=1
    ).project('albersUsa')

states + counties

That code seems to just do the full US county map.

enter image description here

like image 363
Ragnar Lothbrok Avatar asked Oct 27 '25 10:10

Ragnar Lothbrok


1 Answers

A bit strange way.

County id code starts with state id. With simple js trick you can extract it.

counties = alt.topo_feature(data.us_10m.url, 'counties')

map_georgia =(
    alt.Chart(data = counties)
    .mark_geoshape(
        stroke='black',
        strokeWidth=1
    )
    .transform_calculate(state_id = "(datum.id / 1000)|0")
    .transform_filter((alt.datum.state_id)==13)
)

map_georgia
    

enter image description here

like image 85
ilia timofeev Avatar answered Oct 28 '25 23:10

ilia timofeev