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:
JavaScript
x
11
11
1
import plotly.graph_objects as go
2
3
fig = go.Figure(go.Scattergeo())
4
fig.update_geos(
5
visible=False, resolution=50, scope="Spain",
6
showcountries=True, countrycolor="Black",
7
showsubunits=True, subunitcolor="Blue"
8
)
9
fig.update_layout(height=300, margin={"r":0,"t":0,"l":0,"b":0})
10
fig.show()
11
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
JavaScript
1
42
42
1
import requests
2
import plotly.express as px
3
import pandas as pd
4
5
# get Spain municipal boundaries
6
res = requests.get(
7
"https://raw.githubusercontent.com/codeforgermany/click_that_hood/main/public/data/spain-provinces.geojson"
8
)
9
10
# get some cities in Spain
11
df = (
12
pd.json_normalize(
13
requests.get(
14
"https://opendata.arcgis.com/datasets/6996f03a1b364dbab4008d99380370ed_0.geojson"
15
).json()["features"]
16
)
17
.loc[
18
lambda d: d["properties.CNTRY_NAME"].eq("Spain"),
19
["properties.CITY_NAME", "geometry.coordinates"],
20
]
21
.assign(
22
lon=lambda d: d["geometry.coordinates"].apply(lambda v: v[0]),
23
lat=lambda d: d["geometry.coordinates"].apply(lambda v: v[1]),
24
)
25
)
26
27
# scatter the cities and add layer that shows municiple boundary
28
px.scatter_mapbox(df, lat="lat", lon="lon", hover_name="properties.CITY_NAME").update_layout(
29
mapbox={
30
"style": "carto-positron",
31
"zoom": 3.5,
32
"layers": [
33
{
34
"source": res.json(),
35
"type": "line",
36
"color": "green",
37
"line": {"width": 1},
38
}
39
],
40
}
41
)
42