Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

legendgram method #234

Open
wants to merge 2 commits into
base: main
Choose a base branch
from
Open
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
2 changes: 1 addition & 1 deletion mapclassify/__init__.py
Original file line number Diff line number Diff line change
@@ -1,7 +1,7 @@
import contextlib
from importlib.metadata import PackageNotFoundError, version

from . import util
from . import legendgram, util
from ._classify_API import classify
from .classifiers import (
CLASSIFIERS,
Expand Down
33 changes: 33 additions & 0 deletions mapclassify/classifiers.py
Original file line number Diff line number Diff line change
Expand Up @@ -9,6 +9,8 @@
import numpy as np
import scipy.stats as stats
from sklearn.cluster import KMeans
from .legendgram import _legendgram


__author__ = "Sergio J. Rey"

Expand Down Expand Up @@ -1183,6 +1185,37 @@
ax.spines["top"].set_visible(False)
return ax

def plot_legendgram(
self,
ax=None,
cmap="viridis",
bins=50,
inset=True,
clip=None,
vlines=False,
vlinecolor="black",
vlinewidth=1,
loc="lower left",
legend_size=(0.27, 0.2),
frameon=False,
tick_params=None,
):
l = _legendgram(

Check warning on line 1203 in mapclassify/classifiers.py

View check run for this annotation

Codecov / codecov/patch

mapclassify/classifiers.py#L1203

Added line #L1203 was not covered by tests
self,
ax,
cmap,
bins,
inset,
clip,
vlines,
vlinecolor,
vlinewidth,
loc,
legend_size,
frameon,
tick_params,
)


class HeadTailBreaks(MapClassifier):
"""
Expand Down
156 changes: 156 additions & 0 deletions mapclassify/legendgram.py
Original file line number Diff line number Diff line change
@@ -0,0 +1,156 @@
import numpy as np


def _legendgram(
classifier,
ax=None,
cmap="viridis",
bins=50,
inset=True,
clip=None,
vlines=False,
vlinecolor='black',
vlinewidth=1,
loc="lower left",
legend_size=(0.27, 0.2),
frameon=False,
tick_params=None,
):
"""
Add a histogram in a choropleth with colors aligned with map
...

Arguments
---------
f : Figure
ax : AxesSubplot
y : ndarray/Series
Values to map
breaks : list
Sequence with breaks for each class (i.e. boundary values
for colors)
pal : palettable colormap or matplotlib colormap
clip : tuple
[Optional. Default=None] If a tuple, clips the X
axis of the histogram to the bounds provided.
loc : string or int
valid legend location like that used in matplotlib.pyplot.legend
legend_size : tuple
tuple of floats between 0 and 1 describing the (width,height)
of the legend relative to the original frame.
frameon : bool (default: False)
whether to add a frame to the legendgram
tick_params : keyword dictionary
options to control how the histogram axis gets ticked/labelled.

Returns
-------
axis containing the legendgram.
"""

try:
import matplotlib.pyplot as plt
from matplotlib import colormaps

Check warning on line 53 in mapclassify/legendgram.py

View check run for this annotation

Codecov / codecov/patch

mapclassify/legendgram.py#L51-L53

Added lines #L51 - L53 were not covered by tests
except ImportError as e:
raise ImportError from e("you must have matplotlib ")
if ax is None:
f, ax = plt.subplots()

Check warning on line 57 in mapclassify/legendgram.py

View check run for this annotation

Codecov / codecov/patch

mapclassify/legendgram.py#L56-L57

Added lines #L56 - L57 were not covered by tests
else:
f = ax.get_figure()
k = len(classifier.bins)
breaks = classifier.bins
if inset:
histpos = _make_location(ax, loc, legend_size=legend_size)
histax = f.add_axes(histpos)

Check warning on line 64 in mapclassify/legendgram.py

View check run for this annotation

Codecov / codecov/patch

mapclassify/legendgram.py#L59-L64

Added lines #L59 - L64 were not covered by tests
else:
histax = ax
N, bins, patches = histax.hist(classifier.y, bins=bins, color="0.1")
pl = colormaps[cmap]

Check warning on line 68 in mapclassify/legendgram.py

View check run for this annotation

Codecov / codecov/patch

mapclassify/legendgram.py#L66-L68

Added lines #L66 - L68 were not covered by tests

bucket_breaks = [0] + [np.searchsorted(bins, i) for i in breaks]
for c in range(k):
for b in range(bucket_breaks[c], bucket_breaks[c + 1]):
patches[b].set_facecolor(pl(c / k))
if clip is not None:
histax.set_xlim(*clip)
histax.set_frame_on(frameon)
histax.get_yaxis().set_visible(False)
if tick_params is None:
tick_params = dict()
if vlines:
lim = ax.get_ylim()[1]

Check warning on line 81 in mapclassify/legendgram.py

View check run for this annotation

Codecov / codecov/patch

mapclassify/legendgram.py#L70-L81

Added lines #L70 - L81 were not covered by tests
# plot upper limit of each bin
for i in classifier.bins:
histax.vlines(i, 0, lim, color=vlinecolor, linewidth=vlinewidth)
tick_params["labelsize"] = tick_params.get("labelsize", 12)
histax.tick_params(**tick_params)
return histax

Check warning on line 87 in mapclassify/legendgram.py

View check run for this annotation

Codecov / codecov/patch

mapclassify/legendgram.py#L83-L87

Added lines #L83 - L87 were not covered by tests


def _make_location(ax, loc, legend_size=(0.27, 0.2)):
"""
Construct the location bounds of a legendgram

Arguments:
----------
ax : matplotlib.AxesSubplot
axis on which to add a legendgram
loc : string or int
valid legend location like that used in matplotlib.pyplot.legend
legend_size : tuple or float
tuple denoting the length/width of the legendgram in terms
of a fraction of the axis. If a float, the legend is assumed
square.

Returns
-------
a list [left_anchor, bottom_anchor, width, height] in terms of plot units
that defines the location and extent of the legendgram.


"""
position = ax.get_position()
if isinstance(legend_size, float):
legend_size = (legend_size, legend_size)
lw, lh = legend_size
legend_width = position.width * lw
legend_height = position.height * lh
right_offset = position.width - legend_width
top_offset = position.height - legend_height
if isinstance(loc, int):
try:
loc = inv_lut[loc]
except KeyError:
raise KeyError(

Check warning on line 124 in mapclassify/legendgram.py

View check run for this annotation

Codecov / codecov/patch

mapclassify/legendgram.py#L112-L124

Added lines #L112 - L124 were not covered by tests
"Legend location {} not recognized. Please choose "
" from the list of valid matplotlib legend locations."
"".format(loc)
)
if loc.lower() == "lower left" or loc.lower() == "best":
anchor_x, anchor_y = position.x0, position.y0
elif loc.lower() == "lower center":
anchor_x, anchor_y = position.x0 + position.width * 0.5, position.y0
elif loc.lower() == "lower right":
anchor_x, anchor_y = position.x0 + right_offset, position.y0
elif loc.lower() == "center left":
anchor_x, anchor_y = position.x0, position.y0 + position.height * 0.5
elif loc.lower() == "center":
anchor_x, anchor_y = (

Check warning on line 138 in mapclassify/legendgram.py

View check run for this annotation

Codecov / codecov/patch

mapclassify/legendgram.py#L129-L138

Added lines #L129 - L138 were not covered by tests
position.x0 + position.width * 0.5,
position.y0 + position.height * 0.5,
)
elif loc.lower() == "center right" or loc.lower() == "right":
anchor_x, anchor_y = (

Check warning on line 143 in mapclassify/legendgram.py

View check run for this annotation

Codecov / codecov/patch

mapclassify/legendgram.py#L142-L143

Added lines #L142 - L143 were not covered by tests
position.x0 + right_offset,
position.y0 + position.height * 0.5,
)
elif loc.lower() == "upper left":
anchor_x, anchor_y = position.x0, position.y0 + top_offset
elif loc.lower() == "upper center":
anchor_x, anchor_y = (

Check warning on line 150 in mapclassify/legendgram.py

View check run for this annotation

Codecov / codecov/patch

mapclassify/legendgram.py#L147-L150

Added lines #L147 - L150 were not covered by tests
position.x0 + position.width * 0.5,
position.y0 + top_offset,
)
elif loc.lower() == "upper right":
anchor_x, anchor_y = position.x0 + right_offset, position.y0 + top_offset
return [anchor_x, anchor_y, legend_width, legend_height]

Check warning on line 156 in mapclassify/legendgram.py

View check run for this annotation

Codecov / codecov/patch

mapclassify/legendgram.py#L154-L156

Added lines #L154 - L156 were not covered by tests
18 changes: 18 additions & 0 deletions mapclassify/util.py
Original file line number Diff line number Diff line change
Expand Up @@ -83,3 +83,21 @@ def get_color_array(
colors = v.apply(lambda x: to_hex(x / 255.0))
return colors.values
return np.stack(v.values)


loc_lut = {
"best": 0,
"upper right": 1,
"upper left": 2,
"lower left": 3,
"lower right": 4,
"right": 5,
"center left": 6,
"center right": 7,
"lower center": 8,
"upper center": 9,
"center": 10,
}
inv_lut = {v: k for k, v in loc_lut.items()} # yes, it's not general, but it's ok.


110 changes: 110 additions & 0 deletions notebooks/legendgram.ipynb

Large diffs are not rendered by default.

Loading