Skip to content

Fix sample_colorscale crash for colorscales that use CSS named colors - #5931

Open
rashedrana wants to merge 2 commits into
plotly:mainfrom
rashedrana:fix-colorscale-named-colors
Open

rashedrana wants to merge 2 commits into
plotly:mainfrom
rashedrana:fix-colorscale-named-colors

Conversation

@rashedrana

Copy link
Copy Markdown

Fixes #5930

Problem: plotly.colors.sample_colorscale raises TypeError: unsupported operand type(s) for -: 'str' and 'str' when a colorscale uses CSS named colors (for example "red" or "blue"), in both the list of [scale, color] pairs form and the list of colors form. Named colors are valid plotly colors: validate_colorscale accepts such a colorscale and so do graph objects.

Repro:

from plotly import colors

colors.sample_colorscale([[0, "red"], [1, "blue"]], [0, 0.5, 1])

Fix: in _plotly_utils/colors/__init__.py, validate_colors now converts CSS named colors to color tuples, like it already does for rgb and hex strings, so they are interpolated as tuples instead of reaching find_intermediate_color as strings. The name to RGB mapping (_NAMED_COLORS) covers the CSS Color 4 named colors, the same set of names accepted by ColorValidator. The lookup is case-insensitive, and named colors can be mixed with hex, rgb, rgba and tuple colors in one colorscale.

Test result: the repro now returns ['rgb(255, 0, 0)', 'rgb(128, 0, 128)', 'rgb(0, 0, 255)'] for both colorscale forms, matching the hex equivalent. A regression test, test_sample_colorscale_named_colors, was added to tests/test_core/test_colors/test_colors.py; it fails with the TypeError above without the fix and passes with it. The full test module passes (10 tests).

Prepared with AI assistance and verified locally by me.

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.

sample_colorscale raises TypeError when the colorscale uses CSS named colors

1 participant