Skip to content

MNT fix and refactor color handling in DecisionBoundaryDisplay - Part 1 - #33419

Merged
ogrisel merged 8 commits into
scikit-learn:mainfrom
AnneBeyer:dbp_fix-color-selection
Mar 3, 2026
Merged

ogrisel merged 8 commits into
scikit-learn:mainfrom
AnneBeyer:dbp_fix-color-selection

Conversation

@AnneBeyer

Copy link
Copy Markdown
Member

Reference Issues/PRs

Towards #33115
Specifically, this implements checkboxes 1, 2, part of 3, and 5 (see next section for details)

What does this implement/fix? Explain your changes.

This PR moves all parts related to color selection based on 'multiclass_colors' into a sepparate function (3,5), unifies and simplifies the color selection mechanism (2) and adds a check that enough distinct colors are available in the given colormap (1).

It also adds a non-regression test for the last point, which is the only functionality change.

See also the comments in the code for more details.

@ogrisel @lucyleeow @StefanieSenger @antoinebaker

AI usage disclosure

I used AI assistance for:

  • Code generation (e.g., when writing an implementation or fixing a bug)
  • Test/benchmark generation
  • Documentation (including examples)
  • Research and understanding

Any other comments?

Unrelated small change:
I converted the error messages in sklearn/utils/_optional_dependencies.py to f-strings.

({"multiclass_colors": "not_cmap"}, "it must be a valid Matplotlib colormap"),
({"multiclass_colors": ["red", "green"]}, "it must be of the same length"),
(
{"multiclass_colors": ["red", "green", "blue", "yellow"]},

Copy link
Copy Markdown
Member Author

Choose a reason for hiding this comment

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

Added edge case for too many values (could also be accepted and select the first n elements, but currently we check for exact length)

(None, 11),
("plasma", 3),
("Blues", 3),
("tab20", 20),

Copy link
Copy Markdown
Member Author

Choose a reason for hiding this comment

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

Edge case with just enough colors

cmap = mpl.pyplot.get_cmap(multiclass_colors, len(clf.classes_))
multiclass_colors = "gist_rainbow"

if multiclass_colors in ["tab10", "tab20"]:

Copy link
Copy Markdown
Member Author

Choose a reason for hiding this comment

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

I adapted the test to match the new simplified behaviour in the new _select_colors function

f"n_features must be equal to 2. Got {num_features} instead."
)

