Reputation: 121
I am trying to create a choropleth using plotly.express
. The figure is able to load, but it only shows one color. I can mouse over each feature and it displays the relevant information, but not in variable color. This implies that it is reading the geojson but not displaying properly. u/geds133 had the same issue, but I am unable to contact them or comment due to low reputation.
Here is my "predictions" df:
import pandas as pd
predictions = pd.read_csv("Predictions_DF_2002.csv")
predictions.head()
huc12 Predicted PRBT Std
170102120304 30.677075 23.348831
170102120603 31.362211 23.784001
90400010201 5.697461 7.688427
100301040401 3.493039 5.36472
170101011208 4.421055 11.924093
I am attempting to match the DataFrame with a property within the geojson file:
#Read in geojson
import geopandas as gpd
import json
hucs = gpd.read_file(~/"HUC.geojson")
#Populate hucs['properties'] (i.e. convert to plotly-readible geojson-type)
hucs = json.loads(hucs.to_json())
#Print Properties for sanity check
print(hucs['features'][0]['properties'])
#...<a bunch of stuff we don't care about>
{'huc12':170102120304}
#...
Thus, I can use the featureidkey
parameter to specify where to match the values of locations
as written in the docs. Here is the code I use to create the choropleth:
fig = px.choropleth(predictions,
geojson=hucs, color='Predicted PRBT',
locations='huc12', featureidkey='properties.huc12',
color_continuous_scale="Viridis", labels={'Predicted PRBT':'Predicted % RBT'})
fig.update_geos(fitbounds="locations",visible=False)
fig.show()
And here is what the output shows. Note that mouse-over shows relevant information:
My geojson and csv are available for download here.
Upvotes: 2
Views: 1001
Reputation: 121
The geojson must be unwound before plotting:
#Read in geojson
import geopandas as gpd
import json
hucs = gpd.read_file(~/"HUC.geojson")
#Populate hucs['properties'] (i.e. convert to plotly-readible geojson-type)
hucs = json.loads(hucs.to_json())
from geojson_rewind import rewind
hucs_rewound = rewind(hucs,rfc7946=False)
fig = px.choropleth(predictions,
geojson=hucs_rewound, color='Predicted PRBT',
locations='huc12', featureidkey='properties.huc12',
color_continuous_scale="Viridis", labels={'Predicted PRBT':'Predicted % RBT'})
fig.update_geos(fitbounds="locations",visible=False)
fig.show()
See https://github.com/plotly/plotly.py/issues/2354#issuecomment-638742767
and https://github.com/plotly/plotly.py/issues/2619
Upvotes: 3