Testing Python map frameworks

  • Plotly
  • folium
  • basemap
  • Cartopy

In [1]:
%matplotlib inline

import os
import pandas as pd
import matplotlib
import matplotlib.pyplot as plt
import numpy as np

# folium
import folium
print('folium:', folium.__version__)
#cartopy
import cartopy
import cartopy.crs as ccrs
from cartopy.io.img_tiles import OSM
print('cartopy:', cartopy.__version__)
#plotly
import plotly
plotly.offline.init_notebook_mode()
from plotly.offline import download_plotlyjs, init_notebook_mode, iplot
print('plotly:', plotly.__version__)
#basemap
from mpl_toolkits.basemap import Basemap


folium: 0.2.0.dev
cartopy: 0.13.0
plotly: 1.9.5

In [2]:
plt.rcParams['figure.figsize'] = (12, 10)

In [3]:
def haversine(lon1, lat1, lon2, lat2):
    # Distance between two points
    # assuming that the input is in WGS84 and is equivalent
    # to SIRGAS 2000
    lon1, lat1, lon2, lat2 = map(np.radians, [lon1, lat1, lon2, lat2])
    # haversine formula 
    a = np.sin((lat2 - lat1 )/2.)**2 + np.cos(lat1) * np.cos(lat2) * np.sin((lon2 - lon1)/2.)**2
    c = 2. * np.arcsin(np.sqrt(a)) 
    km = 6367. * c
    return km

In [4]:
coords = list(
    zip(
        np.random.uniform(low=-23.0, high=-24.0, size=(10)), 
        np.random.uniform(low=-44.0, high=-46.0, size=(10)),
        np.random.uniform(low=-23.0, high=-25.0, size=(10)),
        np.random.uniform(low=-44.0, high=-47.0, size=(10))
    ),
)

In [5]:
df = pd.DataFrame(coords, index=range(10), columns=['lat_ini', 'lon_ini', 'lat_end', 'lon_end'])

In [6]:
df['dist'] = df.apply(lambda row: haversine(row['lon_ini'],row['lat_ini'],row['lon_end'],row['lat_end'] ), axis=1)

In [7]:
df


Out[7]:
lat_ini lon_ini lat_end lon_end dist
0 -23.150312 -44.018830 -24.895687 -46.109937 287.507936
1 -23.577499 -45.527250 -23.951837 -44.238559 137.505547
2 -23.516451 -44.311166 -23.103546 -44.724607 62.334879
3 -23.164993 -44.078553 -23.485680 -46.922445 292.373868
4 -23.027752 -45.166660 -24.517805 -46.464783 211.763021
5 -23.373562 -45.756430 -23.794661 -44.232629 162.089294
6 -23.484928 -44.320216 -24.668517 -44.982417 147.691538
7 -23.151860 -45.497466 -24.043264 -45.498317 99.057443
8 -23.972198 -45.872358 -24.850285 -44.035905 209.888984
9 -23.530495 -45.969763 -23.119825 -46.568897 76.291448

In [8]:
# Cartopy example
tiler = OSM()
mercator = tiler.crs


ax = plt.axes(projection=mercator)
extend = (-46.871099845400906, -44.04770602852918, -24.57054154739055, -23.01711887727721)
#ax.coastlines('10m')
ax.add_image(tiler, 10)

for key, row in df.iterrows():
        plt.plot(
            [row.lon_end, row.lon_ini], [row.lat_end, row.lat_ini],
             color='blue', linewidth=2, marker='o',
             transform=ccrs.Geodetic(),
         )

ax.set_extent(extend)
plt.show()



In [13]:
zoom_start = 8

mapa = folium.Map(location=[df.lat_ini.mean(), df.lon_ini.mean()], zoom_start=zoom_start)

kw = dict(opacity=1.0, weight=4)

lines = []

start_points = list(zip(df['lat_ini'], df['lon_ini'] ))
end_points = list(zip(df['lat_end'], df['lon_end'] ))

for start_point, end_point in zip(start_points, end_points):
    lines.append(
        folium.PolyLine(locations=[
                start_point,end_point
            ], color='red', **kw)
    )


ml = folium.MultiPolyLine(locations=list(zip(start_points, end_points)), color='blue')
    
# for line in lines:
#     mapa.add_children(line)
mapa.add_children(ml)

mapa


Out[13]:

In [16]:
paths = []
for i in range( len( df ) ):
    paths.append(
        dict(
            type = 'scattergeo',
            locationmode = 'ISO-3',
            lon = [df['lon_end'].iloc[i], df['lon_ini'].iloc[i] ],
            lat = [df['lat_ini'].iloc[i], df['lat_end'].iloc[i] ],
            mode = 'lines',
            line = dict(
                width = 1,
                color = 'blue',
            ),
        )
    )
    
layout = dict(
        title = 'Santos',
        showlegend = False, 
        geo = dict(
            scope='south america',
            #projection=dict( type='azimuthal equal area' ),
        projection=dict( type='mercator' ),
            showland = True,
            lonaxis = dict(range=[df.lon_end.min(), df.lon_ini.max()]),
            lataxis = dict(range=[df.lat_end.min(), df.lat_ini.max()]),
            showcoastlines=True,
            showrivers=True,
            resolution=50,
            landcolor = 'rgb(243, 243, 243)',
            countrycolor = 'rgb(204, 204, 204)',
        ),
    )
fig = dict( data=paths, layout=layout )
iplot(fig)



In [17]:
# Basemap
m = Basemap(
    projection='cyl',
    llcrnrlat=df.lat_ini.min(),
    urcrnrlat=df.lat_end.max(),
    llcrnrlon=df.lon_ini.min(),
    urcrnrlon=df.lon_end.max(), 
    resolution='h'
)

for key, row in df.iterrows():
        m.plot(
            [row.lon_end, row.lon_ini], [row.lat_end, row.lat_ini],
             color='blue', linewidth=2, marker='o'
        )

m.drawcoastlines()
m.drawcountries()
m.drawstates()
m.fillcontinents(zorder=1)


Out[17]:
[<matplotlib.patches.Polygon at 0x7fbd8c43c6a0>,
 <matplotlib.patches.Polygon at 0x7fbd8c43cba8>,
 <matplotlib.patches.Polygon at 0x7fbd8c443240>]

In [ ]: