コード例 #1
0
ファイル: visualization.py プロジェクト: jnetosoares/PyMove
def _add_trajectories_to_folium_map(
    move_data,
    items,
    base_map,
    legend=True,
    save_as_html=True,
    filename='map.html',
):
    """
    Adds a trajectory to a folium map with begin and end markers.

    Parameters
    ----------
    move_data : pymove.core.MoveDataFrameAbstract subclass.
        Input trajectory data.
    legend: boolean, default True
        Whether to add a legend to the map
    base_map : folium.folium.Map, optional, default None.
        Represents the folium map. If not informed, a new map is generated.
    save_as_html : bool, optional, default False.
        Represents if want save this visualization in a new file .html.
    filename : String, optional, default 'plot_trajectory_by_period.html'.
        Represents the file name of new file .html.

    """

    for _id, color in items:
        mv = move_data[move_data[TRAJ_ID] == _id]

        _add_begin_end_markers_to_folium_map(move_data, base_map)

        folium.PolyLine(mv[[LATITUDE, LONGITUDE]],
                        color=color,
                        weight=2.5,
                        opacity=1).add_to(base_map)

    if legend:
        add_map_legend(base_map, 'Color by user ID', items)

    if save_as_html:
        base_map.save(outfile=filename)
コード例 #2
0
ファイル: visualization.py プロジェクト: jnetosoares/PyMove
def plot_stops(
    move_data,
    radius=0,
    weight=3,
    id_=None,
    legend=True,
    n_rows=None,
    lat_origin=None,
    lon_origin=None,
    zoom_start=12,
    base_map=None,
    tile=TILES[0],
    save_as_html=False,
    color='black',
    filename='plot_stops.html',
):
    """
    Generate points on map that represents stops points with folium.

    Parameters
    ----------
    move_data : pymove.core.MoveDataFrameAbstract subclass.
        Input trajectory data.
    radius :  Double, optional(900 by default)
        The radius value is used to determine if a segment is a stop.
        If the value of the point in target_label is greater than
        radius, the segment is a stop, otherwise it'srs a move.
    weight: int or None
        Stroke width in pixels
    id_: int or None
        If int, plots trajectory of the user, else plot for all users
    legend: boolean, default True
        Whether to add a legend to the map
    n_rows : int, optional, default None.
        Represents number of data rows that are will plot.
    lat_origin : float, optional, default None.
        Represents the latitude which will be the center of the map.
        If not entered, the first data from the dataset is used.
    lon_origin : float, optional, default None.
        Represents the longitude which will be the center of the map.
        If not entered, the first data from the dataset is used.
    zoom_start : int, optional, default 12.
        Initial zoom level for the map
    base_map : folium.folium.Map, optional, default None.
        Represents the folium map. If not informed, a new map is generated
        using the function create_base_map(), with the lat_origin,
        lon_origin and zoom_start.
    tile : String, optional, default 'CartoDB positron'.
        Represents the map'srs tiles.
    save_as_html : bool, optional, default False.
        Represents if want save this visualization in a new file .html.
    color : String or List, optional, default 'black'.
        Represents line'srs color of visualization.
        Pass a list if plotting for many users. Else colors will be random
    filename : String, optional, default 'plot_stops.html'.
        Represents the file name of new file .html.

    Returns
    -------
    folium.folium.Map.
        Represents a folium map with visualization.

    Raises
    ------
    KeyError
        If no STOPs found
    IndexError
        If there is no user with the id passed

    """

    if base_map is None:
        base_map = create_base_map(
            move_data,
            lat_origin,
            lon_origin,
            tile=tile,
            default_zoom_start=zoom_start,
        )

    if SITUATION not in move_data:
        move_data.generate_move_and_stop_by_radius(radius=radius)

    mv_df = _filter_generated_feature(move_data, SITUATION, STOP)
    mv_df, items = _filter_and_generate_colors(mv_df, id_, n_rows, color)

    for _id, color in items:
        for stop in mv_df[mv_df[TRAJ_ID] == _id].iterrows():
            base_map.add_child(
                folium.Circle(
                    (stop[1][LATITUDE], stop[1][LONGITUDE]),
                    color=color,
                    weight=weight,
                    radius=40,
                    opacity=0.5,
                    popup=stop[1][DATETIME],
                    fill_color=color,
                    fill_opacity=0.5,
                ))

    if legend:
        add_map_legend(base_map, 'Color by user ID', items)

    if save_as_html:
        base_map.save(outfile=filename)
    else:
        return base_map
