px.scatter_geo()
#
Base Map Layer#
plotly
Geo maps have a built-in base map layer composed of “physical” and “cultural” data from the Natural Earth Dataset. We can show or hide, as well as modify, various components of this base layer. For example, we can take a look at the built-in base map, showing only country sub-units.
import plotly.graph_objects as go # import statement
fig = go.Figure(go.Scattergeo()) # create figure
# update figure to not show physical attributes and show country attributes
fig.update_geos(
visible=False, resolution=50,
showcountries=True, countrycolor="RebeccaPurple"
)
fig.update_layout(height=300, margin={"r":0,"t":0,"l":0,"b":0}) # update figure layout
fig.show() # show figure
There are a few options for zooming or focusing the area represented in the base map. We can set the layout.geo.fitbounds
attribute to locations
to automatically center the visual base map range based on the data being plotted.
import plotly.express as px # import statement
fig = px.scatter_geo(lat=[0,15,20,35], lon=[5,10,25,30]) # scatter plot
fig.update_geos(fitbounds="locations") # update figure to center and zoom base map based on data parameters
fig.update_layout(height=300, margin={"r":0,"t":0,"l":0,"b":0}) # udpate figure size and layout
fig.show() # show figure
Point Data#
Now that we have a base map layer that will serve as the coordinate system for our plot, we can plot data using this coordinate system.
When we understand maps are just another type of plot that uses a different projection system, maps with markers are just another
kind of scatterplot. We can use the px.scatter_geo()
function to plot point data with geospatial dimensions.
import pandas as pd # import statement
df = px.data.gapminder().query("year == 2007") # subset data
fig = px.scatter_geo(df, locations="iso_alpha", size="pop")
fig.update_geos(fitbounds="locations") # update figure to center and zoom base map based on data parameters
fig # show output
A few notes on this example:
We pass the entire data frame
df
to thepx.scatter_geo()
function.We use
locations
to note the column with location information.The
size
parameter determines the size of each marker based on thepop
field value.
Let’s say we wanted to use a different type of global projection, and color the points by continent.
fig = px.scatter_geo(df, locations="iso_alpha", size="pop", color="continent", hover_name="country", projection="natural earth") # create figure
fig # show figure
A few notes on this modified example:
We set
color
to assign a color to each unique value incontinent
.We set the
hover_name
tocountry
.We set
projection
tonatural earth
to change the underlying base map layer.