Plotly Python library comes with mapping capability out-of-the box. This enables us to easily create interactive geospatial analyses. With Plotly we can leverage in-built mapping features such as those for creating lines on maps, adding different layers to maps, scatter plots on mapbox, choropleth among others. We can also extend the plotly mapping and deploy a geospatial application using the dash application. In this post we will look at how to create maps in plotly and how to properly format them. An in-depth data visualization with maps will be covered in the geospatial analysis series. Download the data for this post here; sentiment analysis dataset and kenya 2019 population census by county.
Maps in Plotly
Plotly gives us options to create maps with plotly and Mapbox. For Mapbox we need to register with the Mapbox and obtain an access token to use the Mapbox maps services. Check the following link to access the access token https://www.mapbox.com/.
Import Required Libraries
import numpy as np
import pandas as pd
import plotly.express as px
import plotly.graph_objects as go
Choropleth Map with Plotly Express
When using the choropleth function with plotly express we need to specify certain parameters such as locations, locationmde and scope among others. The ‘scope’ property is an enumeration that may be specified as one of the following enumeration values: [‘world’, ‘usa’, ‘europe’, ‘asia’, ‘africa’, ‘north america’, ‘south america’].
Load Data
sentiment_polarity_df=pd.read_csv('datasets/sentiment_polarity.csv')
sentiment_polarity_df.head()
Now let’s plot sentiment polarity by country
fig = px.choropleth(locations=sentiment_polarity_df['country'], color=sentiment_polarity_df['sentiment_polarity'],
locationmode="country names", scope="world",
hover_name=sentiment_polarity_df['country'])
fig.update_layout(title={'text': 'Sentiment Polarity by Country','y':0.95,'x':0.5, 'xanchor': 'center','yanchor': 'top'},
autosize=True,margin=dict(t=70,b=0,l=0,r=0), xaxis_title='Year', yaxis_title='Year',
font=dict(size=20, family='Times New Romans', color='brown') )
fig.show()
Choropleth Map with Plotly Graph Object
The ‘locationmode’ property is an enumeration that may be specified as one of the following enumeration values: [‘ISO-3’, ‘USA-states’, ‘country names’, ‘geojson-id’]
fig = go.Figure(data=go.Choropleth(
locations=sentiment_polarity_df['country'],
z = sentiment_polarity_df['sentiment_polarity'].astype(float),
locationmode = 'country names',
colorscale = 'Blues',
colorbar_title = "Sentiment Polarity",
# text=df['country']
))
fig.update_layout(title={'text': 'Sentiment Polarity by Country','y':0.95,'x':0.5, 'xanchor': 'center','yanchor': 'top'},
autosize=True,margin=dict(t=70,b=0,l=0,r=0), xaxis_title='Year', yaxis_title='Year',
font=dict(size=20, family='Times New Romans', color='brown') )
fig.show()
Mapbox map with Plotly Express
Load Kenya 2019 Census Data
kenya_county_population = pd.read_csv('datasets/kenyan_population_census_2019.csv')
kenya_county_population.head()
mapbox_access_token = open("mapboxtoken.mapbox_token").read()
fig = px.scatter_mapbox(kenya_county_population, lat="lat", lon="lng", color="County",
size='Total Population',
color_continuous_scale=px.colors.cyclical.IceFire,
size_max=25, zoom=5,
hover_name="County")
fig.update_layout( mapbox=dict( accesstoken=mapbox_access_token,
bearing=10, pitch=0, zoom=6, style='outdoors' ,
center=go.layout.mapbox.Center( lat=0.05, lon=37.65 )),
width=950, height=900,
title={'text': 'Kenyan Population per County for 2019 Census','y':0.95,'x':0.4, 'xanchor': 'center','yanchor': 'top'},
autosize=True,margin=dict(t=70,b=0,l=0,r=0),
font=dict(size=20, family='Times New Romans', color='brown') )
fig.show()
Mapbox map with Plotly Graph Object
mapbox_access_token = open("mapboxtoken.mapbox_token").read()
fig = go.Figure(go.Scattermapbox(lat=kenya_county_population["lat"], lon=kenya_county_population["lng"],
mode="markers", hovertext=kenya_county_population['Total Population'],
marker=go.scattermapbox.Marker(size=15, color = 'red'),
))
fig.update_layout( mapbox=dict( accesstoken=mapbox_access_token,
bearing=10, pitch=0, zoom=6, style='streets' ,
center=go.layout.mapbox.Center( lat=0.05, lon=37.65 )),
width=950, height=900,
title={'text': 'Kenyan Population per County for 2019 Census','y':0.95,'x':0.5, 'xanchor': 'center','yanchor': 'top'},
autosize=True,margin=dict(t=70,b=0,l=0,r=0),
font=dict(size=20, family='Times New Romans', color='brown') )
fig.show()
For complete code check the jupyter notebook here.
Conclusion
Geospatial analytics is useful when working with location-based datasets. It help us visualize and find insights from geographically distributed data. Plotly provides us with out-of-the box tools that makes it easy to build highly interactive maps. In this post we have looked at how to get started with maps in plotly. In the next post and series of posts we will introduce geospatial analytics and look at various python-based tools for geospatial analysis. To learn about tree maps in plotly check our previous post here.