diff --git a/_plotly_utils/colors/__init__.py b/_plotly_utils/colors/__init__.py index e3a304c9bb..4567e480d3 100644 --- a/_plotly_utils/colors/__init__.py +++ b/_plotly_utils/colors/__init__.py @@ -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): @@ -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] diff --git a/tests/test_core/test_colors/test_colors.py b/tests/test_core/test_colors/test_colors.py index f40e1e31d8..cc5cb9f2c9 100644 --- a/tests/test_core/test_colors/test_colors.py +++ b/tests/test_core/test_colors/test_colors.py @@ -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( @@ -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)] + )