Plotlychoropleth_mapbox的GeoJSON问题
我通过创建 choropleth 地图的方法plotly似乎非常简单——加载到 DataFrame 中,加载到 geojson 中,将必要的特征分配给自定义多边形,然后绘制。
显然,在引用自定义多边形时在某处遗漏了一个步骤,因为在漫长的加载时间后只会出现一张空白地图。
需要注意的一件主要事情是,大约一半的多边形位于州内,但它们是州内的自定义多边形。因此,据我所知,choropleth_mapbox是更合适的解决方案。
图像示例,显示各州内的自定义多边形:
编码:
import pandas as pd
import plotly.express as px
import geopandas as gpd
from geojson import Polygon
import json
# reading in the dataframe
path = '/path/to/csv'
df = pd.read_csv(path)
geo_df = gpd.GeoDataFrame(df)
# reading in the geospatial data
with open('/path/to/geojson') as f:
geojson = json.load(f)
# create the plot
fig = px.choropleth_mapbox(geo_df[0:50], #slicing for quick loading
geojson=geojson,
color="MALL",
locations="MWS_ID",
featureidkey="properties.MWS_ID",
center={"lat": 39,
"lon": -95},
mapbox_style="carto-positron",
zoom=3)
fig.show()
输出:
显然数据缺失。
我认为问题出在 geojson 文件中。我能看到的关于 geojson 结构的唯一可能是我的 geojson 的坐标在两个括号中,而文档坐标中的 geojson 在三个括号中。
下面是我的 geojson。
{'type': 'FeatureCollection',
'features': [{'type': 'Feature',
'geometry': {'type': 'Polygon',
'coordinates': [[-89.299965, 36.508405],
[-89.414355, 36.499866],
[-89.424498, 36.476321],
.....
'properties': {'MWS_ID': 'TN_1'}},
{'type': 'Feature',
'geometry': {'type': 'Polygon',
'coordinates': [[-111.043999, 44.139903],
[-111.040171, 42.227952],
[-111.040773, 41.820698],
.....
下面是文档的 geojson
{'type': 'FeatureCollection',
'features': [{'type': 'Feature',
'geometry': {'type': 'MultiPolygon',
'coordinates': [[[[-73.6363215300962, 45.5759177646435],
[-73.6362833815582, 45.5758266113331],
.....
[-73.6363215300962, 45.5759177646435]]],
[[[-73.6561004885273, 45.5841347974261],
.....
[-73.6561004885273, 45.5841347974261]]]]},
'properties': {'district': '11-Sault-au-Récollet'},
'id': '11'},
{'type': 'Feature',
'geometry': {'type': 'Polygon',
'coordinates': [[[-73.6217484540132, 45.5544783077209],
[-73.6235005117779, 45.5536358848324],
[-73.6278096771011, 45.5513024018691],
这是我创建 geojson 的方法
# Create the GeoJSON
names_merged = names_1 + names_2
geoms_merged = geoms_1 + geoms_2
geojson = {'type':'FeatureCollection', 'features':[]}
for i in range(len(names_merged)):
feature = Feature(geometry=geoms_merged[i])
geojson['features'].append(feature)
geojson['features'][i]['properties']['MWS_ID'] = names_merged[i]
with open('/path/to/geojson', 'w') as f:
dump(geojson, f)
其中,names_merged 是str格式中的 MWS_ID 列表,geoms_merged 是格式中的多边形列表geojson.geometry.Polygon。
验证数据框和 geojson 具有相同的键。
print(geo_df['MWS_ID'][3])
print(geojson["features"][28]['properties']["MWS_ID"])
输出
AZ_2
AZ_2
但地图仍然是空白的。
感谢您对 SO 社区的持续帮助。