コード例 #3
0
def plot_trajectories_with_folium(
    move_data,
    n_rows=None,
    lat_origin=None,
    lon_origin=None,
    zoom_start=12,
    legend=False,
    base_map=None,
    tile=TILES[0],
    save_as_html=False,
    color="black",
    filename="plot_trajectories_with_folium.html",
):
    """
    Generate visualization of all trajectories with folium.

    Parameters
    ----------
    move_data : pymove.core.MoveDataFrameAbstract subclass.
        Input trajectory data.
    n_rows : int, optional, default None.
        Represents number of data rows that are will plot.
    lat_origin : float, optional, default None.
        Represents the latitude which will be the center of the map.
        If not entered, the first data from the dataset is used.
    lon_origin : float, optional, default None.
        Represents the longitude which will be the center of the map.
        If not entered, the first data from the dataset is used.
    zoom_start : int, optional, default 12.
        Initial zoom level for the map
    legend: boolean
        Whether to add a legend to the map
    base_map : folium.folium.Map, optional, default None.
        Represents the folium map. If not informed, a new map is generated
        using the function create_base_map(), with the lat_origin, lon_origin
         and zoom_start.
    tile : String, optional, default 'OpenStreetMap'.
        Represents the map's tiles.
    save_as_html : bool, optional, default False.
        Represents if want save this visualization in a new file .html.
    color : String, optional, default 'black'.
        Represents line's color of visualization.
    filename : String, optional, default 'plot_trajectory_with_folium.html'.
        Represents the file name of new file .html.

    Returns
    -------
    base_map : folium.folium.Map.
        Represents a folium map with visualization.
    """

    if base_map is None:
        if lat_origin is None and lon_origin is None:
            lat_origin = move_data.loc[0][LATITUDE]
            lon_origin = move_data.loc[0][LONGITUDE]
        base_map = create_base_map(
            default_location=[lat_origin, lon_origin],
            tile=tile,
            default_zoom_start=zoom_start,
        )

    if n_rows is None:
        n_rows = move_data.shape[0]

    mv_df = move_data.loc[:n_rows,
                          [LATITUDE, LONGITUDE, TRAJ_ID]].reset_index()

    ids = mv_df[TRAJ_ID].unique()
    if isinstance(color, str):
        colors = [generate_color() for _ in ids]
    else:
        colors = color[:]
    items = list(zip(ids, colors))

    for _id, color in items:
        mv = mv_df[mv_df[TRAJ_ID] == _id]
        folium.Marker(
            location=[mv.iloc[0][LATITUDE], mv.iloc[0][LONGITUDE]],
            color="green",
            clustered_marker=True,
            popup="Início",
            icon=folium.Icon(color="green", icon="info-sign"),
        ).add_to(base_map)

        folium.Marker(
            location=[mv.iloc[-1][LATITUDE], mv.iloc[-1][LONGITUDE]],
            color="red",
            clustered_marker=True,
            popup="Fim",
            icon=folium.Icon(color="red", icon="info-sign"),
        ).add_to(base_map)

        folium.PolyLine(mv[[LATITUDE, LONGITUDE]],
                        color=color,
                        weight=2.5,
                        opacity=1).add_to(base_map)

    if legend:
        add_map_legend(base_map, "Color by user ID", items)

    if save_as_html:
        base_map.save(outfile=filename)
    else:
        return base_map
