def plot_triplegs(triplegs,
                  out_filename=None,
                  positionfixes=None,
                  staypoints=None,
                  staypoints_radius=None,
                  plot_osm=False):
    """Plots triplegs (optionally to a file).

    Parameters
    ----------
    triplegs : GeoDataFrame
        The triplegs to plot.
    
    out_filename : str
        The file to plot to, if this is not set, the plot will simply be shown.

    positionfixes : GeoDataFrame
        If available, some positionfixes that can additionally be plotted.

    plot_osm : bool
        If this is set to True, it will download an OSM street network and plot 
        below the triplegs.
    """
    _, ax = regular_figure()

    if plot_osm:
        if positionfixes is not None:
            west = positionfixes.geometry.x.min()
            east = positionfixes.geometry.x.max()
            north = positionfixes.geometry.y.max()
            south = positionfixes.geometry.y.min()
        else:
            triplegs_bounds = triplegs.bounds
            west = min(triplegs_bounds.minx
                       ) - 0.03  #TODO: maybe a relative value instead of 0.03
            east = max(triplegs_bounds.maxx) + 0.03
            north = max(triplegs_bounds.maxy) + 0.03
            south = min(triplegs_bounds.miny) - 0.03
        plot_osm_streets(north, south, east, west, ax)

    if positionfixes is not None:
        positionfixes.plot(ax=ax, markersize=0.5, zorder=2)

    if staypoints is not None:
        if staypoints_radius is None:
            staypoints_radius = 3
        for pt in staypoints.to_dict('records'):
            circle = mpatches.Circle((pt.geometry.x, pt.geometry.y),
                                     staypoints_radius,
                                     facecolor='none',
                                     edgecolor='c',
                                     zorder=3)
            ax.add_artist(circle)

    triplegs.plot(ax=ax, cmap='viridis')

    if out_filename is not None:
        save_fig(out_filename, formats=['png'])
    else:
        plt.show()
示例#2
0
def plot_positionfixes(positionfixes, out_filename=None, plot_osm=False):
    """Plots positionfixes (optionally to a file). If you specify ``plot_osm=True``
    this will use ``osmnx`` to plot streets below the positionfixes. Depending on
    the extent of your data, this might take a long time. 

    Parameters
    ----------
    positionfixes : GeoDataFrame
        The positionfixes to plot.
    
    out_filename : str, optional
        The file to plot to, if this is not set, the plot will simply be shown.

    plot_osm : bool, default False
        If this is set to True, it will download an OSM street network and plot 
        below the staypoints.

    Examples
    --------
    >>> df.as_positionfixes.plot('output.png', plot_osm=True)
    """
    _, ax = regular_figure()

    if plot_osm:
        west = positionfixes['geom'].x.min()
        east = positionfixes['geom'].x.max()
        north = positionfixes['geom'].y.max()
        south = positionfixes['geom'].y.min()
        plot_osm_streets(north, south, east, west, ax)

    positionfixes.plot(ax=ax, markersize=0.5)
    if out_filename is not None:
        save_fig(out_filename, formats=['png'])
    else:
        plt.show()
示例#3
0
    def test_axis(self, test_data):
        """Test the use of regular_figure() to create axis."""
        _, _, tpls = test_data
        tmp_file = os.path.join("tests", "data", "triplegs_plot2.png")
        _, ax = regular_figure()

        tpls.as_triplegs.plot(out_filename=tmp_file, axis=ax)
        assert os.path.exists(tmp_file)
        os.remove(tmp_file)
