Plotting neighborhoods on choropleth map with a geojson

I have the following code which plots an empty map. It should plot all the different values on the different neighborhoods. The CSV-file used: Share/neighborhood_criminality.csv at main 路 RobertKiers/Share 路 GitHub

import plotly.graph_objects as go
import pandas as pd
import numpy as np
from urllib import request
import json

total_data = pd.read_csv('neighborhood_criminality.csv', delimiter=';')

def make_map(df, xcol, ycol):
    # Open geojson
    url='https://cartomap.github.io/nl/wgs84/buurt_2022.geojson'
    with request.urlopen(url) as f:
        jdata = json.load(f)
    
    # Define layout
    layout = go.Layout(
        margin={'l': 0, 'r': 0, 't': 0, 'b': 0},
        mapbox={
            'style': 'carto-positron',
            'center': {'lon': 5.7970, 'lat': 52.1500},
            'zoom': 6
        }
    )

    # Create figure
    fig = go.Figure(layout=layout)

    # Add choropleth trace
    fig.add_trace(go.Choroplethmapbox(
        geojson=jdata,
        locations = df[df.columns[0]].tolist(),
        z=df[ycol],
        colorscale='IceFire',
        colorbar=dict(
            title=ycol
        ),
        marker_opacity=0.7,
        marker_line_width=0.5,
        featureidkey='properties.statcode',
        hoverinfo= "location + z",
        customdata  = np.stack((df[xcol], df[ycol]), axis=-1),
        hovertemplate = ('<br><b>Neighborhood</b>: %{customdata[0]}<br>'+\
                        '<b>Value</b>: %{z}<br>')
    ))

    # Update geos
    fig.update_geos(fitbounds="locations", visible=False)

    # Show figure
    fig.show()

make_map(total_data, 'neighborhood_code', 'total_destruction')

Since we are specifying the municipality code as the location, I think we need to associate it with the statcode of the geojson property. So we need to specify 鈥榩roperties.statcode鈥 as the key to associate. I am commenting on a guess since no sample data is presented, so please replace it with your actual data. I have created sample data and created a map.

from urllib import request
import json
import plotly.graph_objects as go
import numpy as np
import pandas as pd

codes, names, values = [],[],[]
for i in range(len(jdata['features'])):
    stat_code = jdata['features'][i]['properties']['statcode']
    stat_name = jdata['features'][i]['properties']['statnaam']
    codes.append(stat_code)
    names.append(stat_name)
    values.append(np.random.randint(1000,10000))

df = pd.DataFrame({'statcode': codes, 'statnaam': names, 'value': values})

def maak_map(df, xcol, ycol):
    url='https://cartomap.github.io/nl/wgs84/gemeente_2022.geojson'
    with request.urlopen(url) as f:
        jdata = json.load(f)
    
    # Define layout
    layout = go.Layout(
        margin={'l': 0, 'r': 0, 't': 0, 'b': 0},
        mapbox={
            'style': 'carto-positron',
            'center': {'lon': 5.7970, 'lat': 52.1500},
            'zoom': 6
        }
    )

    # Create figure
    fig = go.Figure(layout=layout)

    # Add choropleth trace
    fig.add_trace(go.Choroplethmapbox(
        geojson=jdata,
        locations = df[df.columns[0]].tolist(),
        z=df[ycol],
        colorscale='IceFire',
        colorbar=dict(
            title=ycol
        ),
        marker_opacity=0.7,
        marker_line_width=0.01,
        featureidkey='properties.statcode',
        hoverinfo= "location + z",
        customdata  = np.stack((df[xcol], df[ycol]), axis=-1),
        hovertemplate = ('<br><b>Gemeente</b>: %{customdata[0]}<br>'+\
                        '<b>Waarde</b>: %{z}<br>')
    ))

    # Update geos
    fig.update_geos(fitbounds="locations", visible=False)

    # Show figure
    fig.show()
    
maak_map(df,'statcode','value')

1 Like

Hi. Thank you for the response. I couldn鈥檛 get it to work. I have updated my question with the CSV-file. Can you give any further help?

I have tried running it with the sample data provided and the modified geojson file, and it does indeed produce an error. First of all, the number of users does not match the number of geojson, I did not trace the javascript so I do not know the details, but I do not know if the error is caused by a mismatch between the number of user data and the number of geojson. There may also be a problem with the number of data. If you try to match the region code and geojson count as in my answer, and limit the data to total_data[:500], etc., it will show up.