till Kadabra
till Kadabra

Reputation: 488

How to center plotly scatter_geo to a specific country in python

I use the scatter_geo function from plotly.express to plot geographical data on a map.

import geopandas as gpd
import plotly.express as px
fig = px.scatter_geo(gdf, 
                     lat = 'latitude', 
                     lon = 'longitude', 
                     geojson='geometry', 
                     scope='europe',
                     animation_frame = 'year')
fig.show()

How can I archive that the map is centered to only one country, in my case Germany? The parameter scope accepted only continents. There are two more parameters, center and fitbounds, that sounds useful, but I don't understand to fill in the right value.

center (dict) – Dict keys are 'lat' and 'lon' Sets the center point of the map.

fitbounds (str (default False).) – One of False, locations or geojson.

Dummie data:

    geometry    latitude    longitude   value   year
0   POINT (13.72740 51.05570)   51.0557     13.7274     35.55   1838
1   POINT (13.72740 51.05570)   51.0557     13.7274     35.15   1842

Upvotes: 1

Views: 4571

Answers (1)

r-beginners
r-beginners

Reputation: 35145

There are two ways to specify a specific latitude and longitude: by writing it directly or by adding it in a layout update. Adding it via layout update is more flexible and adjustable. For the scope, select Europe to draw the area by country. To zoom in on the map, use projection_scalse instead of zoom. I was not sure about the center of Germany so I used the data you presented, please change it.

fig = px.scatter_geo(gdf, 
                     lat = 'latitude', 
                     lon = 'longitude', 
                     geojson='geometry', 
                     scope='europe',
                     center=dict(lat=51.0057, lon=13.7274),
                     animation_frame = 'year')

Update layout

import plotly.express as px
df = px.data.gapminder().query("year == 2007")
fig = px.scatter_geo(df,
                     locations="iso_alpha",
                     size="pop",
                     projection="natural earth"
                     )

fig.update_layout(
    autosize=True,
    height=600,
    geo=dict(
        center=dict(
            lat=51.0057,
            lon=13.7274
        ),
        scope='europe',
        projection_scale=6
    )
)
fig.show()

enter image description here

Upvotes: 3

Related Questions