python - 在 Altair 中过滤到状态级别的 Choropleth map

标签 python gis choropleth vega-lite altair

我一直在研究 Altair 的 map 功能。我现在可以很容易地构建带有州和县边界的美国 map 。我坚持的是将 map 过滤到较低级别。例如,如果我想制作一张只有佐治亚州和县边界的 map ,我该怎么做?

我有一个解决方案,但这是一个糟糕的解决方案。好奇有没有更好的办法。这是我的代码:

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

这段代码给了我这个结果:

enter image description here

我使用的是非常常见的 Albers USA data创建州界和县界。我使用“states”来投影佐治亚州,然后我使用“cobb”、“fulton”和“dekalb”在其上投影 3 个不同的亚特兰大都会县。

这行得通,但效率极低,而且对该州的所有 159 个县执行此操作将是一个巨大的痛苦。有没有比我正在使用的方法更简单的方法来过滤县?或者无需 1,000 多行代码即可在所有 159 个县中阅读的一些很好的自动化方法!?

编辑:另外,为了记录,我尝试先处理县,然后按州过滤,但这没有用。代码如下:

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

该代码似乎只做完整的美国县 map 。

enter image description here

最佳答案

有点奇怪的方式。

县 ID 代码以州 ID 开头。使用简单的 js 技巧,您可以提取它。

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

关于python - 在 Altair 中过滤到状态级别的 Choropleth map ,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/55336762/

相关文章:

python - 告诉 Django Compressor 在编译时忽略某些目录

python - 有效地 merge python中的两个大字符串

python - Plotly:如何使用 plotly express 为具有多个组的条形图设置动画?

python - Django + PyMSQL + WSGI

javascript - 单击 Google map 时添加标记

r - 带单选按钮的 Shiny 无功值

javascript - 谷歌地图或其他服务获取指定范围内的地点列表?

python - 为什么 gdal_grid 会使图像上下颠倒?

r - geom_map "map_id"引用问题

python - 在 cartopy choropleth map 上添加值标签