Skip to content

fix(scales): treat values outside discrete position limits as missing - #1160

Open
tushar-mahalya wants to merge 1 commit into
has2k1:mainfrom
tushar-mahalya:fix/discrete-position-unmatched
Open

tushar-mahalya wants to merge 1 commit into
has2k1:mainfrom
tushar-mahalya:fix/discrete-position-unmatched

Conversation

@tushar-mahalya

@tushar-mahalya tushar-mahalya commented Nov 25, 2026 •

Copy link
Copy Markdown

I ran into this while setting explicit limits on a discrete x scale. A value that isn't in the limits should be dropped, but in a small layer it gets drawn on top of one of the real categories instead:

import pandas as pd
from plotnine import aes, geom_point, ggplot, scale_x_discrete

data = pd.DataFrame({"x": list("abcdef"), "y": range(6)})
extra = pd.DataFrame({"x": ["z"], "y": [3]})  # "z" is not one of the limits

p = (
    ggplot(data, aes("x", "y"))
    + geom_point()
    + geom_point(data=extra, color="red")
    + scale_x_discrete(limits=list("abcdef"))
)
print(p.build().layers[1].data[["x", "y"]].values.tolist())

On main this prints [[2.0, 3.0]], so the red point sits on "b". With this branch it's [[nan, 3.0]] and the point is removed like any other missing value, which is what ggplot2 does.

The cause is nomatch=len(x) in scale_position_discrete.map. That goes back to the fix for #342, and it relies on the index running past the end of the position sequence so the IndexError branch inserts NaN. That only happens when the layer has at least as many rows as the scale has limits, so smaller layers still get the #342 behaviour. I switched to the default nomatch=-1 and turn negative indices into NaN, which also lets the try/except go.

There's a scale-level test and one on the built layer data, both failing before the change, and a changelog entry. The rest of the suite matches main for me (the loess tests and the lint-subprocess tests fail locally only because scikit-misc and ruff aren't installed here).

scale_position_discrete.map used nomatch=len(x) when matching values to the limits, so in a layer with fewer rows than the scale has limits an unmatched value was mapped to the position of an existing category instead of NaN.

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.

1 participant