Skip to content
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
29 changes: 28 additions & 1 deletion branca/colormap.py
Original file line number Diff line number Diff line change
Expand Up @@ -77,6 +77,9 @@ def _base(x: float) -> float:
return 0


_LEGEND_POSITIONS = ("topright", "topleft", "bottomright", "bottomleft")


class ColorMap(MacroElement):
"""A generic class for creating colormaps.

Expand All @@ -92,6 +95,9 @@ class ColorMap(MacroElement):
The color for the text.
max_labels : int, default 10
Maximum number of legend tick labels
position : str, default "topright"
Corner of the map the legend is shown in: "topright", "topleft",
"bottomright" or "bottomleft".
"""

_template: Template = ENV.get_template("color_scale.js")
Expand All @@ -103,6 +109,7 @@ def __init__(
caption: str = "",
text_color: str = "black",
max_labels: int = 10,
position: str = "topright",
):
super().__init__()
self._name = "ColorMap"
Expand All @@ -114,6 +121,12 @@ def __init__(
self.index: List[float] = [vmin, vmax]
self.max_labels = max_labels
self.tick_labels: Optional[Sequence[Union[float, str]]] = None
if position not in _LEGEND_POSITIONS:
raise ValueError(
f"position must be one of {', '.join(_LEGEND_POSITIONS)}, "
f"got {position!r}.",
)
self.position = position

self.width = 450
self.height = 40
Expand Down Expand Up @@ -276,7 +289,10 @@ class LinearColormap(ColorMap):
max_labels : int, default 10
Maximum number of legend tick labels
tick_labels: list of floats, default None
If given, used as the positions of ticks."""
If given, used as the positions of ticks.
position : str, default "topright"
Corner of the map the legend is shown in: "topright", "topleft",
"bottomright" or "bottomleft"."""

def __init__(
self,
Expand All @@ -288,13 +304,15 @@ def __init__(
text_color: str = "black",
max_labels: int = 10,
tick_labels: Optional[Sequence[float]] = None,
position: str = "topright",
):
super().__init__(
vmin=vmin,
vmax=vmax,
caption=caption,
text_color=text_color,
max_labels=max_labels,
position=position,
)
self.tick_labels: Optional[Sequence[float]] = tick_labels

Expand Down Expand Up @@ -464,6 +482,7 @@ def to_step(
text_color=text_color,
max_labels=max_labels,
tick_labels=self.tick_labels,
position=self.position,
)

def scale(
Expand All @@ -486,6 +505,7 @@ def scale(
caption=self.caption,
text_color=self.text_color,
max_labels=max_labels,
position=self.position,
)


Expand Down Expand Up @@ -523,6 +543,9 @@ class StepColormap(ColorMap):
Maximum number of legend tick labels
tick_labels: list of floats, default None
If given, used as the positions of ticks.
position : str, default "topright"
Corner of the map the legend is shown in: "topright", "topleft",
"bottomright" or "bottomleft".
"""

def __init__(
Expand All @@ -535,13 +558,15 @@ def __init__(
text_color: str = "black",
max_labels: int = 10,
tick_labels: Optional[Sequence[float]] = None,
position: str = "topright",
):
super().__init__(
vmin=vmin,
vmax=vmax,
caption=caption,
text_color=text_color,
max_labels=max_labels,
position=position,
)
self.tick_labels = tick_labels

Expand Down Expand Up @@ -603,6 +628,7 @@ def to_linear(
caption=self.caption,
text_color=self.text_color,
max_labels=max_labels,
position=self.position,
)

def scale(
Expand All @@ -625,6 +651,7 @@ def scale(
caption=self.caption,
text_color=self.text_color,
max_labels=max_labels,
position=self.position,
)


Expand Down
2 changes: 1 addition & 1 deletion branca/templates/color_scale.js
Original file line number Diff line number Diff line change
Expand Up @@ -15,7 +15,7 @@
.domain([{{ this.color_domain[0] }}, {{ this.color_domain[-1] }}])
.range([0, {{ this.width }} - 50]);

{{this.get_name()}}.legend = L.control({position: 'topright'});
{{this.get_name()}}.legend = L.control({position: {{ this.position|tojson }}});
{{this.get_name()}}.legend.onAdd = function (map) {var div = L.DomUtil.create('div', 'legend'); return div};
{{this.get_name()}}.legend.addTo({{this._parent.get_name()}});

Expand Down
39 changes: 39 additions & 0 deletions tests/test_colormap.py
Original file line number Diff line number Diff line change
Expand Up @@ -6,6 +6,7 @@
import pytest

import branca.colormap as cm
from branca.element import Figure


def test_simple_step():
Expand Down Expand Up @@ -151,3 +152,41 @@ def test_max_labels_step(max_labels, expected):
except AssertionError: # rendering outside parent Figure raises error
pass
assert colorbar.tick_labels == expected


def _render_in_figure(colormap):
figure = Figure()
figure.add_child(colormap)
return figure.render()


@pytest.mark.parametrize("cls", [cm.LinearColormap, cm.StepColormap])
@pytest.mark.parametrize(
"position",
["topright", "topleft", "bottomright", "bottomleft"],
)
def test_legend_position(cls, position):
colormap = cls(["red", "blue"], position=position)
out = _render_in_figure(colormap)
assert f'L.control({{position: "{position}"}})' in out


@pytest.mark.parametrize("cls", [cm.LinearColormap, cm.StepColormap])
def test_legend_position_default(cls):
out = _render_in_figure(cls(["red", "blue"]))
assert 'L.control({position: "topright"})' in out


@pytest.mark.parametrize("position", ["top", "TopLeft", "", None])
def test_legend_position_invalid(position):
with pytest.raises(ValueError, match="position must be one of"):
cm.LinearColormap(["red", "blue"], position=position)


def test_legend_position_kept_by_derived_colormaps():
linear = cm.LinearColormap(["red", "blue"], position="bottomleft")
step = cm.StepColormap(["red", "blue"], position="topleft")
assert linear.to_step(3).position == "bottomleft"
assert linear.scale(0, 10).position == "bottomleft"
assert step.to_linear().position == "topleft"
assert step.scale(0, 10).position == "topleft"