gpt4 book ai didi

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

转载 作者:太空宇宙 更新时间:2023-11-03 15:35:05 24 4
gpt4 key购买 nike

我一直在研究 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/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com