Skip to content

Commit

Permalink
Legend Update (#268)
Browse files Browse the repository at this point in the history
  • Loading branch information
atmorling authored Sep 10, 2024
1 parent e7eb7d5 commit e0f77e7
Show file tree
Hide file tree
Showing 7 changed files with 47 additions and 17 deletions.
2 changes: 2 additions & 0 deletions ecoscope/base/__init__.py
Original file line number Diff line number Diff line change
Expand Up @@ -11,6 +11,7 @@
create_meshgrid,
groupby_intervals,
hex_to_rgba,
color_tuple_to_css,
)

__all__ = [
Expand All @@ -26,4 +27,5 @@
"create_meshgrid",
"groupby_intervals",
"hex_to_rgba",
"color_tuple_to_css",
]
6 changes: 6 additions & 0 deletions ecoscope/base/utils.py
Original file line number Diff line number Diff line change
Expand Up @@ -2,6 +2,7 @@
import numpy as np
import pandas as pd
from shapely.geometry import box
from typing import Tuple


def create_meshgrid(
Expand Down Expand Up @@ -280,3 +281,8 @@ def hex_to_rgba(input: str) -> tuple:
return tuple(int(hex[i : i + 2], 16) for i in (0, 2, 4, 6))
except ValueError:
raise ValueError(f"Invalid hex string, {input}")


def color_tuple_to_css(color: Tuple[int, int, int, int]):
# eg [255,0,120,255] converts to 'rgba(255,0,120,1)'
return f"rgba({color[0]}, {color[1]}, {color[2]}, {color[3]/255})"
21 changes: 15 additions & 6 deletions ecoscope/mapping/map.py
Original file line number Diff line number Diff line change
Expand Up @@ -7,6 +7,7 @@
import numpy as np
import pandas as pd
import rasterio as rio
from ecoscope.base.utils import color_tuple_to_css
from io import BytesIO
from typing import Dict, IO, List, Optional, TextIO, Union
from pathlib import Path
Expand Down Expand Up @@ -236,7 +237,7 @@ def point_layer(
gdf = EcoMap._clean_gdf(gdf)
return ScatterplotLayer.from_geopandas(gdf, **kwargs)

def add_legend(self, **kwargs):
def add_legend(self, labels: list | pd.Series, colors: list | pd.Series, **kwargs):
"""
Adds a legend to the map
Parameters
Expand All @@ -246,14 +247,22 @@ def add_legend(self, **kwargs):
Where to place the widget within the map
title: str
A title displayed on the widget
labels: list[str]
A list of labels
colors: list[str]
A list of colors as hex values
labels: list or pd.Series
A list or series of labels
colors: list or pd.Series
A list or series of colors as string hex values or RGBA color tuples
style: dict
Additional style params
"""
self.add_widget(LegendWidget(**kwargs))
if isinstance(labels, pd.Series):
labels = labels.unique().tolist()
if isinstance(colors, pd.Series):
colors = colors.unique().tolist()

labels = [str(label) for label in labels]
colors = [color_tuple_to_css(color) if isinstance(color, tuple) else color for color in colors]

self.add_widget(LegendWidget(labels=labels, colors=colors, **kwargs))

def add_north_arrow(self, **kwargs):
"""
Expand Down
13 changes: 4 additions & 9 deletions ecoscope/plotting/plot.py
Original file line number Diff line number Diff line change
@@ -1,9 +1,9 @@
from typing import Tuple

import numpy as np
import pandas as pd
import shapely

from ecoscope.base.utils import color_tuple_to_css

try:
from sklearn.neighbors import KernelDensity
import plotly.graph_objs as go
Expand All @@ -26,7 +26,7 @@ def __init__(self, grouped, x_col="x", y_col="y", color_col=None, groupby_style=

if color_col:
for group, data in grouped:
color = color_list_to_css(data[color_col].unique()[0])
color = color_tuple_to_css(data[color_col].unique()[0])

# The least significant 'group' are our categories
if not self.groupby_style.get(group[-1]):
Expand Down Expand Up @@ -381,13 +381,8 @@ def pie_chart(
values = data[value_column].value_counts(sort=False)

if color_column:
style_kwargs["marker_colors"] = [color_list_to_css(color) for color in data[color_column].unique()]
style_kwargs["marker_colors"] = [color_tuple_to_css(color) for color in data[color_column].unique()]
# breakpoint()

fig = go.Figure(data=go.Pie(labels=labels, values=values, **style_kwargs), layout=layout_kwargs)
return fig


def color_list_to_css(color: Tuple[int, int, int, int]):
# eg [255,0,120,255] converts to 'rgba(255,0,120,1)'
return f"rgba({color[0]}, {color[1]}, {color[2]}, {color[3]/255})"
2 changes: 1 addition & 1 deletion environment.yml
Original file line number Diff line number Diff line change
Expand Up @@ -16,7 +16,7 @@ dependencies:
- coverage[toml]
- earthranger-client @ git+https://github.com/PADAS/[email protected]
- ecoscope
- lonboard @ git+https://github.com/wildlife-dynamics/[email protected].2
- lonboard @ git+https://github.com/wildlife-dynamics/[email protected].3
- nbsphinx
- sphinx-autoapi
- dask[dataframe]
Expand Down
2 changes: 1 addition & 1 deletion pyproject.toml
Original file line number Diff line number Diff line change
Expand Up @@ -56,7 +56,7 @@ async_earthranger = [
"earthranger-client @ git+https://github.com/PADAS/[email protected]",
]
mapping = [
"lonboard @ git+https://github.com/wildlife-dynamics/[email protected].2",
"lonboard @ git+https://github.com/wildlife-dynamics/[email protected].3",
"matplotlib",
"mapclassify",
]
Expand Down
18 changes: 18 additions & 0 deletions tests/test_ecomap.py
Original file line number Diff line number Diff line change
Expand Up @@ -67,6 +67,24 @@ def test_add_legend():
assert len(m.deck_widgets) == 1


def test_add_legend_tuples():
m = EcoMap(default_widgets=False)
m.add_legend(labels=["Black", "White"], colors=[(0, 0, 0, 255), (255, 255, 255, 255)])
assert len(m.deck_widgets) == 1


def test_add_legend_mixed():
m = EcoMap(default_widgets=False)
m.add_legend(labels=["Black", "White"], colors=[(0, 0, 0, 255), "#FFFFFF"])
assert len(m.deck_widgets) == 1


def test_add_legend_series():
m = EcoMap(default_widgets=False)
m.add_legend(labels=pd.Series(["Black", "White"]), colors=pd.Series([(0, 0, 0, 255), (255, 255, 255, 255)]))
assert len(m.deck_widgets) == 1


def test_add_north_arrow():
m = EcoMap()
m.add_north_arrow()
Expand Down

0 comments on commit e0f77e7

Please sign in to comment.