From 619bdf1ecee21384d6ede4486655500b0f807fa3 Mon Sep 17 00:00:00 2001 From: Hassan Kibirige Date: Fri, 12 Jun 2026 14:37:47 +0300 Subject: [PATCH] feat: accept a scalar value in factor() A scalar (int, float or str) passed to factor() within an aes() expression is now wrapped in a list before creating the Categorical. --- doc/changelog.qmd | 7 +++++++ plotnine/mapping/_eval_environment.py | 5 ++++- 2 files changed, 11 insertions(+), 1 deletion(-) diff --git a/doc/changelog.qmd b/doc/changelog.qmd index 61c044646..5d7888016 100644 --- a/doc/changelog.qmd +++ b/doc/changelog.qmd @@ -91,6 +91,13 @@ title: Changelog ### Enhancements +- The `factor` function available when evaluating expressions in + [](:class:`~plotnine.aes`) now accepts a scalar value. + + ```python + ggplot(mtcars, aes("wt", "mpg", color="factor(4)")) + geom_point() + ``` + - Increased the default linespacing used by themes from `0.9` to `1.2`. This gives multiline titles, subtitles and captions a better balance between looking compact and looking crumpled. diff --git a/plotnine/mapping/_eval_environment.py b/plotnine/mapping/_eval_environment.py index 8a71d29cb..0aca64a5f 100644 --- a/plotnine/mapping/_eval_environment.py +++ b/plotnine/mapping/_eval_environment.py @@ -23,7 +23,7 @@ def factor( - values: Sequence[Any], + values: Sequence[Any] | float | str, categories: Sequence[Any] | None = None, ordered: bool | None = None, ) -> pd.Categorical: @@ -48,6 +48,9 @@ def factor( `categories` attribute (which in turn is the `categories` argument, if provided). """ + if isinstance(values, (int, float, str)): + values = [values] + return pd.Categorical(values, categories=categories, ordered=None) # pyright: ignore[reportReturnType]