Search code examples
pythonplotlyvisualizationgeospatialchoropleth

Choropleth map plotly python


I have a geo json file that gives data about political districts in PA (state in USA): api='https://www.redistricting.state.pa.us/Resources/GISData/Districts/Legislative/House/2021-Final/JSON/2022%20LRC-House-Final.json'

I have dataset that looks smth like this:

|   |District|Total Population|...|
|---|--------|----------------|---|
|0  |1       |35000           |...|
|1  |2       |67800           |...|
|2  |3       |93300           |...|
|...|...     |...             |...|

Json file and dataset can be connected by 'District' variable in both (df['District'] in dataset, and ['properties']['District'] in json)

I need to produce map that draws polygons of districts in PA based on coordinates given in json file in ['geometry'], and shows total population of those districts from the data given in df

Here is what I tried:

with urlopen(api) as response:
    geo = json.load(response) 
    
districts_geo=[]

for district in geo['features']:
    district_no=district['properties']['District']
    geometry=district['geometry']
    districts_geo.append({
        'type':'Feature',
        'geometry':geometry,
        'id':district_no
    })
    
districts_geo_ok={'type':'FeatureCollection','features':districts_geo}   

fig=px.choropleth(df, geojson=districts_geo_ok, scope='usa' ,locations='District', color='Total population')
fig.update_geos(fitbounds="locations", visible=False)
fig.show()

The problem is I am getting this wrong output: enter image description here


Solution

  • I tried running px.choropleth() with the geojson presented and the color bar shows up but the map does not. It is true that there may be an issue with the geojson, but I decided that it would be too difficult to lead it to the correct form, so I used a different map. px.choropleth_mapbox() was able to handle this issue. You are the one who should verify that the output fill area matches.

    from urllib import request
    import json
    import pandas as pd
    import numpy as np
    
    api='https://www.redistricting.state.pa.us/Resources/GISData/Districts/Legislative/House/2021-Final/JSON/2022%20LRC-House-Final.json'
    
    with request.urlopen(api) as f:
        geo = json.load(f)
    
    district = []
    for d in range(len(geo['features'])):
        dis = geo['features'][d]['properties']['District']
        district.append(dis)
    
    df = pd.DataFrame({'District': district, 'Total Population': np.random.randint(100, 10000, len(geo['features']))})
    
    import plotly.express as px
    
    fig = px.choropleth_mapbox(df, 
                               geojson=geo,
                               locations='District',
                               color='Total Population',
                               color_continuous_scale="Viridis",
                               range_color=(0, 10000),
                               mapbox_style="carto-positron",
                               zoom=6,
                               center={"lat": 41.0, "lon": -78.0},
                               opacity=0.3,
                               labels={'Total Population':'Population'}
                              )
    
    fig.update_layout(autosize=False, height=600, width=1000, margin={"r":0,"t":0,"l":0,"b":0})
    fig.show()
    

    enter image description here