Пример #1
0
def make_prop_lines(gdf, field_name, color='red', normalize_values=False,
                    norm_min=None, norm_max=None, axes=None):
    """
    Display a GeoDataFrame collection of (Multi)LineStrings,
    proportionaly to numerical field.

    Parameters
    ----------
    gdf: GeoDataFrame
        The collection of linestring/multilinestring to be displayed
    field_name: String
        The name of the field containing values to scale the line width of
        each border.
    color: String
        The color to render the lines with.
    normalize_values: Boolean, default False
        Normalize the value of the 'field_name' column between norm_min and
        norm_max.
    norm_min: float, default None
        The linewidth for the minimum value to plot.
    norm_max: float, default None
        The linewidth for the maximum value to plot.
    axes:
        Axes on which to draw the plot.

    Return
    ------
    axes: matplotlib.axes._subplots.AxesSubplot
    """
    from geopandas.plotting import plot_linestring, plot_multilinestring
    from shapely.geometry import MultiLineString
    import matplotlib.pyplot as plt

    if normalize_values and norm_max and norm_min:
        vals = (norm_max - norm_min) * (normalize(gdf[field_name].astype(float))).T + norm_min
    elif normalize_values:
        print('Warning : values where not normalized '
              '(norm_max or norm_min is missing)')
        vals = gdf[field_name].values
    else:
        vals = gdf[field_name].values

    if not axes:
        axes = plt.gca()
    for nbi, line in enumerate(gdf.geometry.values):
        if isinstance(line, MultiLineString):
            plot_multilinestring(axes, gdf.geometry.iloc[nbi],
                                 linewidth=vals[nbi], color=color)
        else:
            plot_linestring(axes, gdf.geometry.iloc[nbi],
                            linewidth=vals[nbi], color=color)
    return axes
Пример #2
0
def make_prop_lines(gdf, field_name, color="red", normalize_values=False, norm_min=None, norm_max=None, axes=None):
    """
    Display a GeoDataFrame collection of (Multi)LineStrings,
    proportionaly to numerical field.

    Parameters
    ----------
    gdf: GeoDataFrame
        The collection of linestring/multilinestring to be displayed
    field_name: String
        The name of the field containing values to scale the line width of
        each border.
    color: String
        The color to render the lines with.
    normalize_values: Boolean, default False
        Normalize the value of the 'field_name' column between norm_min and
        norm_max.
    norm_min: float, default None
        The linewidth for the minimum value to plot.
    norm_max: float, default None
        The linewidth for the maximum value to plot.
    axes:
        Axes on which to draw the plot.

    Return
    ------
    axes: matplotlib.axes._subplots.AxesSubplot
    """
    from geopandas.plotting import plot_linestring, plot_multilinestring
    from shapely.geometry import MultiLineString
    import matplotlib.pyplot as plt

    if normalize_values and norm_max and norm_min:
        vals = (norm_max - norm_min) * (normalize(gdf[field_name].astype(float))).T + norm_min
    elif normalize_values:
        print("Warning : values where not normalized " "(norm_max or norm_min is missing)")
        vals = gdf[field_name].values
    else:
        vals = gdf[field_name].values

    if not axes:
        axes = plt.gca()
    for nbi, line in enumerate(gdf.geometry.values):
        if isinstance(line, MultiLineString):
            plot_multilinestring(axes, gdf.geometry.iloc[nbi], linewidth=vals[nbi], color=color)
        else:
            plot_linestring(axes, gdf.geometry.iloc[nbi], linewidth=vals[nbi], color=color)
    return axes
