How to add Puerto Rico to USA scatter map?

Hi @bestfirstsearch, welcome to the forums.

I found a topic which is related to your problem:

Combining the information given there and your desired contries I achieved this:

import plotly.graph_objects as go
import urllib.request
import json

# geojson for Puerto Rico and USA
urls = [
    "https://raw.githubusercontent.com/commonwealth-of-puerto-rico/crime-spotter/master/public/data/municipalities.geojson",
    "https://raw.githubusercontent.com/ResidentMario/geoplot-data/master/contiguous-usa.geojson"
]

# function from the linked topic
def state_boundaries(geojdata):
    pts = []#list of points defining boundaries of polygons, pts has as coordinates the lon and lat
    for  feature in geojdata['features']:
        if feature['geometry']['type'] == 'Polygon':
            pts.extend(feature['geometry']['coordinates'][0])    
            pts.append([None, None])#mark the end of a polygon   
        
        elif feature['geometry']['type'] == 'MultiPolygon':
            for polyg in feature['geometry']['coordinates']:
                pts.extend(polyg[0])
                pts.append([None, None])#end of polygon
        elif feature['geometry']['type'] == 'LineString': 
            points.extend(feature['geometry']['coordinates'])
            points.append([None, None])
        else: pass           
    lons, lats = zip(*pts) 
    return lons, lats

geojsons = []
for url in urls:
    with urllib.request.urlopen(url) as u:
        geojsons.append(json.loads(u.read().decode()))

data = []
for contry in geojsons:
    lons, lats = state_boundaries(contry)
    data.append(
        go.Scattergeo(
            lon=lons, 
            lat=lats,
            mode="lines", 
            line_width=1.5, 
            line_color="black"
        )
    )

fig = go.Figure(data=data)

fig.update_layout(height=800, margin={"r":0,"t":0,"l":0,"b":0})
fig.update_geos(visible=False, fitbounds="locations")
fig.show()

2 Likes