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
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]:
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]:
In [ ]: