Mauro
Mauro

Reputation: 105

Issue plotting GeoJSON with python's plotly cloropleth

I'm trying to plot from a geojson with the following structure:

import geopandas as gpd
states = gpd.read_file('diamante.geojson')
display(states.head())

enter image description here

This was obtained by converting from .shp, shx, prj, etc using mygeoconverter. The link column is my reference for merging with another dataframe later on with proper labels. The shape information seems fine as I get a basic plot from geopandas.

states.plot(aspect=1)

enter image description here

I do not know why i need the aspect=1 parameter in order for it to work. When trying to plot my map using plotly I get the following:

import pyproj
#states.to_crs(pyproj.CRS.from_epsg(4326), inplace=True)
fig = px.choropleth(states, geojson=states['geometry'], locations=states.index, color=states.varon)
fig.show()

enter image description here

The commented line was an attempt to solve the issue based on another post, which didn't seem to do anything. I am new to mapping so I don't know what to look for. Link to my geojson file.

Also, adding the following line from the documentation shows a blank graph.

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

Upvotes: 0

Views: 1359

Answers (1)

Rob Raymond
Rob Raymond

Reputation: 31236

  • you need to work out your CRS. Code below assumes that your polygons are expressed in UK UTM CRS system. This is the projected to WSG84 so that plotly can then work with it
  • your CRS has units in millions, so is not WSG84
  • without fitbounds I cannot find the geojson on the world map
import requests, json
import geopandas as gpd
import plotly.express as px

gdf = gpd.GeoDataFrame.from_features(requests.get("https://pastebin.com/raw/GwUsskWs").json()["features"])

gdf = gdf.set_crs("EPSG:32630").to_crs("EPSG:4326").set_index("link", drop=False)

fig = px.choropleth(gdf, geojson=json.loads(gdf.geometry.to_json()), locations="link", color="varon")
fig.update_geos(fitbounds="locations", visible=False)

enter image description here

Upvotes: 1

Related Questions