Skip to content

ENH add xlim/ylim parameters to DecisionBoundaryDisplay - #33211

Draft
AnneBeyer wants to merge 15 commits into
scikit-learn:mainfrom
AnneBeyer:enh_add_xlim_ylim
Draft

AnneBeyer wants to merge 15 commits into
scikit-learn:mainfrom
AnneBeyer:enh_add_xlim_ylim

Conversation

@AnneBeyer

@AnneBeyer AnneBeyer commented Feb 5, 2026 •

Copy link
Copy Markdown
Member

Reference Issues/PRs

Towards #27462 (supersedes #31693 )

What does this implement/fix? Explain your changes.

Add xlim and ylim parameters to from_estimator and plot methods to allow setting the boundaries for the plot. Also added corresponding tests.

See the discussion in #31693 for the reason of extending the grid first (instead of simply overwriting the boundaries).

@lucyleeow @ogrisel @StefanieSenger

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?

@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.

Thanks! Small nits only.

Is it possible to add a test for when xlim and ylim 'shrink' the grid, we infer n_classes thus checking that the colors remain consistent?

@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.

I tried the branch with the following:

Details
from sklearn.inspection import DecisionBoundaryDisplay
from sklearn.naive_bayes import GaussianNB
import numpy as np
import matplotlib.pyplot as plt


X = np.concatenate(
    [
        np.random.multivariate_normal(mean=[-3, 3], cov=np.diag([2, 2]), size=100),
        np.random.multivariate_normal(mean=[-3, -3], cov=np.diag([1.5, 0.5]), size=100),
        np.random.multivariate_normal(mean=[3, 0], cov=np.diag([0.5, 1.5]), size=100),
    ]
)
y = np.concatenate([np.zeros(100), np.ones(100), np.ones(100) * 2])

estimator = GaussianNB(var_smoothing=1e-2).fit(X, y)
cmap = "gist_rainbow"

fig, axs = plt.subplots(2, 2, figsize=(10, 10))


for ax, (xlim, ylim) in zip(
    axs.flatten(),
    [
        (None, None),
        ((-15, 15), (-15, 15)),
        ((-4, -1), (1, 4)),
        ((-1, 2), (-5, -2)),
    ],
):
    disp = DecisionBoundaryDisplay.from_estimator(
        estimator,
        X,
        response_method="predict_proba",
        plot_method="pcolormesh",
        multiclass_colors=cmap,
        alpha=0.8,
        xlim=xlim,
        ylim=ylim,
        ax=ax,
    )
    _ = disp.ax_.scatter(X[:, 0], X[:, 1], c=y, edgecolor="k", cmap=cmap)
    ax.set_title(f"xlim={xlim}, ylim={ylim}")

and it yields:

image

Good:

  • it's possible to both zoom out and zoom in as expected;
  • the resulting colors are not impacted by zooming in / zooming out. I think this is nice;
  • the subsequent scatter plot does not cancel the limits passed to the display.

Not so good:

  • we can see that zooming in results in large pcolormesh pixels. I suppose that similar zoom-induced resolution degradation would also happen with other the plot methods.

I am not sure how we could get the best of both words: stable colors across zoom levels while preserving the same resolution at any zoom level (without computing gigabytes of unrendered response values).

Maybe the zoom induced resolution degradation is not such a big deal. If we cannot devise any easy solution to this problem, +1 for merging as it is.

AnneBeyer and others added 2 commits February 6, 2026 22:22
Co-authored-by: Lucy Liu <[email protected]>
Co-authored-by: Lucy Liu <[email protected]>
@github-actions github-actions Bot added the CI:Linter failure The linter CI is failing on this PR label Feb 6, 2026
@github-actions github-actions Bot removed the CI:Linter failure The linter CI is failing on this PR label Feb 6, 2026
@AnneBeyer

Copy link
Copy Markdown
Member Author

Thank you for the feedback!

Is it possible to add a test for when xlim and ylim 'shrink' the grid, we infer n_classes thus checking that the colors remain consistent?

Good point, I'll try to come up with one.

I am not sure how we could get the best of both words: stable colors across zoom levels while preserving the same resolution at any zoom level (without computing gigabytes of unrendered response values).

