使用ONS GeoJSON数据的Choropleth映射错误(在python中使用plotly)

2024-04-20 04:56:43 发布

您现在位置:Python中文网/ 问答频道 /正文

我最近一直在研究如何使用Python在plotly上创建choropleth映射。我可以使用在internet上找到的GeoJSON文件(https://emilyshackleton1.carto.com/tables/uk_regions_map/public)来实现这一点

但是我接着在ONS GeoPortal上下载了一些GeoJSON文件, 然后,我尝试以完全相同的方式创建一个choropleth贴图,但它不起作用

代码:

import plotly.express as px
import pandas as pd
from urllib.request import urlopen
import json
with urlopen('https://opendata.arcgis.com/datasets/92ebeaf3caa8458ea467ec164baeefa4_0.geojson') as response:
    ons2 = json.load(response)

area={}
for feature in ons2["features"]:
    feature['id'] = feature["properties"]["objectid"]
    area[feature["properties"]["ctry19nm"]] = feature["id"]

df3 = pd.DataFrame((['Wales',6.7],
                    ['Scotland',4.6],
                   ['England',4.7],
                   ['Northern Ireland',4.1],
                   ),columns='fips B'.split())

df3["id"]=df3["fips"].apply(lambda x: area[x])

fig = px.choropleth(df3, locations="id", geojson=ons2["features"][1], color="B", scope = "europe", hover_name="fips")
fig.update_geos(fitbounds="locations", visible=False)
fig.show()

For some reason it is coloring the whole space and only Northern Ireland is showing.

奇怪的是,如果我把鼠标悬停在这张地图上,它仍然会显示出苏格兰、英格兰和威尔士应该在哪里

这让我抓狂,如果有任何帮助,我将不胜感激:)


Tags: 文件httpsimportcomidasgeojsonfig
1条回答
网友
1楼 · 发布于 2024-04-20 04:56:43

我用其他GeoJSON文件测试了您的代码,结果成功了。此外,GeoJSON文件没有任何错误,因此plotly库中可能存在错误

作为替代方案,我可以建议使用px.choropleth_mapbox()函数,它与px.choropleth()非常类似

import plotly.express as px
import pandas as pd
from urllib.request import urlopen
import json
with urlopen('https://opendata.arcgis.com/datasets/92ebeaf3caa8458ea467ec164baeefa4_0.geojson') as response:
    ons2 = json.load(response)

area={}
for feature in ons2["features"]:
    feature['id'] = feature["properties"]["objectid"]
    area[feature["properties"]["ctry19nm"]] = feature["id"]

df3 = pd.DataFrame((['Wales',6.7],
                    ['Scotland',4.6],
                   ['England',4.7],
                   ['Northern Ireland',4.1],
                   ),columns='fips B'.split())

df3["id"]=df3["fips"].apply(lambda x: area[x])
fig = px.choropleth_mapbox(df3, locations="id", featureidkey="properties.objectid", geojson=ons2, color="B", hover_name="fips", mapbox_style="white-bg", zoom=4, center = {"lat": 55, "lon": 0})

fig.show()

相关问题 更多 >