Skip to content

Fix ZeroDivisionError when requesting a single color from palette helpers - #5922

Open
rashedrana wants to merge 2 commits into
plotly:mainfrom
rashedrana:fix-single-color-zero-division
Open

rashedrana wants to merge 2 commits into
plotly:mainfrom
rashedrana:fix-single-color-zero-division

Conversation

@rashedrana

Copy link
Copy Markdown

Link to issue

Fixes #5805

Description of change

sample_colorscale and n_colors raise ZeroDivisionError when asked for exactly one color, because both divide by the requested count minus one. This breaks palettes sized to a dataset's group count when there is exactly one group.

For a single requested color there is no interval to step through: n_colors now uses a zero increment so it returns the low color, and sample_colorscale takes its single sample at the low end of the interval. Results for zero and for two or more colors are unchanged.

Prepared with AI assistance and verified locally by me.

Demo

Not applicable. This change fixes color utility functions and does not introduce visual changes to Plotly charts.

Testing strategy

Added regression tests test_sample_colorscale_single_color and test_n_colors_single_color to tests/test_core/test_colors/test_colors.py. Both fail on the original code with ZeroDivisionError and pass with the fix. Full file: 11 passed.

Additional information (optional)

Repro from the issue, on current main:

  • sample_colorscale("Viridis", 1) raises ZeroDivisionError; with the fix it returns ['rgb(68, 1, 84)']
  • n_colors((0, 0, 0), (1, 1, 1), 1) raises ZeroDivisionError; with the fix it returns [(0.0, 0.0, 0.0)]

Guidelines

@atishay-kasliwal atishay-kasliwal left a comment

Copy link
Copy Markdown

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

n_colors(..., 1) now returns the low colour and sample_colorscale('Viridis', 1) returns rgb(68, 1, 84) (with low=0.5, the 0.5 colour; with colortype='tuple', a tuple); master raised ZeroDivisionError for each. 0 and 3 samples are unchanged. For whoever triages: #5882, opened 2026-11-15 for the same issue, makes the same two changes.

This branch has not been deployed

No deployments
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

None yet

Projects

None yet

Development

Successfully merging this pull request may close these issues.

[BUG]: Single-color requests raise ZeroDivisionError in palette helpers

2 participants