if (

Copy link
Copy Markdown
Member Author

Choose a reason for hiding this comment

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

This part is now integrated in _select_colors

<...>
>>> plt.show()
"""
check_matplotlib_support(f"{cls.__name__}.from_estimator")

Copy link
Copy Markdown
Member Author

Choose a reason for hiding this comment

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

This was only needed for validating multilcass_colors, which now happens in the new function

@ogrisel ogrisel left a comment

Copy link
Copy Markdown
Member

Choose a reason for hiding this comment

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

LGTM. I manually checked that the plot #32872 qualitatively looks the same as before.

@ogrisel

ogrisel commented Mar 3, 2026 •

Copy link
Copy Markdown
Member

Since this is mostly an internal refactoring with little user facing impacts, let's merge to unlock the subsequent items in the linked issue TODO list.

@ogrisel
ogrisel merged commit 2d59ab9 into scikit-learn:main Mar 3, 2026
32 checks passed
@github-project-automation github-project-automation Bot moved this from In progress to Done in Labs Mar 3, 2026

@lucyleeow lucyleeow left a comment

Copy link
Copy Markdown
Member

Choose a reason for hiding this comment

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

Sorry late again.

I think we can test the specific colors as suggested (https://github.com/scikit-learn/scikit-learn/pull/33300/changes#r2866814374)

In particular we should check that for qualitative colormaps we are picking the first n_classes colors and not sampling evenly (ref: https://github.com/scikit-learn/scikit-learn/pull/33015/changes#r2703134927)

Maybe we could add some of the test fixes before moving on?

- If `None`, defaults to `"tab10"` when `n_classes <= 10`, otherwise
`"gist_rainbow"`.
- If `str`, interpreted as a Matplotlib colormap name.
- If `list`, each entry must be a valid Matplotlib color-like value.

Copy link
Copy Markdown
Member

Choose a reason for hiding this comment

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

Could we add a reference to mpl is_color_like function, just to help anyone reading the code.

"different colormap or provide a list of colors via "
"'multiclass_colors'."
)
if cmap.N < 256:

Copy link
Copy Markdown
Member

Choose a reason for hiding this comment

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

I think this is a fine way to differentiate between qualitative and continuous colormaps and and I can't see where it would fail - but I think a 'safer' way may be with class.

I think qualitative maps are ListedColormap (note the colors attribute, which we do use later) - it's hard to find documentation but it is mentioned here: https://matplotlib.org/stable/gallery/color/individual_colors_from_cmap.html#extracting-colors-from-a-discrete-colormap

Continuous colormaps are LinearSegmentedColormap - note the default of N=256

WDYT?

Copy link
Copy Markdown
Member Author

Choose a reason for hiding this comment

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

I double checked this, but related to my comment above, not all continuous colormaps are of type LinearSegmentedColormap.
Inspecting the cmaps in matplotlib's colormap reference (see code below for reference) shows that there are also some ListedColormaps in {'Miscellaneous', 'Diverging', 'Cyclic', 'Qualitative', 'Perceptually Uniform Sequential'}, which will have the colors attribute, but also 256 colors, so sampling the first n_colors (which we do in this case) will result in almost indistinguishable colors (all purples in the case of viridis, for example). This is why I went for the approach above.

import matplotlib as mpl
import matplotlib.pyplot as plt

# list taken from https://matplotlib.org/stable/gallery/color/colormap_reference.html
cmaps = [('Perceptually Uniform Sequential', [
            'viridis', 'plasma', 'inferno', 'magma', 'cividis']),
         ('Sequential', [
            'Greys', 'Purples', 'Blues', 'Greens', 'Oranges', 'Reds',
            'YlOrBr', 'YlOrRd', 'OrRd', 'PuRd', 'RdPu', 'BuPu',
            'GnBu', 'PuBu', 'YlGnBu', 'PuBuGn', 'BuGn', 'YlGn']),
         ('Sequential (2)', [
            'binary', 'gist_yarg', 'gist_gray', 'gray', 'bone', 'pink',
            'spring', 'summer', 'autumn', 'winter', 'cool', 'Wistia',
            'hot', 'afmhot', 'gist_heat', 'copper']),
         ('Diverging', [
            'PiYG', 'PRGn', 'BrBG', 'PuOr', 'RdGy', 'RdBu',
            'RdYlBu', 'RdYlGn', 'Spectral', 'coolwarm', 'bwr', 'seismic',
            'berlin', 'managua', 'vanimo']),
         ('Cyclic', ['twilight', 'twilight_shifted', 'hsv']),
         ('Qualitative', [
            'Pastel1', 'Pastel2', 'Paired', 'Accent',
            'Dark2', 'Set1', 'Set2', 'Set3',
            'tab10', 'tab20', 'tab20b', 'tab20c']),
         ('Miscellaneous', [
            'flag', 'prism', 'ocean', 'gist_earth', 'terrain', 'gist_stern',
            'gnuplot', 'gnuplot2', 'CMRmap', 'cubehelix', 'brg',
            'gist_rainbow', 'rainbow', 'jet', 'turbo', 'nipy_spectral',
            'gist_ncar'])]

listed_cmaps=set()
for cmap_category, cmap_list in cmaps:
   for cmap in cmap_list:
      if type(plt.get_cmap(cmap)) == mpl.colors.ListedColormap:
         print(f"{cmap}({cmap_category})\ncolor counts:{plt.get_cmap(cmap).N}")
print(listed_cmaps)

Copy link
Copy Markdown
Member

Choose a reason for hiding this comment

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

Ah interesting, thanks for taking the time to explain.


if ax is None:
_, ax = plt.subplots()
_, ax = mpl.pyplot.subplots()

Copy link
Copy Markdown
Member

Choose a reason for hiding this comment

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

Locally this causes problems for me. It seems that importing matplotlib does not automatically import pyplot:

In [1]: import matplotlib as mpl

In [2]: _, ax = mpl.pyplot.subplots()
---------------------------------------------------------------------------
AttributeError                            Traceback (most recent call last)
Cell In[2], line 1
----> 1 _, ax = mpl.pyplot.subplots()

File ~/miniconda3/envs/sklearn-env/lib/python3.13/site-packages/matplotlib/_api/__init__.py:217, in caching_module_getattr.<locals>.__getattr__(name)
    215 if name in props:
    216     return props[name].__get__(instance)
--> 217 raise AttributeError(
    218     f"module {cls.__module__!r} has no attribute {name!r}")

AttributeError: module 'matplotlib' has no attribute 'pyplot'

The tests indeed all pass, but I wonder if that is because pyplot was already imported by the time decision boundary tests are run?

@AnneBeyer

Copy link
Copy Markdown
Member Author

Choose a reason for hiding this comment

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

I had the same problem after this was merged, and wanted to revert it in the next PR, but at some point I couldn't reproduce it anymore. Inspecting this again, I now realize that it was because I imported pyplot at another point in my notebook to call plt.close("all"), so I'll open a PR to revert this.

@AnneBeyer
AnneBeyer deleted the dbp_fix-color-selection branch April 15, 2026 19:09
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Projects

None yet

Development

Successfully merging this pull request may close these issues.

3 participants