Search code examples
pythonplotlygeojson

Creating a plotly choropleth based on a geojson


Can't figure out why my code is not showing the geojson (just the basic map of the world).

What am I doing wrong?

geojson file is https://raw.githubusercontent.com/isellsoap/deutschlandGeoJSON/main/4_kreise/2_hoch.geo.json

import json
import pandas as pd

geoJSONFile = projectFolder+'geoJSON/DE-kreise.geo.json'
with open(geoJSONFile) as response:
    polygons = json.load(response)

df = pd.DataFrame([{'fips':1,'unemp':2.4,
                   'fips':2,'unemp':5.4,
                   'fips':3,'unemp':3.4,
                   'fips':4,'unemp':7.4,
                   'fips':5,'unemp':9.4,
                   'fips':6,'unemp':0.4,
                   'fips':7,'unemp':10.4,
                   'fips':8,'unemp':5.4}])

import plotly.express as px

fig = px.choropleth(df, geojson=polygons, locations='fips', color='unemp',
                           color_continuous_scale="Viridis",
                           range_color=(0, 12),
                           #scope="europe",
                           labels={'unemp':'unemployment rate'}
                          )
fig.update_layout(margin={"r":0,"t":0,"l":0,"b":0})
fig.show()

Solution

    • you have stated that geojson you want to use are regions in Germany based on shared URL in question
    • normally fips is used to identify an area in the US. I have still used it in construction of a dataframe that uses the ID_3 property in the geojson domain
    • the answer really is featureidkey argument. This defines the property in geojson that is used to match to the locations argument value
    • there was an issue with you dataframe construction, so I generated another one to make this example work
    import json
    import requests
    import pandas as pd
    import numpy as np
    import plotly.express as px
    
    
    # df = pd.read_csv("https://raw.githubusercontent.com/plotly/datasets/master/fips-unemp-16.csv",
    #                   dtype={"fips": int})
    polygons = requests.get(
        "https://raw.githubusercontent.com/isellsoap/deutschlandGeoJSON/main/4_kreise/2_hoch.geo.json"
    ).json()
    
    
    # generate some data for each region defined in geojson...
    df = pd.DataFrame(
        {"fips": range(1, 434, 1), "unemp": np.random.uniform(0.4, 10.4, 433)}
    )
    
    fig = px.choropleth(
        df,
        geojson=polygons,
        locations="fips",
        featureidkey="properties.ID_3",
        color="unemp",
        color_continuous_scale="Viridis",
        range_color=(0, 12),
        # scope="europe",
        labels={"unemp": "unemployment rate"},
    )
    fig.update_layout(margin={"r": 0, "t": 0, "l": 0, "b": 0})
    fig.update_geos(fitbounds="locations", visible=True)
    fig.show()
    

    enter image description here