Search code examples
pythonplotlygeojsonchoropleth

plotly choropleth not drawing any polygons


I have been following this https://plotly.com/python/choropleth-maps/ tutorial to draw a choropleth map of Australian suburbs. Using this https://github.com/tonywr71/GeoJson-Data/blob/master/australian-suburbs.geojson as the base geojson data, and then modifying it such that each feature has an 'id' property, which is the postcode for that feature. The final result looks like this: (available at https://github.com/meherGill/geojson_suburbs/blob/main/suburbsModified.geojson) enter image description here

The corresponding dataframe for this is
enter image description here

and the code to draw the map is

import plotly.express as px

with open('./data/suburbsModified.geojson') as f:
    jsondata = json.loads(f.read())

fig = px.choropleth(df2, geojson=jsondata, locations='Postal', color='Status', color_continuous_scale="Viridis")
fig.show()

But my figure looks like this, a map with nothing drawn on it. enter image description here

Why is it not drawing a choropleth map of australian suburbs as defined in the geojson file


Solution

    • fundamentally your issues are the fact your geojson is problematic. Viewing on GitHub shows that modified geojson does not overlay Australia
    • original geojson shows other issues, a few of the features have no geometry. Have used geopandas to filter this out
    • have synthesized df2 from the geojson so that your code could be used
    • approach I would recommend is using source geojson and supplementing postal code in data frame
    import requests
    import pandas as pd
    import numpy as np
    import plotly.express as px
    
    # original geojson
    url = "https://raw.githubusercontent.com/tonywr71/GeoJson-Data/master/australian-suburbs.geojson"
    # user's geojson
    url = "https://raw.githubusercontent.com/meherGill/geojson_suburbs/main/suburbsModified.geojson"
    fix = True
    
    # get geojson
    req = requests.get(url)
    jsondata = req.json()
    
    # well there is some invalid geomtry, exclude using geopandas
    if fix:
        gdf = gpd.GeoDataFrame.from_features(jsondata).set_index(
            pd.json_normalize(jsondata["features"])["id"]
        )
        jsondata = gdf.loc[~gdf.geometry.isna()].__geo_interface__
    
    # syntesize data frame
    df2 = pd.DataFrame({"Postal": pd.json_normalize(req.json()["features"])["id"]}).assign(
        Status=lambda d: np.random.randint(1, 400, len(d))
    )
    
    fig = px.choropleth(
        df2,
        geojson=jsondata,
        locations="Postal",
        color="Status",
        color_continuous_scale="Viridis",
    )
    fig.show()