How to add Puerto Rico to USA scatter map?

I need a USA map with Puerto Rico on it. Unfortunately I don’t believe the default go.Scattergeo map provides one.

Is there a way to add Puerto Rico to the built-in USA map? If not, is it possible to use a GeoJson file of Puerto Rico to create the map and somehow overlay and add that image with the default USA map?

Thank you!

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()

Is there a way to do this with the provided built-in scattter map? I need a map of the United States (including Hawaii and Alaska) as well as Puerto Rico.

Not sure about the builtin maps. But you could just search for a different geojson- file which meets your requirements, maybe this one?

How would I use that GeoJson file as the map? I’ve tried including it into my Scattergeo map but to no avail.

You could use my example from above and substitute the second URL with the one which meets your needs.

I got this code working for me, but is there a way to fill in the country (Puerto Rico) with a color? (as well as the outline)