I don't see a simple solution right away, but grid_resolution can be set by the user in from_estimator. Maybe we could add a note there that it should be increased when zooming in?

@lucyleeow

Copy link
Copy Markdown
Member

I don't see a simple solution right away, but grid_resolution can be set by the user in from_estimator. Maybe we could add a note there that it should be increased when zooming in?

Since this is only for purpose of inferring n_classes when using type_of_target what if we use the original X instead of the grid, as that should capture all classes/labels right? e.g.:

@@ -589,11 +589,19 @@ class DecisionBoundaryDisplay:
         elif is_clusterer(estimator) and hasattr(estimator, "labels_"):
             n_classes = len(np.unique(estimator.labels_))
         else:
-            target_type = type_of_target(response)
+            # Use original X (not grid) to infer number of classes/labels, ensuring all
+            # classes/labels are captured even if some fall outside the grid boundaries
+            response_all, _ = _get_response_values(
+                estimator,
+                X,
+                response_method=prediction_method,
+                pos_label=class_of_interest,
+            )
+            target_type = type_of_target(response_all)
             if target_type in ("binary", "continuous"):
                 n_classes = 2
             elif target_type == "multiclass":
-                n_classes = len(np.unique(response))
+                n_classes = len(np.unique(response_all))
             else:
                 raise ValueError(
                     "Number of classes or labels cannot be inferred from "

@AnneBeyer

Copy link
Copy Markdown
Member Author

Since this is only for purpose of inferring n_classes when using type_of_target what if we use the original X instead of the grid, as that should capture all classes/labels right?

That sounds reasonable. Especially since we might need to calculate these again anyway for the scatter plot integration planned in #33094
I'll adapt the code.

@github-project-automation github-project-automation Bot moved this to Todo in Labs Feb 9, 2026
@StefanieSenger StefanieSenger moved this from Todo to In progress - High Priority in Labs Feb 9, 2026
@auguste-probabl auguste-probabl moved this from In progress - High Priority to In progress in Labs Feb 9, 2026
@AnneBeyer

Copy link
Copy Markdown
Member Author

It turns out to be a bit more complex again: Since we currently just store the number of classes, the colors are not consistent when zooming in, because plot just selects the first ones from the colormap as it doesn't know about the order of the classes. I think we also need to first map the classes to their indices and select the colors based on that. This makes things a bit more complicated, but I think it will also be necessary to ensure consistency for the scatterplot, so I think it is worth the effort.

@AnneBeyer

Copy link
Copy Markdown
Member Author

Ah, actually, the LabelEncoder takes care of the mapping (at least for classifiers), so it is actually only a matter of selecting colors according to the response values in plot. For predict, this is straight forward, for the others it should be the same conceptually, I'll look into that next.

@AnneBeyer
AnneBeyer marked this pull request as draft February 10, 2026 10:07
@AnneBeyer

Copy link
Copy Markdown
Member Author

In the end it was even easier for the non-predict contourf and pcolormesh versions, as the enumeration already takes care of the color selection.

Note: This PR does not address the following cases (which will be addressed in their own PRs):

  • Matching colors of scatterplot for clusterers (see #33094 and #33119)
  • The contour case (see #33108)

I will still look into adding an explicit test for the color consistency when zooming in.

@AnneBeyer

Copy link
Copy Markdown
Member Author

New can of worms:
For the binary cases (binary classification/clustering, outlier-detection and regression (as we decided to treat it like binary decision_function)), we don't handle the color selection (see Point 4 in #33115), so there is currently no easy way of making the colors stay consistent when zooming in in these cases.

I don't want to mix these things up, so I think it makes sense to pause this PR until I tackled #33115 and #33094, then I can check if @lucyleeow's suggestion can be integrated more easily to solve the pixel issue.

@AnneBeyer AnneBeyer moved this from PR Stalled to In progress in Labs Aug 20, 2026
@AnneBeyer AnneBeyer moved this from In progress to PR Stalled in Labs Aug 31, 2026

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

Projects

Status: PR stalled

Development

Successfully merging this pull request may close these issues.

4 participants