Skip to content

Commit d0d0f0b

Browse files
EltonChang1has2k1
authored andcommitted
Fix facet grid categorical missing IDs
1 parent 6dcd7b6 commit d0d0f0b

3 files changed

Lines changed: 35 additions & 0 deletions

File tree

plotnine/_utils/__init__.py

Lines changed: 3 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -372,6 +372,9 @@ def _id_var(x: AnyArrayLike, drop: bool = False) -> list[int]:
372372
if drop:
373373
x = x.cat.remove_unused_categories()
374374
lst = list(x.cat.codes + 1)
375+
if 0 in lst:
376+
new_nan_code = max(lst) + 1
377+
lst = [val if val != 0 else new_nan_code for val in lst]
375378
else:
376379
has_nan = any(np.isnan(i) for i in x if isinstance(i, float))
377380
if has_nan:

tests/test_facets.py

Lines changed: 19 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -222,6 +222,25 @@ def test_facetting_with_unused_categories():
222222
p.draw_test() # pyright: ignore
223223

224224

225+
def test_facet_grid_with_missing_categorical_values():
226+
data = pd.DataFrame(
227+
{
228+
"x": [0.0] * 6,
229+
"y": [0.0] * 6,
230+
"row": ["a", "a", "a", "b", "b", "b"],
231+
"col": pd.Categorical(
232+
["x", "y", None, "x", "y", None],
233+
categories=["x", "y"],
234+
),
235+
}
236+
)
237+
238+
p = ggplot(data, aes("x", "y")) + geom_point() + facet_grid("row ~ col")
239+
240+
# No exception
241+
p.draw_test() # pyright: ignore
242+
243+
225244
def test_invalid_scales_value_raises():
226245
with pytest.raises(ValueError):
227246
# note the missing underscore

tests/test_utils.py

Lines changed: 13 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -131,6 +131,19 @@ def test_ninteraction():
131131
assert ninteraction(data) == [1]
132132

133133

134+
def test_ninteraction_drops_unused_categorical_levels_with_missing():
135+
data = pd.DataFrame(
136+
{
137+
"a": pd.Categorical(
138+
["x", "y", None, "x"],
139+
categories=["x", "unused", "y"],
140+
)
141+
}
142+
)
143+
144+
assert ninteraction(data, drop=True) == [1, 2, 3, 1]
145+
146+
134147
def test_ninteraction_datetime_series():
135148
# When a pandas datetime is converted Numpy datetime, the two
136149
# no longer compare as equal! This test ensures that case is

0 commit comments

Comments
 (0)