示例#4
0
def plot_positionfixes(positionfixes,
                       out_filename=None,
                       plot_osm=False,
                       axis=None):
    """Plots positionfixes (optionally to a file).

    If you specify ``plot_osm=True`` this will use ``osmnx`` to plot streets
    below the positionfixes. Depending on the extent of your data, this might
    take a long time. The data gets transformed to wgs84 for the plotting.

    Parameters
    ----------
    positionfixes : GeoDataFrame (as trackintel positionfixes)
        The positionfixes to plot.

    out_filename : str, optional
        The file to plot to, if this is not set, the plot will simply be shown.

    plot_osm : bool, default False
        If this is set to True, it will download an OSM street network and plot
        below the staypoints.

    axis : matplotlib.pyplot.Artist, optional
        axis on which to draw the plot

    Examples
    --------
    >>> pfs.as_positionfixes.plot('output.png', plot_osm=True)
    """
    if axis is None:
        _, ax = regular_figure()
    else:
        ax = axis
    _, positionfixes = check_gdf_planar(positionfixes, transform=True)

    if plot_osm:
        west = positionfixes.geometry.x.min()
        east = positionfixes.geometry.x.max()
        north = positionfixes.geometry.y.max()
        south = positionfixes.geometry.y.min()
        plot_osm_streets(north, south, east, west, ax)

    positionfixes.plot(ax=ax, markersize=0.5, zorder=2)
    ax.set_aspect("equal", adjustable="box")

    if out_filename is not None:
        save_fig(out_filename, formats=["png"])
    elif axis is None:
        plt.show()
示例#5
0
    def test_axis(self, test_data):
        """Test the use of regular_figure() to create axis."""
        pfs, _, locs = test_data
        tmp_file = os.path.join("tests", "data", "locations_plot2.png")
        _, ax = regular_figure()

        locs.as_locations.plot(
            out_filename=tmp_file,
            radius=120,
            positionfixes=pfs,
            plot_osm=False,
            axis=ax,
        )
        assert os.path.exists(tmp_file)
        os.remove(tmp_file)
示例#6
0
def plot_modal_split(df_modal_split_in,
                     out_path=None,
                     date_fmt_x_axis='%W',
                     axis=None,
                     title=None,
                     x_label=None,
                     y_label=None,
                     x_pad=10,
                     y_pad=10,
                     title_pad=1.02,
                     skip_xticks=0,
                     n_col_legend=5,
                     borderaxespad=0.5):
    """
    Plot modal split as returned by `trackintel.analysis.modal_split.calculate_modal_split`

    Parameters
    ----------
    df_modal_split : DataFrame
        DataFrame with modal split information. Format is
    out_path : str, optional
        Path to store the figure
    date_fmt_x_axis : str, default: '%W'
        strftime() date format code that is used for the x-axis
    title : str, optional
    x_label : str, optional
    y_label : str, optional
    axis : matplotlib axes
    x_pad : float, default: 10
        used to set ax.xaxis.labelpad
    y_pad : float, default: 10
        used to set ax.yaxis.labelpad
    title_pad : float, default: 1.02
        passed on to `matplotlib.pyplot.title`
    skip_xticks : int, default: 0
        if larger than 0, every nth x-tick label is skipped.
    n_col_legend : int
        passed on as `ncol` to matplotlib.pyplot.legend()
    borderaxespad : float
        passed on to matplotlib.pyplot.legend()

    Returns
    -------
    fig : Matplotlib figure handle
    ax : Matplotlib axis handle

    Examples
    --------
    >>> modal_split = calculate_modal_split(triplegs, metric='count', freq='D', per_user=False)
    >>> plot_modal_split(modal_split, out_path=tmp_file, date_fmt_x_axis='%d',
    >>>                  y_label='Percentage of daily count', x_label='days')
    """

    df_modal_split = df_modal_split_in.copy()
    if axis is None:
        fig, ax = regular_figure()
    else:
        ax = axis

    # make sure that modal split is only of a single user
    if isinstance(df_modal_split.index[0], tuple):
        raise ValueError(
            "This function can not support multiindex types. Use 'pandas.MultiIndex.droplevel' or pass "
            "the `per_user=False` flag in 'calculate_modal_split' function.")

    if not is_datetime64_any_dtype(df_modal_split.index.dtype):
        raise ValueError(
            "Index of modal split has to be a datetime type. This problem can be solved if the 'freq' "
            "keyword of 'calculate_modal_split is not None'")
    # set date formatter
    df_modal_split.index = df_modal_split.index.map(
        lambda s: s.strftime(date_fmt_x_axis))

    # plotting
    df_modal_split.plot.bar(stacked=True, ax=ax)

    # skip ticks for X axis
    if skip_xticks > 0:
        for i, tick in enumerate(ax.xaxis.get_major_ticks()):
            if (i % skip_xticks == 0):
                tick.set_visible(False)

    # We use a nice trick to put the legend out of the plot and to scale it automatically
    # https://stackoverflow.com/questions/4700614/how-to-put-the-legend-out-of-the-plot
    box = ax.get_position()
    ax.set_position(
        [box.x0, box.y0 + box.height * 0.1, box.width, box.height * 0.9])

    # Put a legend below current axis
    ax.legend(loc='upper center',
              bbox_to_anchor=(0.5, -0.05),
              fancybox=True,
              frameon=False,
              ncol=n_col_legend,
              borderaxespad=borderaxespad)

    if title is not None:
        plt.title(title, y=title_pad)

    ax.set_xlabel(x_label)
    ax.set_ylabel(y_label)
    fig.autofmt_xdate()

    plt.tight_layout()

    ax.xaxis.labelpad = x_pad
    ax.yaxis.labelpad = y_pad

    if out_path is not None:
        save_fig(out_path)

    return fig, ax
