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
20 changes: 14 additions & 6 deletions branca/colormap.py
Original file line number Diff line number Diff line change
Expand Up @@ -445,12 +445,20 @@ def to_step(
if round_method == "log10":
index = [_base(x) for x in index]

colors = [
scaled_cm.rgba_floats_tuple(
index[i] * (1.0 - i / (n - 1.0)) + index[i + 1] * i / (n - 1.0),
)
for i in range(n)
]
if n == 1:
# Steps are normally sampled at points spread evenly across the
# colormap, the first at `index[0]` and the last at `index[-1]`.
# A single step is the degenerate case of that spread (0 / 0), so
# sample the middle instead: the one bin covers the whole range
# and gets a color to match.
colors = [scaled_cm.rgba_floats_tuple((index[0] + index[1]) / 2.0)]
else:
colors = [
scaled_cm.rgba_floats_tuple(
index[i] * (1.0 - i / (n - 1.0)) + index[i + 1] * i / (n - 1.0),
)
for i in range(n)
]

caption = self.caption
text_color = self.text_color
Expand Down
19 changes: 19 additions & 0 deletions tests/test_colormap.py
Original file line number Diff line number Diff line change
Expand Up @@ -89,6 +89,25 @@ def test_linear_to_step():
lc.to_step(data=some_list, quantiles=[0, 0.3, 0.7, 1], round_method="log10")


@pytest.mark.parametrize(
"kwargs",
[
{"n": 1},
{"index": [0, 1]},
{"data": [0, 0.5, 1], "n": 1},
{"data": [0.5, 0.75, 1], "n": 1, "method": "log"},
{"data": [0, 0.5, 1], "quantiles": [0, 1]},
],
)
def test_linear_to_step_single_step(kwargs):
"""A one-bin colormap is valid; every path here raised ZeroDivisionError."""
linear = cm.LinearColormap(["red", "blue"], vmin=0, vmax=1)
step = linear.to_step(**kwargs)
assert len(step.colors) == 1
# The single bin spans the whole range, so it takes the middle color.
assert step.colors[0] == linear.rgba_floats_tuple(0.5)


def test_step_to_linear():
step = cm.StepColormap(
["green", "yellow", "red"],
Expand Down