Show Sidebar Hide Sidebar

Lines on Maps in Python

How to draw lines, great circles, and contours on maps in Python.

New to Plotly?

Plotly's Python library is free and open source! Get started by downloading the client and reading the primer.
You can set up Plotly to work in online or offline mode, or in jupyter notebooks.
We also have a quick-reference cheatsheet (new!) to help you get started!

US Flight Paths Map

In [1]:
import plotly.plotly as py
import pandas as pd

df_airports = pd.read_csv('https://raw.githubusercontent.com/plotly/datasets/master/2011_february_us_airport_traffic.csv')
df_airports.head()

df_flight_paths = pd.read_csv('https://raw.githubusercontent.com/plotly/datasets/master/2011_february_aa_flight_paths.csv')
df_flight_paths.head()

airports = [ dict(
        type = 'scattergeo',
        locationmode = 'USA-states',
        lon = df_airports['long'],
        lat = df_airports['lat'],
        hoverinfo = 'text',
        text = df_airports['airport'],
        mode = 'markers',
        marker = dict( 
            size=2, 
            color='rgb(255, 0, 0)',
            line = dict(
                width=3,
                color='rgba(68, 68, 68, 0)'
            )
        ))]
        
flight_paths = []
for i in range( len( df_flight_paths ) ):
    flight_paths.append(
        dict(
            type = 'scattergeo',
            locationmode = 'USA-states',
            lon = [ df_flight_paths['start_lon'][i], df_flight_paths['end_lon'][i] ],
            lat = [ df_flight_paths['start_lat'][i], df_flight_paths['end_lat'][i] ],
            mode = 'lines',
            line = dict(
                width = 1,
                color = 'red',
            ),
            opacity = float(df_flight_paths['cnt'][i])/float(df_flight_paths['cnt'].max()),
        )
    )
    
layout = dict(
        title = 'Feb. 2011 American Airline flight paths<br>(Hover for airport names)',
        showlegend = False, 
        geo = dict(
            scope='north america',
            projection=dict( type='azimuthal equal area' ),
            showland = True,
            landcolor = 'rgb(243, 243, 243)',
            countrycolor = 'rgb(204, 204, 204)',
        ),
    )
    
fig = dict( data=flight_paths + airports, layout=layout )
py.iplot( fig, filename='d3-flight-paths' )
Out[1]:

London to NYC Great Circle

In [2]:
import plotly.plotly as py

nyc_london = [ dict(
    type = 'scattergeo',
    lat = [ 40.7127, 51.5072 ],
    lon = [ -74.0059, 0.1275 ],
    mode = 'lines',
    line = dict(
        width = 2,
        color = 'blue',
    ),
) ]
    
layout = dict(
        title = 'London to NYC Great Circle',
        showlegend = False,         
        geo = dict(
            resolution = 50,
            showland = True,
            showlakes = True,
            landcolor = 'rgb(204, 204, 204)',
            countrycolor = 'rgb(204, 204, 204)',
            lakecolor = 'rgb(255, 255, 255)',
            projection = dict( type="equirectangular" ),
            coastlinewidth = 2,
            lataxis = dict(
                range = [ 20, 60 ],
                showgrid = True,
                tickmode = "linear",
                dtick = 10
            ),
            lonaxis = dict(
                range = [-100, 20],
                showgrid = True,
                tickmode = "linear",
                dtick = 20
            ),
        )
    )
    
fig = dict( data=nyc_london, layout=layout )
py.iplot( fig, validate=False, filename='d3-great-circle' )
Out[2]:

Contour lines on globe

In [7]:
import plotly.plotly as py
import pandas as pd

try:
    # Python 2
    from itertools import izip
except ImportError:
        # Python 3
        izip = zip

df = pd.read_csv('https://raw.githubusercontent.com/plotly/datasets/master/globe_contours.csv')
df.head()

contours = []

scl = ['rgb(213,62,79)','rgb(244,109,67)','rgb(253,174,97)',\
       'rgb(254,224,139)','rgb(255,255,191)','rgb(230,245,152)',\
       'rgb(171,221,164)','rgb(102,194,165)','rgb(50,136,189)']

def pairwise(iterable):
    a = iter(iterable)
    return izip(a, a)

i=0
for lat, lon in pairwise(df.columns):
    contours.append( dict(
        type = 'scattergeo',
        lon = df[lon],
        lat = df[lat],
        mode = 'lines',
        line = dict(
            width = 2,
            color = scl[i]
        )
    ) )
    i = 0 if i+1 >= len(df.columns)/4 else i+1
    
layout = dict(
        title = 'Contour lines over globe<br>(Click and drag to rotate)',
        showlegend = False,         
        geo = dict(
            showland = True,
            showlakes = True,
            showcountries = True,
            showocean = True,
            countrywidth = 0.5,
            landcolor = 'rgb(230, 145, 56)',
            lakecolor = 'rgb(0, 255, 255)',
            oceancolor = 'rgb(0, 255, 255)',
            projection = dict( 
                type = 'orthographic',
                rotation = dict(
                    lon = -100,
                    lat = 40,
                    roll = 0
                )            
            ),
            lonaxis = dict( 
                showgrid = True,
                gridcolor = 'rgb(102, 102, 102)',
                gridwidth = 0.5
            ),
            lataxis = dict( 
                showgrid = True,
                gridcolor = 'rgb(102, 102, 102)',
                gridwidth = 0.5
            )
        )
    )
    
fig = dict( data=contours, layout=layout )
py.iplot( fig, validate=False, filename='d3-globe' )
Out[7]:

Reference

See https://plot.ly/python/reference/#scattergeo for more information and chart attribute options!

Still need help?
Contact Us

For guaranteed 24 hour response turnarounds, upgrade to a Developer Support Plan.