MovingPandas provides a trajectory datatype based on GeoPandas. The project home is at https://github.com/movingpandas/movingpandas
The documentation is available at https://movingpandas.readthedocs.io/
import pandas as pd
import geopandas as gpd
import movingpandas as mpd
import shapely as shp
import hvplot.pandas
from geopandas import GeoDataFrame, read_file
from shapely.geometry import Point, LineString, Polygon
from datetime import datetime, timedelta
from holoviews import opts
import warnings
warnings.filterwarnings('ignore')
opts.defaults(opts.Overlay(active_tools=['wheel_zoom'], frame_width=500, frame_height=400))
mpd.show_versions()
Trajectory objects consist of a trajectory ID and a GeoPandas GeoDataFrame with a DatetimeIndex. The data frame therefore represents the trajectory data as a Pandas time series with associated point locations (and optional further attributes).
Let's create a small toy trajectory to see how this works:
df = pd.DataFrame([
{'geometry':Point(0,0), 't':datetime(2018,1,1,12,0,0)},
{'geometry':Point(6,0), 't':datetime(2018,1,1,12,6,0)},
{'geometry':Point(6,6), 't':datetime(2018,1,1,12,10,0)},
{'geometry':Point(9,9), 't':datetime(2018,1,1,12,15,0)}
]).set_index('t')
gdf = GeoDataFrame(df, crs=31256)
toy_traj = mpd.Trajectory(gdf, 1)
toy_traj
toy_traj.plot()
toy_traj.hvplot()
We can also access the trajectory's GeoDataFrame:
toy_traj.df
toy_traj.df.plot()
df = pd.read_csv('../data/geolife_small.csv', delimiter=';')
df
traj_collection = mpd.TrajectoryCollection(df, 'trajectory_id', t='t', x='X', y='Y')
print(traj_collection)
traj_collection.plot(column='trajectory_id', legend=True, figsize=(9,5))
gdf = read_file('../data/geolife_small.gpkg')
gdf
After reading the trajectory point data from file, we want to construct the trajectories.
traj_collection = mpd.TrajectoryCollection(gdf, 'trajectory_id', t='t')
print(traj_collection)
traj_collection.plot(column='trajectory_id', legend=True, figsize=(9,5))
traj_collection.plot()
my_traj = traj_collection.trajectories[1]
print(my_traj)
my_traj.plot(linewidth=5, capstyle='round', figsize=(9,3))
To visualize trajectories in their geographical context, we can also create interactive plots with basemaps:
my_traj.hvplot(line_width=7.0, tiles='OSM')
df = pd.DataFrame(
{
"t": pd.date_range("2020-01-01", periods=5, freq="min"),
"trajectory_id": [1, 1, 2, 2, 2],
"geometry": [Point(0, 0), Point(0, 1), Point(1, 2), Point(1, 3), Point(2, 4)],
}
)
gdf = gpd.GeoDataFrame(df, crs=4326)
tc = mpd.TrajectoryCollection(gdf, traj_id_col='trajectory_id', t='t')
tc
tc.hvplot()
min_duration = timedelta(minutes=1)
tc.trajectories = [traj for traj in tc if traj.get_duration() > min_duration]
tc