Пример #3
0
def m_plot_dataframe(s,
                     column=None,
                     colormap=None,
                     alpha=0.5,
                     edgecolor=None,
                     categorical=False,
                     legend=False,
                     axes=None,
                     scheme=None,
                     contour_poly_width=0.5,
                     k=5):
    """ Plot a GeoDataFrame

        Generate a plot of a GeoDataFrame with matplotlib.  If a
        column is specified, the plot coloring will be based on values
        in that column.  Otherwise, a categorical plot of the
        geometries in the `geometry` column will be generated.

        Parameters
        ----------

        GeoDataFrame
            The GeoDataFrame to be plotted.  Currently Polygon,
            MultiPolygon, LineString, MultiLineString and Point
            geometries can be plotted.

        column : str (default None)
            The name of the column to be plotted.

        categorical : bool (default False)
            If False, colormap will reflect numerical values of the
            column being plotted.  For non-numerical columns (or if
            column=None), this will be set to True.

        colormap : str (default 'Set1')
            The name of a colormap recognized by matplotlib.

        alpha : float (default 0.5)
            Alpha value for polygon fill regions.  Has no effect for
            lines or points.

        legend : bool (default False)
            Plot a legend (Experimental; currently for categorical
            plots only)

        axes : matplotlib.pyplot.Artist (default None)
            axes on which to draw the plot

        scheme : pysal.esda.mapclassify.Map_Classifier
            Choropleth classification schemes

        k   : int (default 5)
            Number of classes (ignored if scheme is None)


        Returns
        -------

        matplotlib axes instance
    """
    import matplotlib.pyplot as plt
    from matplotlib.lines import Line2D
    from matplotlib.colors import Normalize
    from matplotlib import cm

    if column is None:
        return plot_series(s.geometry,
                           colormap=colormap,
                           alpha=alpha,
                           axes=axes)
    else:
        if s[column].dtype is np.dtype('O'):
            categorical = True
        if categorical:
            if colormap is None:
                colormap = 'Set1'
            categories = list(set(s[column].values))
            categories.sort()
            valuemap = dict([(key, v) for (v, key) in enumerate(categories)])
            values = [valuemap[key] for key in s[column]]
        else:
            values = s[column]
        if scheme is not None:
            values = __pysal_choro(values, scheme, k=k)
        cmap = norm_cmap(values, colormap, Normalize, cm)
        if not axes:
            fig = plt.gcf()
            fig.add_subplot(111, aspect='equal')
            ax = plt.gca()
        else:
            ax = axes
        for geom, value in zip(s.geometry, values):
            if geom.type == 'Polygon' or geom.type == 'MultiPolygon':
                m_plot_multipolygon(ax,
                                    geom,
                                    facecolor=cmap.to_rgba(value),
                                    edgecolor=edgecolor,
                                    linewidth=contour_poly_width,
                                    alpha=alpha)
            elif geom.type == 'LineString' or geom.type == 'MultiLineString':
                plot_multilinestring(ax, geom, color=cmap.to_rgba(value))
            # TODO: color point geometries
            elif geom.type == 'Point':
                plot_point(ax, geom)
        if legend:
            if categorical:
                patches = []
                for value, cat in enumerate(categories):
                    patches.append(
                        Line2D([0], [0],
                               linestyle="none",
                               marker="o",
                               alpha=alpha,
                               markersize=10,
                               markerfacecolor=cmap.to_rgba(value)))
                ax.legend(patches, categories, numpoints=1, loc='best')
            else:
                # TODO: show a colorbar
                raise NotImplementedError
    plt.draw()
    return ax
Пример #4
0
def m_plot_dataframe(s, column=None, colormap=None, alpha=0.5, edgecolor=None,
                     categorical=False, legend=False, axes=None, scheme=None,
                     contour_poly_width=0.5,
                     k=5):
    """ Plot a GeoDataFrame

        Generate a plot of a GeoDataFrame with matplotlib.  If a
        column is specified, the plot coloring will be based on values
        in that column.  Otherwise, a categorical plot of the
        geometries in the `geometry` column will be generated.

        Parameters
        ----------

        GeoDataFrame
            The GeoDataFrame to be plotted.  Currently Polygon,
            MultiPolygon, LineString, MultiLineString and Point
            geometries can be plotted.

        column : str (default None)
            The name of the column to be plotted.

        categorical : bool (default False)
            If False, colormap will reflect numerical values of the
            column being plotted.  For non-numerical columns (or if
            column=None), this will be set to True.

        colormap : str (default 'Set1')
            The name of a colormap recognized by matplotlib.

        alpha : float (default 0.5)
            Alpha value for polygon fill regions.  Has no effect for
            lines or points.

        legend : bool (default False)
            Plot a legend (Experimental; currently for categorical
            plots only)

        axes : matplotlib.pyplot.Artist (default None)
            axes on which to draw the plot

        scheme : pysal.esda.mapclassify.Map_Classifier
            Choropleth classification schemes

        k   : int (default 5)
            Number of classes (ignored if scheme is None)


        Returns
        -------

        matplotlib axes instance
    """
    import matplotlib.pyplot as plt
    from matplotlib.lines import Line2D
    from matplotlib.colors import Normalize
    from matplotlib import cm

    if column is None:
        return plot_series(s.geometry, colormap=colormap, alpha=alpha, axes=axes)
    else:
        if s[column].dtype is np.dtype('O'):
            categorical = True
        if categorical:
            if colormap is None:
                colormap = 'Set1'
            categories = list(set(s[column].values))
            categories.sort()
            valuemap = dict([(key, v) for (v, key) in enumerate(categories)])
            values = [valuemap[key] for key in s[column]]
        else:
            values = s[column]
        if scheme is not None:
            values = __pysal_choro(values, scheme, k=k)
        cmap = norm_cmap(values, colormap, Normalize, cm)
        if not axes:
            fig = plt.gcf()
            fig.add_subplot(111, aspect='equal')
            ax = plt.gca()
        else:
            ax = axes
        for geom, value in zip(s.geometry, values):
            if geom.type == 'Polygon' or geom.type == 'MultiPolygon':
                m_plot_multipolygon(ax, geom, facecolor=cmap.to_rgba(value),
                                    edgecolor=edgecolor,
                                    linewidth=contour_poly_width, alpha=alpha)
            elif geom.type == 'LineString' or geom.type == 'MultiLineString':
                plot_multilinestring(ax, geom, color=cmap.to_rgba(value))
            # TODO: color point geometries
            elif geom.type == 'Point':
                plot_point(ax, geom)
        if legend:
            if categorical:
                patches = []
                for value, cat in enumerate(categories):
                    patches.append(Line2D([0], [0], linestyle="none",
                                          marker="o", alpha=alpha,
                                          markersize=10,
                                          markerfacecolor=cmap.to_rgba(value)))
                ax.legend(patches, categories, numpoints=1, loc='best')
            else:
                # TODO: show a colorbar
                raise NotImplementedError
    plt.draw()
    return ax