コード例 #4
0
def plot_trajectory_by_period(
    move_data,
    period,
    id_=None,
    legend=True,
    n_rows=None,
    lat_origin=None,
    lon_origin=None,
    zoom_start=12,
    base_map=None,
    tile=TILES[0],
    save_as_html=False,
    color="black",
    filename="plot_trajectory_by_period_with_folium.html",
):
    """
    Generate trajectory view by period of day provided by user.

    Parameters
    ----------
    move_data : pymove.core.MoveDataFrameAbstract subclass.
        Input trajectory data.
    period: String
        Represents period of day.
    id_: int or None
        If int, plots trajectory of the user, else plot for all users
    legend: boolean
        Whether to add a legend to the map
    n_rows : int, optional, default None.
        Represents number of data rows that are will plot.
    lat_origin : float, optional, default None.
        Represents the latitude which will be the center of the map.
        If not entered, the first data from the dataset is used.
    lon_origin : float, optional, default None.
        Represents the longitude which will be the center of the map.
        If not entered, the first data from the dataset is used.
    zoom_start : int, optional, default 12.
        Initial zoom level for the map
    base_map : folium.folium.Map, optional, default None.
        Represents the folium map. If not informed, a new map is generated
        using the function create_base_map(), with the lat_origin,
        lon_origin and zoom_start.
    tile : String, optional, default 'OpenStreetMap'.
        Represents the map's tiles.
    save_as_html : bool, optional, default False.
        Represents if want save this visualization in a new file .html.
    color : String or List, optional, default 'black'.
        Represents line's color of visualization.
        Pass a list if ploting for many users. Else colors will be chosen at random
    filename : String, optional, default 'plot_trajectory_by_period.html'.
        Represents the file name of new file .html.

    Returns
    -------
    base_map : folium.folium.Map.
        Represents a folium map with visualization.

    Raises
    ------
        KeyError period not found in dataframe
        IndexError if there is no user with the id passed
    """
    if base_map is None:
        if lat_origin is None and lon_origin is None:
            lat_origin = move_data.loc[0][LATITUDE]
            lon_origin = move_data.loc[0][LONGITUDE]
        base_map = create_base_map(
            default_location=[lat_origin, lon_origin],
            tile=tile,
            default_zoom_start=zoom_start,
        )

    if PERIOD not in move_data:
        move_data.generate_time_of_day_features()

    mv_df = move_data[move_data[PERIOD] == period].reset_index()
    if not len(mv_df):
        raise KeyError(f"No PERIOD found in dataframe")

    if n_rows is None:
        n_rows = mv_df.shape[0]

    if id_ is not None:
        mv_df = mv_df[mv_df[TRAJ_ID] ==
                      id_].loc[:n_rows, [LATITUDE, LONGITUDE, TRAJ_ID]]
        if not len(mv_df):
            raise IndexError(f"No user with id {id_} in dataframe")
    else:
        mv_df = mv_df.loc[:n_rows, [LATITUDE, LONGITUDE, TRAJ_ID]]

    if id_ is not None:
        items = list(zip([id_], [color]))
    else:
        ids = mv_df[TRAJ_ID].unique()
        if isinstance(color, str):
            colors = [generate_color() for _ in ids]
        else:
            colors = color[:]
        items = list(zip(ids, colors))

    for _id, color in items:
        mv = mv_df[mv_df[TRAJ_ID] == _id]
        folium.Marker(
            location=[mv.iloc[0][LATITUDE], mv.iloc[0][LONGITUDE]],
            color="green",
            clustered_marker=True,
            popup="Início",
            icon=folium.Icon(color="green", icon="info-sign"),
        ).add_to(base_map)

        folium.Marker(
            location=[mv.iloc[-1][LATITUDE], mv.iloc[-1][LONGITUDE]],
            color="red",
            clustered_marker=True,
            popup="Fim",
            icon=folium.Icon(color="red", icon="info-sign"),
        ).add_to(base_map)

        folium.PolyLine(mv[[LATITUDE, LONGITUDE]],
                        color=color,
                        weight=2.5,
                        opacity=1).add_to(base_map)

    if id_ is None and legend:
        add_map_legend(base_map, "Color by user ID", items)

    if save_as_html:
        base_map.save(outfile=filename)
    else:
        return base_map
