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

Allow classifier to label ranges #269

Open
wants to merge 5 commits into
base: master
Choose a base branch
from
Open
Show file tree
Hide file tree
Changes from 2 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
24 changes: 23 additions & 1 deletion ecoscope/analysis/classifier.py
Original file line number Diff line number Diff line change
@@ -1,4 +1,5 @@
import pandas as pd
import numpy as np
import matplotlib as mpl
from ecoscope.base.utils import hex_to_rgba

Expand All @@ -25,7 +26,16 @@

# pass in a dataframe and output a series
def apply_classification(
dataframe, input_column_name, output_column_name=None, labels=None, scheme="natural_breaks", **kwargs
dataframe,
input_column_name,
output_column_name=None,
labels=None,
scheme="natural_breaks",
label_prefix="",
label_suffix="",
label_ranges=False,
label_decimals=1,
**kwargs,
):
"""
Classifies the data in a GeoDataFrame column using specified classification scheme.
atmorling marked this conversation as resolved.
Show resolved Hide resolved
Expand Down Expand Up @@ -75,7 +85,19 @@ def apply_classification(
classifier = classifier_class(dataframe[input_column_name].to_numpy(), **kwargs)
if labels is None:
labels = classifier.bins

# Generate range labels if our bins are numeric
if np.issubdtype(dataframe[input_column_name].dtype, np.number) and label_ranges:
# We could do this using mapclassify.get_legend_classes, but this generates a cleaner labely
atmorling marked this conversation as resolved.
Show resolved Hide resolved
ranges = [f"0 - {labels[0]:.{label_decimals}f}"]
atmorling marked this conversation as resolved.
Show resolved Hide resolved
ranges.extend(
[f"{labels[i]:.{label_decimals}f} - {labels[i + 1]:.{label_decimals}f}" for i in range(len(labels) - 1)]
)
labels = ranges

assert len(labels) == len(classifier.bins)
if label_prefix or label_suffix:
labels = [f"{label_prefix}{label}{label_suffix}" for label in labels]
dataframe[output_column_name] = [labels[i] for i in classifier.yb]
return dataframe

Expand Down
18 changes: 18 additions & 0 deletions tests/test_classifier.py
Original file line number Diff line number Diff line change
Expand Up @@ -37,6 +37,19 @@ def test_classify_with_labels(sample_df):
assert result["value_classified"].values.tolist() == ["1", "1", "1", "2", "2"]


def test_classify_with_labels_prefix_suffix(sample_df):
result = apply_classification(
sample_df,
input_column_name="value",
labels=["1", "2"],
label_prefix="_",
label_suffix="_",
scheme="equal_interval",
k=2,
)
assert result["value_classified"].values.tolist() == ["_1_", "_1_", "_1_", "_2_", "_2_"]


def test_classify_with_invalid_labels(sample_df):
with pytest.raises(AssertionError):
apply_classification(sample_df, input_column_name="value", labels=[0], scheme="std_mean")
Expand Down Expand Up @@ -92,3 +105,8 @@ def test_apply_colormap_cmap_user_defined_bad(movebank_relocations):

with pytest.raises(AssertionError):
apply_color_map(classified, "speed_bins", cmap)


def test_classify_with_ranges(sample_df):
result = apply_classification(sample_df, input_column_name="value", scheme="equal_interval", label_ranges=True, k=5)
assert result["value_classified"].values.tolist() == ["0 - 1.8", "1.8 - 2.6", "2.6 - 3.4", "3.4 - 4.2", "4.2 - 5.0"]
9 changes: 8 additions & 1 deletion tests/test_ecomap.py
Original file line number Diff line number Diff line change
Expand Up @@ -279,13 +279,20 @@ def test_add_polyline_with_color(movebank_relocations):
trajectory = ecoscope.base.Trajectory.from_relocations(movebank_relocations)
# this is effectively a reimplementation of SpeedDataFrame
apply_classification(
trajectory, input_column_name="speed_kmhr", output_column_name="speed_bins", scheme="equal_interval", k=6
trajectory,
input_column_name="speed_kmhr",
output_column_name="speed_bins",
scheme="equal_interval",
label_suffix=" km/h",
label_ranges=True,
k=6,
)
cmap = ["#1a9850", "#91cf60", "#d9ef8b", "#fee08b", "#fc8d59", "#d73027"]
apply_color_map(trajectory, "speed_bins", cmap=cmap, output_column_name="speed_colors")

m = EcoMap()
m.add_layer(m.polyline_layer(trajectory, color_column="speed_colors", get_width=2000))
m.add_legend(labels=trajectory["speed_bins"], colors=trajectory["speed_colors"])

assert len(m.layers) == 2
assert isinstance(m.layers[1], PathLayer)
Expand Down
Loading