Data Visualisation of Route on Map Python Tutorial

This tutorial is to introduce how to plot a route on the map using python. We are going to use Basemap python package in this tutorial, there are some other packages have similar function, like GCMap, plotly.

Install Basemap package

Install mpl_tookits.basemap python API is not hard. I am using installed Ipython environment, so the code is like

!apt-get install -y python-mpltoolkits.basemap

After that, import some basic python packages needed in this tutorial.

import numpy as np
import pandas as pd
import matplotlib.pyplot as plt
from mpl_toolkits.basemap import Basemap

Load Data

In this tutorial, we are going to use a set of pseudo trip data. The plotting data should contain at least 4 variables: start latitude, start longitude, stop latitude, stop longitude.

df = pd.read_csv("pseudo_trip.csv")

Pandas will load the data into default dataframe format.

Plot Data

We will plot the start point as a green circle marker, the destination point as a red circle marker, and there will be a big circle line between two points.

fig = plt.figure(figsize=(15,15))

xbuf = 0.2
ybuf = 0.35
minlat = np.min([df2.stop_lat.min(), df2.start_lat.min()])
minlon = np.min([df2.stop_lon.min(), df2.start_lon.min()])
maxlat = np.max([df2.stop_lat.max(), df2.start_lat.max()])
maxlon = np.max([df2.stop_lon.max(), df2.start_lon.max()])
width = maxlon - minlon
height = maxlat - minlat

m = Basemap(llcrnrlon=minlon - width* xbuf,
            llcrnrlat=minlat - height*ybuf,
            urcrnrlon=maxlon + width* xbuf,
            urcrnrlat=maxlat + height*ybuf,
            projection='merc',
            resolution='l',
            lat_0=minlat + height/2,
            lon_0=minlon + width/2,)

m.drawmapboundary(fill_color='#191970')
m.drawcoastlines()
m.drawstates()
m.drawcountries()
m.fillcontinents(color='black',lake_color='#191970')

for i in df.index:
    m.drawgreatcircle(df['start_lon'][i], df['start_lat'][i], 
                      df['stop_lon'][i], df['stop_lat'][i], 
                      linewidth=3, alpha=0.2, color='white')
    m.plot(*m(df['start_lon'][i], df['start_lat'][i]), 
           color='y', markersize=10, alpha=0.8, marker='o')
    m.plot(*m(df['stop_lon'][i], df['stop_lat'][i]), 
           color='r', alpha=0.5, marker='o' )

fig.text(0.15, 0.20, 
         "Plotted using Python, Basemap", 
         ha='left', color='white', style='italic')
fig.text(0.15, 0.18, 
         "data.com", 
         color='white', fontsize=16, ha='left')
plt.savefig('Map.png', dpi=150, 
            frameon=True, transparent=False, 
            bbox_inches='tight', 
            pad_inches=0.2)

The result looks like

US_CA

Last, choose a color you like!

Advertisements