Secure your code as it's written. Use Snyk Code to scan source code in minutes - no build needed - and fix issues immediately.
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")
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)
# 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)
)
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',
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)
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)
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
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
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()
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