Looking to display a choropleth map with text labels on custom GeoJSON. Was successful with go.Choroplethmapbox until running into this bug attempting to add labels using go.Scattermapbox: https://github.com/plotly/plotly.js/issues/4110
Looking now to implement using go.Choropleth with go.Scattergeo for text labels. Can get the labels to appear, but only the first polygon is shaded per z, with the background taking on a solid colour.
Been banging my head against this for a day now- any help would be sincerely appreciated!
import pandas as pd
import geopandas as gpd
import copy
import plotly.graph_objects as go
from shapely.geometry import shape
import json
geojson_layer = json.loads(('{"type": "FeatureCollection", "features": [{"type": "Feature", "geometry": '
'{"coordinates": [[[-139.1265796280109, 48.38073542719777], '
'[-138.78971139646606, 47.99172990900129], [-138.1159749333764, '
'47.99172990900129], [-137.77910670183158, 48.38073542719777], '
'[-138.1159749333764, 48.76679074547397], [-138.78971139646606, '
'48.76679074547397], [-139.1265796280109, 48.38073542719777]]], "type": '
'"Polygon"}, "id": 1, "properties": {"abbr": "AAA"}}, {"type": "Feature", '
'"geometry": {"coordinates": [[[-139.1265796280109, 51.38705091951641], '
'[-138.78971139646606, 51.021480977726554], [-138.1159749333764, '
'51.021480977726554], [-137.77910670183158, 51.38705091951641], '
'[-138.1159749333764, 51.74972352163286], [-138.78971139646606, '
'51.74972352163286], [-139.1265796280109, 51.38705091951641]]], "type": '
'"Polygon"}, "id": 2, "properties": {"abbr": "AAB"}}, {"type": "Feature", '
'"geometry": {"coordinates": [[[-139.1265796280109, 52.10950733100988], '
'[-138.78971139646606, 51.74972352163286], [-138.1159749333764, '
'51.74972352163286], [-137.77910670183158, 52.10950733100988], '
'[-138.1159749333764, 52.46641128396985], [-138.78971139646606, '
'52.46641128396985], [-139.1265796280109, 52.10950733100988]]], "type": '
'"Polygon"}, "id": 3, "properties": {"abbr": "AAC"}}]}'))
df = pd.DataFrame.from_dict({
'abbr': {0: 'AAA', 1: 'AAB', 2: 'AAC'},
'id': {0: 1, 1: 2, 2: 3},
'result': {0: 0.525262154432793,
1: 0.473385132784414,
2: 0.444949382989729}
})
# build GeoDataFrame for adding labels via go.Scattergeo
layers = copy.deepcopy(geojson_layer)
for k in range(len(layers['features'])):
layers['features'][k]['geometry'] = shape(layers['features'][k]['geometry'])
gdf = gpd.GeoDataFrame(pd.io.json.json_normalize(layers['features'])).set_geometry('geometry')
gdf.columns = ['geometry', 'id', 'abbr', 'type']
del layers
map_layout = go.Layout()
map_layers = [
go.Choropleth(
geojson=geojson_layer,
locations=df.id.to_list(),
z=df.result
),
go.Scattergeo(
lat=gdf.geometry.centroid.y.to_list(),
lon=gdf.geometry.centroid.x.to_list(),
text=gdf.abbr,
mode='text')
]
fig = go.Figure(data=map_layers, layout=map_layout)
fig.update_geos(scope='north america',
visible=False,
fitbounds="locations")
fig.show()