def plot_staypoints(staypoints,
                    out_filename=None,
                    radius=None,
                    positionfixes=None,
                    plot_osm=False):
    """Plots staypoints (optionally to a file). You can specify the radius with which 
    each staypoint should be drawn, as well as if underlying positionfixes and OSM streets
    should be drawn.

    Parameters
    ----------
    staypoints : GeoDataFrame
        The staypoints to plot.
    
    out_filename : str, optional
        The file to plot to, if this is not set, the plot will simply be shown.

    radius : float, optional
        The radius with which circles around staypoints should be drawn.

    positionfixes : GeoDataFrame, optional
        If available, some positionfixes that can additionally be plotted.

    plot_osm : bool, default False
        If this is set to True, it will download an OSM street network and plot 
        below the staypoints.

    Examples
    --------
    >>> df.as_staypoints.plot('output.png', radius=10, positionfixes=pdf, plot_osm=True)
    """
    _, ax = regular_figure()
    name_geocol = staypoints.geometry.name

    if positionfixes is not None:
        west = positionfixes.geometry.x.min() - 0.01
        east = positionfixes.geometry.x.max() + 0.01
        north = positionfixes.geometry.y.max() + 0.01
        south = positionfixes.geometry.y.min() - 0.01
    else:
        west = staypoints.geometry.x.min() - 0.03
        east = staypoints.geometry.x.max() + 0.03
        north = staypoints.geometry.y.max() + 0.03
        south = staypoints.geometry.y.min() - 0.03

    if plot_osm:
        plot_osm_streets(north, south, east, west, ax)

    if positionfixes is not None:
        positionfixes.plot(ax=ax, markersize=0.5, zorder=2)

    if radius is None:
        radius = 5
    for pt in staypoints.to_dict('records'):
        circle = mpatches.Circle((pt[name_geocol].x, pt[name_geocol].y),
                                 radius,
                                 facecolor='none',
                                 edgecolor='g',
                                 zorder=3)
        ax.add_artist(circle)

    ax.set_xlim([west, east])
    ax.set_ylim([south, north])

    if out_filename is not None:
        save_fig(out_filename, formats=['png'])
    else:
        plt.show()
def plot_center_of_locations(locations, out_filename=None, radius=None, positionfixes=None, 
                          staypoints=None, staypoints_radius=None, plot_osm=False):
    """Plots locations (optionally to a file). Optionally, you can specify several other
    datasets to be plotted beneath the locations.

    Parameters
    ----------
    locations : GeoDataFrame
        The locations to plot.
    
    out_filename : str, optional
        The file to plot to, if this is not set, the plot will simply be shown.

    radius : float, optional
        The radius with which circles around locations should be drawn.

    positionfixes : GeoDataFrame, optional
        If available, some positionfixes that can additionally be plotted.

    staypoints : GeoDataFrame, optional
        If available, some staypoints that can additionally be plotted.

    plot_osm : bool, default False
        If this is set to True, it will download an OSM street network and plot 
        below the staypoints.

    Examples
    --------
    >>> df.as_locations.plot('output.png', radius=10, positionfixes=pdf, 
    >>>                   staypoints=spf, staypoints_radius=8, plot_osm=True)
    """
    _, ax = regular_figure()

    if plot_osm:
        if positionfixes is not None:
            west = positionfixes.geometry.x.min()
            east = positionfixes.geometry.x.max()
            north = positionfixes.geometry.y.max()
            south = positionfixes.geometry.y.min()
        else:
            west = locations['center'].x.min() - 0.03
            east = locations['center'].x.max() + 0.03
            north = locations['center'].y.max() + 0.03
            south = locations['center'].y.min() - 0.03
        plot_osm_streets(north, south, east, west, ax)

    if positionfixes is not None:
        positionfixes.plot(ax=ax, markersize=0.5, zorder=2)

    if staypoints is not None:
        if staypoints_radius is None:
            staypoints_radius = 3
        for pt in staypoints.to_dict('records'):
            circle = mpatches.Circle((pt.geometry.x, pt.geometry.y), staypoints_radius,
                                     facecolor='none', edgecolor='c', zorder=3)
            ax.add_artist(circle)

    if radius is None:
        radius = 5
    for pt in locations.to_dict('records'):
        circle = mpatches.Circle((pt['center'].x, pt['center'].y), radius, 
                                  facecolor='none', edgecolor='r', zorder=4)
        ax.add_artist(circle)
    if out_filename is not None:
        save_fig(out_filename, formats=['png'])
    else:
        plt.show()
