How to use mapclassify - 10 common examples

To help you get started, we’ve selected a few mapclassify examples, based on popular ways it is used in public projects.

Secure your code as it's written. Use Snyk Code to scan source code in minutes - no build needed - and fix issues immediately.

github martinfleis / momepy / tests / test_diversity.py View on Github external
import geopandas as gpd
import momepy as mm
import numpy as np
import pytest
from momepy import sw_high
from pytest import approx

from distutils.version import LooseVersion

try:
    import mapclassify

    MC_21 = str(mapclassify.__version__) < LooseVersion("2.1.0")
except ImportError:
    import pysal

    MC_21 = str(pysal.__version__) < LooseVersion("2.1.0")


class TestDiversity:
    def setup_method(self):

        test_file_path = mm.datasets.get_path("bubenec")
        self.df_buildings = gpd.read_file(test_file_path, layer="buildings")
        self.df_streets = gpd.read_file(test_file_path, layer="streets")
        self.df_tessellation = gpd.read_file(test_file_path, layer="tessellation")
        self.df_buildings["height"] = np.linspace(10.0, 30.0, 144)
        self.df_tessellation["area"] = mm.Area(self.df_tessellation).series
        self.sw = sw_high(k=3, gdf=self.df_tessellation, ids="uID")
github ResidentMario / geoplot / examples / plot_obesity.py View on Github external
import pandas as pd
import geopandas as gpd
import geoplot as gplt
import geoplot.crs as gcrs
import matplotlib.pyplot as plt
import mapclassify as mc

# load the data
obesity_by_state = pd.read_csv(gplt.datasets.get_path('obesity_by_state'), sep='\t')
contiguous_usa = gpd.read_file(gplt.datasets.get_path('contiguous_usa'))
contiguous_usa['Obesity Rate'] = contiguous_usa['state'].map(
    lambda state: obesity_by_state.query("State == @state").iloc[0]['Percent']
)
scheme = mc.Quantiles(contiguous_usa['Obesity Rate'], k=5)


ax = gplt.cartogram(
    contiguous_usa,
    scale='Obesity Rate', limits=(0.75, 1),
    projection=gcrs.AlbersEqualArea(central_longitude=-98, central_latitude=39.5),
    hue='Obesity Rate', cmap='Reds', scheme=scheme,
    linewidth=0.5,
    legend=True, legend_kwargs={'loc': 'lower right'}, legend_var='hue',
    figsize=(8, 12)
)
gplt.polyplot(contiguous_usa, facecolor='lightgray', edgecolor='None', ax=ax)

plt.title("Adult Obesity Rate by State, 2013")
plt.savefig("obesity.png", bbox_inches='tight', pad_inches=0.1)
github geopandas / geopandas / examples / plotting_with_geoplot.py View on Github external
# use the Orthographic map projection (e.g. a world globe)
ax = geoplot.polyplot(
    world, projection=geoplot.crs.Orthographic(), figsize=(8, 4)
)
ax.outline_patch.set_visible(True)

###############################################################################
# ``polyplot`` is trivial and can only plot the geometries you pass to it. If
# you want to use color as a visual variable, specify a ``choropleth``. Here
# we sort GDP per person by country into five buckets by color, using
# "quantiles" binning from the `Mapclassify `_
# library.

import mapclassify
gpd_per_person = world['gdp_md_est'] / world['pop_est']
scheme = mapclassify.Quantiles(gpd_per_person, k=5)

# Note: this code sample requires geoplot>=0.4.0.
geoplot.choropleth(
    world, hue=gpd_per_person, scheme=scheme,
    cmap='Greens', figsize=(8, 4)
)

###############################################################################
# If you want to use size as a visual variable, use a ``cartogram``. Here are
# population estimates for countries in Africa.

