Black Lives Matter. Please consider donating to Black Girls Code today.

Custom GeoJson Issue: drawing boundary of last value and colouring all the plot with same colour

Hello,

When I try to plot a plotly express choropleth map, I get a problem when plotly loads my custom GeoJson (I am pulling this form th UK’s official open data portal (see link in code snippet below)

Here is my code and I have attached the dummy dataset I am using.

The problem is that I see that the data is showing when I hover and only one of the boundaries have been drawn. The rest of the screen seems to have been filled by the values.

import pandas as pd
import plotly
import numpy as np


from urllib.request import urlopen
import json
with urlopen('https://opendata.arcgis.com/datasets/c572ffec290b42768f80e43d31ac53a6_0.geojson') as response:
    counties = json.load(response)
    
df = pd.read_excel('testdata.xlsx',dtype={"cty19cd": str})
df.columns=['CODE','NAME','VALUE']

import plotly.express as px

fig = px.choropleth(df, geojson=counties, locations='CODE', featureidkey="properties.cty19cd", color='VALUE',
                           color_continuous_scale="Inferno",
                            scope="europe")

fig.update_geos( fitbounds="locations", visible=True)
fig.write_html('maptest.html',auto_open=True)

I have researched the web about the problem I am having. I found that the problem might be related to the incompatibility of the current GEOJSON standard and the D3 library that pltly uses under the hood, as discussed here.

Has anybody found a way to make plotly work with this uncompatible GeoJSONS?

Thanks!

It looks like a similar issue I ran into. I was able to fix this by reversing the polygons into clockwise order.

I’m sure there are plenty of ways to do this, but my method was to use Mapshaper and adding the gj2008 flag to the -o command.

Hello,

Found the answer. I am going to put it here in case it helps people that encounter the same mistake.

There is a library called geojson_rewind that will let you “rewind” the GeoJson to the proper clockwise/counterclockwise direction.

The parameter rfc7946=False will ignore the current GeoJson specifications (see details here https://geojson.org/) and use the previous 2008 version, which was clockwise

from geojson_rewind import rewind

#Load geo json
with urlopen('https://opendata.arcgis.com/datasets/48b6b85bb7ea43699ee85f4ecd12fd36_4.geojson') as response:
    counties = json.load(response)

counties_corrected=rewind(counties,rfc7946=False)

Then you can use that counties_corrected in the Plotly graph