示例#9
0
def plot_staypoints(staypoints, out_filename=None, radius=100, positionfixes=None, plot_osm=False, axis=None):
    """Plot staypoints (optionally to a file).

    You can specify the radius with which  each staypoint should be drawn, as well as
    if underlying positionfixes and OSM streets should be drawn. The data gets transformed
    to wgs84 for the plotting.

    Parameters
    ----------
    staypoints : GeoDataFrame (as trackintel staypoints)
        The staypoints to plot.

    out_filename : str, optional
        The file to plot to, if this is not set, the plot will simply be shown.

    radius : float, default 100 (meter)
        The radius in meter with which circles around staypoints should be drawn.

    positionfixes : GeoDataFrame (as trackintel positionfixes), optional
        If available, some positionfixes that can additionally be plotted.

    plot_osm : bool, default False
        If this is set to True, it will download an OSM street network and plot
        below the staypoints.

    axis : matplotlib.pyplot.Artist, optional
        axis on which to draw the plot

    Examples
    --------
    >>> stps.as_staypoints.plot('output.png', radius=100, positionfixes=pfs, plot_osm=True)
    """
    if axis is None:
        _, ax = regular_figure()
    else:
        ax = axis
    name_geocol = staypoints.geometry.name
    _, staypoints = check_gdf_crs(staypoints, transform=True)

    if positionfixes is not None:
        positionfixes.as_positionfixes.plot(plot_osm=plot_osm, axis=ax)
    else:
        west = staypoints.geometry.x.min() - 0.03
        east = staypoints.geometry.x.max() + 0.03
        north = staypoints.geometry.y.max() + 0.03
        south = staypoints.geometry.y.min() - 0.03
        if plot_osm:
            plot_osm_streets(north, south, east, west, ax)
        ax.set_xlim([west, east])
        ax.set_ylim([south, north])

    center_latitude = (ax.get_ylim()[0] + ax.get_ylim()[1]) / 2
    radius = meters_to_decimal_degrees(radius, center_latitude)
    for pt in staypoints.to_dict("records"):
        circle = mpatches.Circle(
            (pt[name_geocol].x, pt[name_geocol].y), radius, facecolor="none", edgecolor="g", zorder=3
        )
        ax.add_artist(circle)

    ax.set_aspect("equal", adjustable="box")
    if out_filename is not None:
        save_fig(out_filename, formats=["png"])
    elif axis is None:
        plt.show()
