首页 > 解决方案 > 我的 topojson 文件的结构是否正确以便在 folium 上渲染地图?

问题描述

我从美国人口普查局下载了 us-counties shapefile,并使用 mapshaper.com 将其转换为 topojson 文件。不幸的是,我必须对 topojson 进行大量解析才能获得 FIPS 县代码。我正在使用 Folium 渲染地图,但不断出现错误。

我已经把我的数据框做成了一系列 FIPS_codes 和 $amounts。使用 style_function,我从 topojson 文件中调用 FIPS_codes,并将该值与系列进行比较以呈现美国县的地图。

import branca
colorscale = branca.colormap.linear.YlOrRd_09.scale(0, 50e3)
def style_function(feature):
    county_dict = cms_2017_grouped_series.get(
features['objects']['tl_2017_us_county']['geometries']['properties']['GEOID'], None)
    return {
        'fillOpacity': 0.5,
        'weight': 0,
        'fillColor': '#black' if employed is None else colorscale(employed)
    }

我得到的错误是AttributeError: 'list' object has no attribute 'get'

渲染地图所需的其余代码如下

m = folium.Map(
    location=[48, -102],
    tiles='cartodbpositron',
    zoom_start=3
)

folium.TopoJson(
    json.load(open(county_geo)),
    'objects.tl_2017_us_county.geometries.properties.GEOID',
    style_function=style_function
).add_to(m)

标签: topojsonfolium

解决方案


我按照您的步骤创建了 topojson 和好消息,它检查出来了。只需要用你的代码改变几件事

我首先创建了一些模拟用户数据。我正在使用 geopandas 和 topjson 文件来简化自己,但您只需使用包含县和就业人数的 pandas 数据框

import geopandas as gpd
gdf = gpd.read_file('tl_2017_us_county.json')

gdf['employed'] = np.random.randint(low=1, high=100000, size= len(gdf))

使用您的数据框创建一个系列。这将在样式函数中用于将您的数据“绑定”到地图

cms_2017_grouped_series = gdf.set_index('GEOID')['employed']
print(cms_2017_grouped_series.head())
GEOID
31039    54221
53069    68374
35011     8477
31109     2278
31129    40247
Name: employed, dtype: int64

这非常接近您的样式功能。我刚刚用 更改了行.get()以使用更正的 dict 键feature。哦,我在employed下面的 fillColor 中使用了返回值()

import branca
colorscale = branca.colormap.linear.YlOrRd_09.scale(0, 50e3)

def style_function(feature):

    employed = cms_2017_grouped_series.get(feature['properties']['GEOID'], None)

    return {
        'fillOpacity': 0.5,
        'weight': 0,
        'fillColor': '#black' if employed is None else colorscale(employed)
    }

object_path接下来是轻微的mod 。我还在保存地图,然后在 Chrome 中打开它,因为它不会在我的笔记本中呈现,因为它的大小

m = folium.Map(
    location=[48, -102],
    tiles='cartodbpositron',
    zoom_start=3
)
folium.TopoJson(open('tl_2017_us_county.json'), 'objects.tl_2017_us_county', 
                style_function=style_function).add_to(m)
m.save('map.html')

在此处输入图像描述


推荐阅读