[Plotly + Mapbox] Interactive Scatter Plot Tutorial

Yash Sanghvi
Tech@Carnot
Published in
4 min readAug 12, 2020

Introduction (what we’ll create):

Here we will use Plotly with Mapbox to create a scatter-map visualization. The following video explains what we intend to create by the end of this tutorial:

Structure of the tutorial:

The tutorial is structured into the following sections:

  1. Pre-requisites
  2. Getting started with the tutorial
  3. When to use this library
  4. References

Pre-requisites:

This tutorial assumes that you are familiar with python and that you have python downloaded and installed in your machine. If you are not familiar with python but have some experience of programming in some other languages, you may still be able to follow this tutorial, depending on your proficiency.

It is very strongly recommended that you go through the Plotly tutorial before going through this tutorial. In this tutorial, the installation of Plotly and the concepts covered in the Plotly tutorial will not be repeated.

Also, you are strongly encouraged to go through the ‘About Mapbox’ section in the [Plotly + Mapbox] Interactive Choropleth visualization tutorial. We will not repeat that section here, but it is very much a part of this tutorial.

Getting started with the tutorial:

GitHub repo: https://github.com/carnot-technologies/MapVisualizations

Relevant notebook: PlotlyWithMapbox (Scatter Plot).ipynb

View notebook on NBViewer: Click Here

Import relevant packages:

from datetime import datetime, timedelta
import plotly.express as px
import pandas as pd
#In order to upload the figure to chart-studio
import chart_studio
import chart_studio.plotly as py
chart_studio.tools.set_credentials_file(username='your_user_name', api_key='your_api_key')

Note that we have imported chart_studio. This will help us upload our visualization directly to chart_studio. Once the visualization is on chart_studio, you can get an embed link to directly integrate the visualization in-line on your website.

You will need to sign-up for a free account on chart-studio. Once that is done, get your user-name and api-key and add them to the set_credentials_file method above.

Please note that the visualizations you upload to chart-studio using a free account will be public. You can skip this part if you are not interested in uploading your visualization to chart-studio.

Loading and Processing Data:

We will use the same dataset that we used for the Cartopy tutorial:

df = pd.read_csv('data/scatter_dummy_data.csv')
df['day'] = pd.to_datetime(df['day'],format="%d-%m-%Y")
df['dt_str'] = df['day'].apply(lambda x: x.strftime("%d-%b-%Y"))

We have performed some basic processing on the day column, and also created a dt_str column which contains the date in a more readable string format. This is because a plotly animation requires the frames to be grouped by a string object.

Next, let’s limit the data to just 10 days. We are doing this to limit the size of the visualization. Chart-studio doesn’t allow you to upload visualizations more than approx. 500 KB in size. Further, we will scale the n_trip_on field, which will indicate the size of the circles in the scatter visualization.

#Trim and sort data
date1 = datetime(2020,3,1)
date2 = datetime(2020,3,10)
df = df[(df['day'] >= date1) & (df['day'] <= date2)]
df.sort_values(by = ['day'], inplace=True)
df['n_trip_scaled']=df['n_trip_on'].apply(lambda x: x/500)

Finally, we are now in a good shape to generate the visualization:

fig = px.scatter_mapbox(df, lat="start_lat", 
lon="start_lon",
hover_name="day",
hover_data=["device_fk_id","n_trip_on"],
color_discrete_sequence=["yellow"],
zoom=3, height=550, width=500,
animation_frame="dt_str",
size='n_trip_scaled',size_max=10,)
fig.update_layout(
mapbox_style="carto-darkmatter")
#Adjust pitch and bearing to adjust the rotation
fig.update_layout(margin={"r":0,"t":0,"l":0,"b":0},
mapbox=dict(
pitch=60,
bearing=30
))
fig.show()

Here, we have used the dt_str column to separate one frame from another. All rows having the same value of dt_str will be a part of the same frame.

We have used the carto-darkmatter style from Mapbox, and we have set the pitch and bearing to provide a tilt to the map. You can try playing around with these numbers to change the tilt.

A snapshot of the visualization created

Once the visualization is generated, you can export it as a stand-alone HTML file:

fig.write_html("html_files/plotly_mapbox_scatter.html")

To upload the visualization to chart-studio, you can just execute the following line of code:

#This line of code uploads the visualization to plotly chart-studio #and returns the link to the visualizationpy.plot(fig, filename = 'plotly_mapbox_scatter', auto_open=True)

This line will return the link to the visualization on chart-studio. It will also open the visualization in a separate tab because we have set auto_open = True . For example, the output when I run the above line was: https://plotly.com/~yashs7/2/

When to use this library:

The same guide which applies to Plotly also applies to Plotly+Mapbox.

References:

  1. Mapbox Scatter Maps in Python: https://plotly.com/python/mapbox-county-choropleth/
  2. Mapbox Official Website: https://www.mapbox.com/

We are trying to fix some broken benches in the Indian agriculture ecosystem through technology, to improve farmers’ income. If you share the same passion join us in the pursuit, or simply drop us a line on report@carnot.co.in

--

--