The aim of create a map of a country with plotly. I show you the code to make the map with dots from cities and I want to change it to regions:
import plotly.graph_objects as go fig = go.Figure(go.Scattergeo()) fig.update_geos( visible=False, resolution=50, scope="Spain", showcountries=True, countrycolor="Black", showsubunits=True, subunitcolor="Blue" ) fig.update_layout(height=300, margin={"r":0,"t":0,"l":0,"b":0}) fig.show()
In the scope we have by default: “world” | “usa” | “europe” | “asia” | “africa” | “north america” | “south america”. How to implement those who are not in the scope? For example Spain.
Advertisement
Answer
- using mapbox instead of geos
- you can add layers to mapbox scatter
- have sourced cities and boundary geometries to demonstrate
import requests import plotly.express as px import pandas as pd # get Spain municipal boundaries res = requests.get( "https://raw.githubusercontent.com/codeforgermany/click_that_hood/main/public/data/spain-provinces.geojson" ) # get some cities in Spain df = ( pd.json_normalize( requests.get( "https://opendata.arcgis.com/datasets/6996f03a1b364dbab4008d99380370ed_0.geojson" ).json()["features"] ) .loc[ lambda d: d["properties.CNTRY_NAME"].eq("Spain"), ["properties.CITY_NAME", "geometry.coordinates"], ] .assign( lon=lambda d: d["geometry.coordinates"].apply(lambda v: v[0]), lat=lambda d: d["geometry.coordinates"].apply(lambda v: v[1]), ) ) # scatter the cities and add layer that shows municiple boundary px.scatter_mapbox(df, lat="lat", lon="lon", hover_name="properties.CITY_NAME").update_layout( mapbox={ "style": "carto-positron", "zoom": 3.5, "layers": [ { "source": res.json(), "type": "line", "color": "green", "line": {"width": 1}, } ], } )