plotly

Plotly.Express.Scatter_Geo()

Plotly allows us to create scatter plots on a map using the scatter_geo() function. In this article, we will explore how we can use this function in Plotly.

Function Syntax and Parameter

The plotly.express.scatter_geo() function provides a relatively simple syntax as shown in the following:

Keep in mind that the function also borrows other common syntax from the Plotly library. Feel free to check the docs for more.

The function parameters are the following:

  1. data_frame – This specifies the DataFrame containing the column names.
  2. lat – The lat parameter contains the values used to position the marks on the latitude of the map.
  3. lon – Similar to the lat parameter, the values of the lon parameter are used to position the marks along the longitude on the map.
  4. locationmode – Determines the set of locations used to match the entries in locations to regions on the map.
  5. color – Specifies the values used to assign a unique color to the scatter marks.
  6. title – Defines the title for the Figure.
  7. width/height – Sets the width and height of the figure in pixels.

Example:

The following code shows how to create a scatter map using the scatter_geo() function:

import plotly.express as px
df = px.data.gapminder().query("year == 2007")
fig = px.scatter_geo(df, locations='iso_alpha', size='gdpPercap')
fig.show()

The given code returns a scatter plot of the gdpPercap of the countries in the DataFrame.
The resulting figure is as follows:

We can customize the marks of the scatter by coloring them by the country.

import plotly.express as px
df = px.data.gapminder().query("year == 2007")
fig = px.scatter_geo(df, locations='iso_alpha', size='gdpPercap', color='country')
fig.show()

Output:

We can also create a scatter map using the MapBox API as shown in the following:

import plotly.express as px
import pandas as pd
df = pd.read_csv('worldcities.csv')
px.set_mapbox_access_token(open('mapbox.mapbox_token').read())
lat=df.lat
lon=df.lng
df.head()
fig = px.scatter_geo(df, lat=lat, lon=lon)
fig.show()

This returns a world map of all the cities.

Conclusion

This article describes the simple steps of creating a scatter geo map using the scatter_geo() function.

About the author

John Otieno

My name is John and am a fellow geek like you. I am passionate about all things computers from Hardware, Operating systems to Programming. My dream is to share my knowledge with the world and help out fellow geeks. Follow my content by subscribing to LinuxHint mailing list