Black Lives Matter. Please consider donating to Black Girls Code today.

Choropleth geojson fitbounds with wrapping geojson

I’m having an issue with wrapping and geojson.

Here’s an example based on Choropleth map using GeoJSON (https://plotly.com/python/choropleth-maps/)

from urllib.request import urlopen
import json
with urlopen('https://raw.githubusercontent.com/plotly/datasets/master/geojson-counties-fips.json') as response:
        counties = json.load(response)

import pandas as pd
df = pd.read_csv("https://raw.githubusercontent.com/plotly/datasets/master/fips-unemp-16.csv",
                 dtype={"fips": str})

import plotly.express as px

df = df[df.fips.str.startswith("01")]

fig = px.choropleth(df, geojson=counties, locations='fips', color='unemp',
                    color_continuous_scale="Viridis",
                    range_color=(0, 12),
                    labels={'unemp':'unemployment rate'}
)
fig.update_geos(fitbounds="locations", visible=False)

import dash
import dash_core_components as dcc
import dash_html_components as html

app = dash.Dash()
app.layout = html.Div([
        dcc.Graph(figure=fig)
    ])

app.run_server(debug=True, use_reloader=False)

From the code you can see I filter down to the Alabama data (FIPS state code 01) and use fitbounds=“locations” to center and zoom on the provided data. And you can see in the picture below that it works great.

Now, let’s try with Alaska (FIPS 02), as in

df = df[df.fips.str.startswith("02")]

Gross! I’ve tried all manner of update_geos with center, projection_rotation, *axis_range, etc. but the fitbounds overrides them all, and without it I have to manually calculate and set everything (assuming I can replicate all the zooming too).

Is there any way to have fitbounds locations understand that a rotation before bounding is better than wrapping? Or, let me provide a center or rotation prior to calculating bounds?

Using the following special case code for Alaska gets me close to what I want. However, I think any geojson shapes that wrap will have this issue.

if alaska:
        fig.update_geos(
              lonaxis_range=[20, 380],
              projection_scale=6,
              center=dict(lat=61),
              visible=False)
else:
        fig.update_geos(fitbounds="locations", visible=False)   

Any advice on a better way to do this so that a special case isn’t required? Or could the fitbounds location code be updated to handle this?