示例#10
0
def plot_triplegs(triplegs,
                  out_filename=None,
                  positionfixes=None,
                  staypoints=None,
                  staypoints_radius=100,
                  plot_osm=False,
                  axis=None):
    """Plot triplegs (optionally to a file).

    You can specify several other datasets to be plotted beneath the triplegs,
    as well as if the OSM streets should be drawn. The data gets transformed to
    wgs84 for the plotting.

    Parameters
    ----------
    triplegs : GeoDataFrame (as trackintel triplegs)
        The triplegs to plot.

    out_filename : str, optional
        The file to plot to, if this is not set, the plot will simply be shown.

    positionfixes : GeoDataFrame (as trackintel positionfixes), optional
        If available, some positionfixes that can additionally be plotted.

    staypoints : GeoDataFrame (as trackintel staypoints), optional
        If available, some staypoints that can additionally be plotted.

    staypoints_radius : float, default 100 (meter)
        The radius in meter with which circles around staypoints should be drawn.

    plot_osm : bool, default False
        If this is set to True, it will download an OSM street network and plot
        below the triplegs.

    axis : matplotlib.pyplot.Artist, optional
        axis on which to draw the plot

    Example
    -------
    >>> tpls.as_triplegs.plot('output.png', positionfixes=pfs, staypoints=sp, plot_osm=True)
    """
    if axis is None:
        _, ax = regular_figure()
    else:
        ax = axis
    _, triplegs = check_gdf_planar(triplegs, transform=True)

    if staypoints is not None:
        staypoints.as_staypoints.plot(radius=staypoints_radius,
                                      positionfixes=positionfixes,
                                      plot_osm=plot_osm,
                                      axis=ax)
    elif positionfixes is not None:
        positionfixes.as_positionfixes.plot(plot_osm=plot_osm, axis=ax)
    elif plot_osm:
        triplegs_bounds = triplegs.bounds
        west = min(triplegs_bounds.minx
                   ) - 0.03  # TODO: maybe a relative value instead of 0.03
        east = max(triplegs_bounds.maxx) + 0.03
        north = max(triplegs_bounds.maxy) + 0.03
        south = min(triplegs_bounds.miny) - 0.03
        plot_osm_streets(north, south, east, west, ax)

    triplegs.plot(ax=ax, cmap="viridis")
    ax.set_aspect("equal", adjustable="box")

    if out_filename is not None:
        save_fig(out_filename, formats=["png"])
    else:
        plt.show()
示例#11
0
def plot_center_of_locations(
    locations,
    out_filename=None,
    radius=None,
    positionfixes=None,
    staypoints=None,
    staypoints_radius=None,
    plot_osm=False,
    axis=None,
):
    """Plot locations (optionally to a file).

    Optionally, you can specify several other datasets to be plotted beneath the locations.

    Parameters
    ----------
    locations : GeoDataFrame (as trackintel locations)
        The locations to plot.

    out_filename : str, optional
        The file to plot to, if this is not set, the plot will simply be shown.

    radius : float, optional
        The radius in meter with which circles around locations should be drawn.

    positionfixes : GeoDataFrame (as trackintel positionfixes), optional
        If available, some positionfixes that can additionally be plotted.

    staypoints : GeoDataFrame (as trackintel staypoints), optional
        If available, some staypoints that can additionally be plotted.

    staypoints_radius : float, optional
        The radius in meter with which circles around staypoints should be drawn.

    plot_osm : bool, default False
        If this is set to True, it will download an OSM street network and plot
        below the staypoints.

    axis : matplotlib.pyplot.Artist, optional
        axis on which to draw the plot

    Examples
    --------
    >>> df.as_locations.plot('output.png', radius=100, positionfixes=pdf,
    >>>                      staypoints=spf, staypoints_radius=80, plot_osm=True)
    """
    if axis is None:
        _, ax = regular_figure()
    else:
        ax = axis
    locations = transform_gdf_to_wgs84(locations)

    if staypoints is not None:
        staypoints.as_staypoints.plot(radius=staypoints_radius,
                                      positionfixes=positionfixes,
                                      plot_osm=plot_osm,
                                      axis=ax)
    elif positionfixes is not None:
        positionfixes.as_positionfixes.plot(plot_osm=plot_osm, axis=ax)
    elif plot_osm:
        west = locations["center"].x.min() - 0.03
        east = locations["center"].x.max() + 0.03
        north = locations["center"].y.max() + 0.03
        south = locations["center"].y.min() - 0.03
        plot_osm_streets(north, south, east, west, ax)

    if radius is None:
        radius = 125
    center_latitude = (ax.get_ylim()[0] + ax.get_ylim()[1]) / 2
    radius = meters_to_decimal_degrees(radius, center_latitude)
    for pt in locations.to_dict("records"):
        circle = mpatches.Circle((pt["center"].x, pt["center"].y),
                                 radius,
                                 facecolor="none",
                                 edgecolor="r",
                                 zorder=4)
        ax.add_artist(circle)
    if out_filename is not None:
        save_fig(out_filename, formats=["png"])
    else:
        plt.show()