Reputation: 3
I have recently been looking into creating choropleth maps on plotly using Python. I was able to do this using a GeoJSON file I found on the internet (https://emilyshackleton1.carto.com/tables/uk_regions_map/public)
However I then went on the ONS GeoPortal and downloaded some GeoJSON files, I then tried to create a choropleth map in the exact same manner, and it wouldn't work
Code:
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.
The weird thing is if I hover over this map it still comes up with Scotland, England and Wales where they should be
This has been driving me crazy, would appreciate any help :)
Upvotes: 0
Views: 782
Reputation: 2826
I tested your code with other GeoJSON files and it worked. Also your GeoJSON file does not have any errors, so there is likely a bug in the plotly library.
As an alternative, I can recommend to use the px.choropleth_mapbox()
function which is quite similar to 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()
Upvotes: 1