africa = world.query('continent == "Africa"')
ax = geoplot.cartogram(
    africa, scale='pop_est', limits=(0.2, 1),
    edgecolor='None', figsize=(7, 8)
)
github ResidentMario / geoplot / examples / plot_largest_cities_usa.py View on Github external
This example, taken from the User Guide, plots cities in the contiguous United States by their
population. It demonstrates some of the range of styling options available in ``geoplot``.
"""


import geopandas as gpd
import geoplot as gplt
import geoplot.crs as gcrs
import matplotlib.pyplot as plt
import mapclassify as mc

continental_usa_cities = gpd.read_file(gplt.datasets.get_path('usa_cities'))
continental_usa_cities = continental_usa_cities.query('STATE not in ["AK", "HI", "PR"]')
contiguous_usa = gpd.read_file(gplt.datasets.get_path('contiguous_usa'))
scheme = mc.Quantiles(continental_usa_cities['POP_2010'], k=5)

ax = gplt.polyplot(
    contiguous_usa, 
    zorder=-1,
    linewidth=1,
    projection=gcrs.AlbersEqualArea(),
    edgecolor='white',
    facecolor='lightgray',
    figsize=(8, 12)
)
gplt.pointplot(
    continental_usa_cities, 
    scale='POP_2010',
    limits=(2, 30),
    hue='POP_2010',
    cmap='Blues',
github martinfleis / momepy / momepy / diversity.py View on Github external
except ImportError:
            raise ImportError("The 'mapclassify' package is required")

    def p(n, N):
        """ Relative abundance """
        if n == 0:
            return 0
        return float(n) / N

    if categorical:
        counts = data.value_counts().to_dict()
        for c in categories:
            if c not in counts.keys():
                counts[c] = 0
    else:
        sample_bins = mc.UserDefined(data, bins)
        counts = dict(zip(bins, sample_bins.counts))

    N = sum(counts.values())

    return sum(p(n, N) ** 2 for n in counts.values() if n != 0)
github martinfleis / momepy / momepy / diversity.py View on Github external
except ImportError:
            raise ImportError("The 'mapclassify' package is required")

    def p(n, N):
        """ Relative abundance """
        if n == 0:
            return 0
        return (float(n) / N) * ln(float(n) / N)

    if categorical:
        counts = data.value_counts().to_dict()
        for c in categories:
            if c not in counts.keys():
                counts[c] = 0
    else:
        sample_bins = mc.UserDefined(data, bins)
        counts = dict(zip(bins, sample_bins.counts))

    N = sum(counts.values())

    return -sum(p(n, N) for n in counts.values() if n != 0)
github martinfleis / momepy / momepy / diversity.py View on Github external
binning="HeadTailBreaks",
        gini_simpson=False,
        inverse=False,
        categorical=False,
        categories=None,
        verbose=True,
        **classification_kwds
    ):
        if not categorical:
            try:
                import mapclassify.classifiers as classifiers
            except ImportError:
                raise ImportError("The 'mapclassify' package is required")

            schemes = {}
            for classifier in classifiers.CLASSIFIERS:
                schemes[classifier.lower()] = getattr(classifiers, classifier)
            binning = binning.lower()
            if binning not in schemes:
                raise ValueError(
                    "Invalid binning. Binning must be in the"
                    " set: %r" % schemes.keys()
                )

        self.gdf = gdf
        self.sw = spatial_weights
        self.id = gdf[unique_id]
        self.binning = binning
        self.gini_simpson = gini_simpson
        self.inverse = inverse
        self.categorical = categorical
        self.categories = categories
github martinfleis / momepy / momepy / diversity.py View on Github external
spatial_weights,
        unique_id,
        binning="HeadTailBreaks",
        categorical=False,
        categories=None,
        verbose=True,
        **classification_kwds
    ):
        if not categorical:
            try:
                import mapclassify.classifiers as classifiers
            except ImportError:
                raise ImportError("The 'mapclassify' package is required")

            schemes = {}
            for classifier in classifiers.CLASSIFIERS:
                schemes[classifier.lower()] = getattr(classifiers, classifier)
            binning = binning.lower()
            if binning not in schemes:
                raise ValueError(
                    "Invalid binning. Binning must be in the"
                    " set: %r" % schemes.keys()
                )

        self.gdf = gdf
        self.sw = spatial_weights
        self.id = gdf[unique_id]
        self.binning = binning
        self.categorical = categorical
        self.categories = categories
        self.classification_kwds = classification_kwds
github martinfleis / momepy / momepy / diversity.py View on Github external
unique_id,
        binning="HeadTailBreaks",
        categorical=False,
        categories=None,
        verbose=True,
        **classification_kwds
    ):
        if not categorical:
            try:
                import mapclassify.classifiers as classifiers
            except ImportError:
                raise ImportError("The 'mapclassify' package is required")

            schemes = {}
            for classifier in classifiers.CLASSIFIERS:
                schemes[classifier.lower()] = getattr(classifiers, classifier)
            binning = binning.lower()
            if binning not in schemes:
                raise ValueError(
                    "Invalid binning. Binning must be in the"
                    " set: %r" % schemes.keys()
                )

        self.gdf = gdf
        self.sw = spatial_weights
        self.id = gdf[unique_id]
        self.binning = binning
        self.categorical = categorical
        self.categories = categories
        self.classification_kwds = classification_kwds

        data = gdf.copy()
github martinfleis / momepy / momepy / diversity.py View on Github external
gini_simpson=False,
        inverse=False,
        categorical=False,
        categories=None,
        verbose=True,
        **classification_kwds
    ):
        if not categorical:
            try:
                import mapclassify.classifiers as classifiers
            except ImportError:
                raise ImportError("The 'mapclassify' package is required")

            schemes = {}
            for classifier in classifiers.CLASSIFIERS:
                schemes[classifier.lower()] = getattr(classifiers, classifier)
            binning = binning.lower()
            if binning not in schemes:
                raise ValueError(
                    "Invalid binning. Binning must be in the"
                    " set: %r" % schemes.keys()
                )

        self.gdf = gdf
        self.sw = spatial_weights
        self.id = gdf[unique_id]
        self.binning = binning
        self.gini_simpson = gini_simpson
        self.inverse = inverse
        self.categorical = categorical
        self.categories = categories
        self.classification_kwds = classification_kwds

mapclassify

Classification Schemes for Choropleth Maps.

BSD-3-Clause
Latest version published 2 months ago

Package Health Score

79 / 100
Full package analysis

Similar packages