コード例 #5
0
def plot_stops(
    move_data,
    radius=0,
    weight=3,
    id_=None,
    legend=True,
    n_rows=None,
    lat_origin=None,
    lon_origin=None,
    zoom_start=12,
    base_map=None,
    tile=TILES[0],
    save_as_html=False,
    color="black",
    filename="plot_stops.html",
):
    """
    Generate points on map that represents stops points with folium.

    Parameters
    ----------
    move_data : pymove.core.MoveDataFrameAbstract subclass.
        Input trajectory data.
    radius :  Double, optional(900 by default)
        The radius value is used to determine if a segment is a stop.
        If the value of the point in target_label is greater than
        radius, the segment is a stop, otherwise it's a move.
    weight: int or None
        Stroke width in pixels
    id_: int or None
        If int, plots trajectory of the user, else plot for all users
    legend: boolean
        Whether to add a legend to the map
    n_rows : int, optional, default None.
        Represents number of data rows that are will plot.
    lat_origin : float, optional, default None.
        Represents the latitude which will be the center of the map.
        If not entered, the first data from the dataset is used.
    lon_origin : float, optional, default None.
        Represents the longitude which will be the center of the map.
        If not entered, the first data from the dataset is used.
    zoom_start : int, optional, default 12.
        Initial zoom level for the map
    base_map : folium.folium.Map, optional, default None.
        Represents the folium map. If not informed, a new map is generated
        using the function create_base_map(), with the lat_origin,
        lon_origin and zoom_start.
    tile : String, optional, default 'OpenStreetMap'.
        Represents the map's tiles.
    save_as_html : bool, optional, default False.
        Represents if want save this visualization in a new file .html.
    color : String or List, optional, default 'black'.
        Represents line's color of visualization.
        Pass a list if ploting for many users. Else colors will be chosen at random
    filename : String, optional, default 'plot_stops.html'.
        Represents the file name of new file .html.

    Returns
    -------
    base_map : folium.folium.Map.
        Represents a folium map with visualization.

    Raises
        ------
        KeyError if no STOPs found
        IndexError if there is no user with the id passed
    """
    if base_map is None:
        if lat_origin is None and lon_origin is None:
            lat_origin = move_data.loc[0][LATITUDE]
            lon_origin = move_data.loc[0][LONGITUDE]
        base_map = create_base_map(
            default_location=[lat_origin, lon_origin],
            tile=tile,
            default_zoom_start=zoom_start,
        )

    if SITUATION not in move_data:
        move_data.generate_move_and_stop_by_radius(radius=radius)

    stops = move_data[move_data[SITUATION] == STOP].reset_index()
    if not len(stops):
        raise KeyError(f"No STOPS found in dataframe")

    if n_rows is None:
        n_rows = stops.shape[0]

    if id_ is not None:
        stops = stops[stops[TRAJ_ID] ==
                      id_].loc[:n_rows,
                               [LATITUDE, LONGITUDE, DATETIME, TRAJ_ID]]
        if not len(stops):
            raise IndexError(f"No user with id {id_} in dataframe")
    else:
        stops = stops.loc[:n_rows, [LATITUDE, LONGITUDE, DATETIME, TRAJ_ID]]

    if id_ is not None:
        items = list(zip([id_], [color]))
    else:
        ids = stops[TRAJ_ID].unique()
        if isinstance(color, str):
            colors = [generate_color() for _ in ids]
        else:
            colors = color[:]
        items = list(zip(ids, colors))

    for _id, color in items:
        for stop in stops[stops[TRAJ_ID] == _id].iterrows():
            base_map.add_child(
                folium.Circle(
                    (stop[1][LATITUDE], stop[1][LONGITUDE]),
                    color=color,
                    weight=weight,
                    radius=30,
                    opacity=0.5,
                    popup=stop[1][DATETIME],
                    fill_color=color,
                    fill_opacity=0.5,
                ))
    if id_ is None and legend:
        add_map_legend(base_map, "Color by user ID", items)

    if save_as_html:
        base_map.save(outfile=filename)
    else:
        return base_map