Skip to content

Commit 84e5ae6

Browse files
Fix single-color palette sampling
1 parent 3c1aeba commit 84e5ae6

2 files changed

Lines changed: 22 additions & 3 deletions

File tree

‎_plotly_utils/colors/__init__.py‎

Lines changed: 10 additions & 3 deletions
Original file line numberDiff line numberDiff line change
@@ -694,6 +694,9 @@ def n_colors(lowcolor, highcolor, n_colors, colortype="tuple"):
694694
lowcolor = unlabel_rgb(lowcolor)
695695
highcolor = unlabel_rgb(highcolor)
696696

697+
if n_colors == 1:
698+
return [lowcolor]
699+
697700
diff_0 = float(highcolor[0] - lowcolor[0])
698701
incr_0 = diff_0 / (n_colors - 1)
699702
diff_1 = float(highcolor[1] - lowcolor[1])
@@ -906,9 +909,13 @@ def sample_colorscale(colorscale, samplepoints, low=0.0, high=1.0, colortype="rg
906909
colors = validate_colors(colors, colortype="tuple")
907910

908911
if isinstance(samplepoints, int):
909-
samplepoints = [
910-
low + idx / (samplepoints - 1) * (high - low) for idx in range(samplepoints)
911-
]
912+
if samplepoints == 1:
913+
samplepoints = [low]
914+
else:
915+
samplepoints = [
916+
low + idx / (samplepoints - 1) * (high - low)
917+
for idx in range(samplepoints)
918+
]
912919
elif isinstance(samplepoints, float):
913920
samplepoints = [samplepoints]
914921

‎tests/test_core/test_colors/test_colors.py‎

Lines changed: 12 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -250,3 +250,15 @@ def test_n_colors(self):
250250
]
251251

252252
self.assertEqual(generated_colorscale, expected_colorscale)
253+
254+
def test_sample_colorscale_single_color(self):
255+
result = colors.sample_colorscale("Viridis", 1)
256+
assert len(result) == 1
257+
assert result[0] == "rgb(68, 1, 84)"
258+
259+
260+
def test_n_colors_single_color(self):
261+
result = colors.n_colors(
262+
(0, 0, 0), (255, 255, 255), 1
263+
)
264+
assert result == [(0, 0, 0)]

0 commit comments

Comments
 (0)