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 _plotly_utils/colors/__init__.py
Original file line number Diff line number Diff line change
Expand Up @@ -694,12 +694,14 @@ def n_colors(lowcolor, highcolor, n_colors, colortype="tuple"):
lowcolor = unlabel_rgb(lowcolor)
highcolor = unlabel_rgb(highcolor)

# A single requested color is the low color: there is no interval to
# step through, and dividing by (n_colors - 1) would divide by zero.
diff_0 = float(highcolor[0] - lowcolor[0])
incr_0 = diff_0 / (n_colors - 1)
incr_0 = diff_0 / (n_colors - 1) if n_colors > 1 else 0.0
diff_1 = float(highcolor[1] - lowcolor[1])
incr_1 = diff_1 / (n_colors - 1)
incr_1 = diff_1 / (n_colors - 1) if n_colors > 1 else 0.0
diff_2 = float(highcolor[2] - lowcolor[2])
incr_2 = diff_2 / (n_colors - 1)
incr_2 = diff_2 / (n_colors - 1) if n_colors > 1 else 0.0
list_of_colors = []

def _constrain_color(c):
Expand Down Expand Up @@ -906,9 +908,15 @@ def sample_colorscale(colorscale, samplepoints, low=0.0, high=1.0, colortype="rg
colors = validate_colors(colors, colortype="tuple")

if isinstance(samplepoints, int):
samplepoints = [
low + idx / (samplepoints - 1) * (high - low) for idx in range(samplepoints)
]
if samplepoints == 1:
# A single sample is taken at the low end of the interval;
# dividing by (samplepoints - 1) would divide by zero.
samplepoints = [low]
else:
samplepoints = [
low + idx / (samplepoints - 1) * (high - low)
for idx in range(samplepoints)
]
elif isinstance(samplepoints, float):
samplepoints = [samplepoints]

Expand Down
14 changes: 14 additions & 0 deletions tests/test_core/test_colors/test_colors.py
Original file line number Diff line number Diff line change
Expand Up @@ -224,6 +224,13 @@ def test_sample_colorscale(self):
colors.sequential.turbid_r,
)

def test_sample_colorscale_single_color(self):
# requesting a single color returns the first color of the scale
# (this used to raise a ZeroDivisionError)
self.assertEqual(
colors.sample_colorscale("Viridis", 1), ["rgb(68, 1, 84)"]
)

def test_n_colors(self):
# test that n_colors constrains values to between 0 and 255
generated_colorscale = colors.n_colors(
Expand All @@ -250,3 +257,10 @@ def test_n_colors(self):
]

self.assertEqual(generated_colorscale, expected_colorscale)

def test_n_colors_single_color(self):
# requesting a single color returns the low color
# (this used to raise a ZeroDivisionError)
self.assertEqual(
colors.n_colors((0, 0, 0), (1, 1, 1), 1), [(0.0, 0.0, 0.0)]
)