Search code examples
pythonplotlygeopandas

Plotting a geopandas dataframe using plotly


I have a geopandas dataframe, which consists of the region name(District), the geometry column, and the amount column. My goal is to plot a choropleth map using the method mentioned below https://plotly.com/python/choropleth-maps/#using-geopandas-data-frames

Here’s a snippet of my dataframe

I also checked that my columns were in the right format/type.

enter image description here

And here's the code I used to plot the map

fig = px.choropleth(merged,

                   geojson=merged.geometry,

                   locations=merged.index,

                   color="Amount")

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

fig.show()

It produced the below figure

enter image description here

which is obviously not the right figure. For some reasons, it doesn't show the map, instead it shows a line and when I zoom in, I am able to see the map but it has lines running through it. Like this

enter image description here

Has anyone ran into a similar problem? If so how were you able to resolve it?

The Plotly version I am using is 4.7.0. I have tried upgrading to a most recent version but it still didn’t work.

Any help is greatly appreciated. Please find my code and the data on my github.


Solution

  • I'll give you the answer to @tgrandje's comment that solved the problem. Thanks to @Poopah and @tgrandje for the opportunity to raise the answer.

    import pandas as pd
    import plotly.express as px
    import geopandas as gpd
    import pyproj
    
    # reading in the shapefile
    fp = "./data/"
    map_df = gpd.read_file(fp)
    map_df.to_crs(pyproj.CRS.from_epsg(4326), inplace=True)
    
    df = pd.read_csv("./data/loans_amount.csv")
    # join the geodataframe with the cleaned up csv dataframe
    merged = map_df.set_index('District').join(df.set_index('District'))
    #merged = merged.reset_index()
    merged.head()
    
    fig = px.choropleth(merged, geojson=merged.geometry, locations=merged.index, color="Amount")
    fig.update_geos(fitbounds="locations", visible=False)
    
    fig.show()
    

    enter image description here