[英]How to plot a Plotly Choropleth map with English local authorities using GeoJSON
[英]Choropleth Map Error (using plotly in python) Using ONS GeoJSON data
我最近一直在研究使用 Python 在 plotly 上創建等值線圖。 我能夠使用我在互聯網上找到的 GeoJSON 文件(https://emilyshackleton1.carto.com/tables/uk_regions_map/public )來做到這一點
但是,我隨后在 ONS GeoPortal 上下載了一些 GeoJSON 文件,然后嘗試以完全相同的方式創建一個 choropleth map,但它不起作用
代碼:
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()
奇怪的是,如果我在這個 map 上使用 hover 它仍然會出現蘇格蘭、英格蘭和威爾士應該在的地方
這一直讓我發瘋,將不勝感激任何幫助:)
我用其他 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()
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.