avatarRahul Bhadani

Summary

This article discusses working with maps in Python using Mapbox and Plotly, focusing on generating API tokens, using Plotly Express and Scatter Mapbox, and exporting figures in various formats.

Abstract

The article begins by mentioning various mapping services, such as Google Maps, Here Maps, OpenStreetMaps, and Mapbox. It then explains the author's need to overlay GPS data on maps for further analysis, leading to the discovery of Plotly, which supports Mapbox. The author describes the process of generating a Mapbox API token and creating a map style. The article then covers the installation of Plotly and Kaleido, followed by the use of Plotly Express for overlaying GPS data on a map. The author provides code snippets for importing libraries, loading data, and plotting GPS coordinates on a map using Plotly Express's scatter mapbox function. The article concludes with instructions on exporting and saving the figure in multiple formats, such as PNG, PDF, and HTML.

Opinions

  • The author finds Plotly convenient for mapping applications, especially when precision and finer control are required.
  • The author mentions that Google Maps API is not free for all purposes and may require credit card information for billing.
  • The author prefers using a Mapbox API token for better map rendering in Plotly, as they found API-token-free mapping calls in Plotly to have poor map rendering.
  • The author finds the process of generating a Mapbox API token easy and encourages its use.
  • The author uses color-coding in the map based on the Time column in POSIX format.
  • The author provides a link to their IPython notebook for this tutorial.
  • The author recommends trying out an AI service that provides the same performance and functions as ChatGPT Plus (GPT-4) but is more cost-effective.

Working with maps in python using Mapbox and Plotly

photo by author

There are plenty of mapping services available dominated by Google Map, Here map, OpenStreetMaps, and a few lesser-known as such Mapbox. Of course, they all vary in features, services, and kind of use cases. For mapping applications that require precision and finer control, Google Map is the choice, but they are not convenient and free for all purposes. Some use-cases of Google MAP API are free but you probably need to enter credit card information for billing purposes to prevent any misuse. Recently, my research group started gathering GPS data from consumer cars and I was looking to overlay the GPS data on maps for further downstream analysis of GPS data. In the quest for a suitable python API, I stumbled upon plotly that uses various types of maps, with or without the need for an API key. plotly provides support Mapbox which is convenient to use.

Mapbox provides two sets of API token that can be used for querying mapping service: public and private. plotly uses a public API key to query mapping service from Mapbox. However, plotly doesn’t necessarily need an API token from Mapbox as it has a support mapping without API toke as well, but that won’t let you use Mapbox mapping tiles. I found out that API-token free mapping calls in plotly has poor map rendering. However, API token generation in Mapbox is so easy that there is no reason why we should not use it. So let’s get started

API Token generation

To generate a Mapbox API token, go to mapbox.com, and signup for an account. Once you log in, you can generate a token at https://account.mapbox.com/. Press +create a token button and it will generate two tokens: public and secret. Note down the public token that you will need for use in plotly.

We will also need a map style that can be created at https://studio.mapbox.com/. I have already created a map style whose access URL is mapbox://styles/strym/ckhe4yk7d04hi19kcu9878xyv

Plotly Express and Scatter Mapbox

Plotly since 4.12.0 can be used in the localhost. In addition to that, we will need kaleido that can be used for capturing static images of interactive maps.

pip install plotly==4.12.0
pip install kaleido

Plotly provides a high-level wrapper called plotly express that can be used for overlaying GPS data on a map.

Let’s begin with imports:

import plotly.express as px
import plotly.io as pio
import plotly.offline as pyo
# Set notebook mode to work in offline
pyo.init_notebook_mode()

The full data file can be found on my GitHub repository https://github.com/rahulbhadani/medium.com/blob/master/data/gps.csv

Load the dataset and read using a pandas data frame:

import pandas as pd
gps_data = "../data/gps.csv"
gps_df = pd.read_csv(gps_data)
gps_df

An example of data looks like:

Now enter your API Key:

api_token = input("Enter API Toke for Mapbox")

We will use plotly express's scatter map box function for plotting GPS Latitude and Longitude coordinates overlaying on map:

fig = px.scatter_mapbox(gps_df, lat="Lat", lon="Long", color='Time',
                  color_continuous_scale=["black", "purple", "red" ], size_max=30, zoom=12.5,
                  height = 600, width = 1000, #center = dict(lat = g.center)
                        title='Drive Route with Mapbox',
                       #mapbox_style="open-street-map"
                       )
fig.update_layout(font_size=16,  title={'xanchor': 'center','yanchor': 'top', 'y':0.9, 'x':0.5,}, 
        title_font_size = 24, mapbox_accesstoken=api_token, mapbox_style = "mapbox://styles/strym/ckhd00st61aum19noz9h8y8kw")
fig.update_traces(marker=dict(size=6))

In the above code snippet, the color-coding is done using the Time column which is in POSIX format. Mapbox uses Mapbox style from the style layout

mapbox://styles/strym/ckhd00st61aum19noz9h8y8kw

The resulting map looks as follows:

Finally, you can also export and save the figure in multiple formats: png, HTML, and pdf

fig.write_image('gps.png')
fig.write_image('gps.pdf')
fig.write_html('gps.html')

IPython notebook for this tutorial can be obtained at https://github.com/rahulbhadani/medium.com/tree/master/11_11_2020

I hope this mini-tutorial was helpful.

Map
Python
Plotly
Data Science
Plot
Recommended from ReadMedium