From ce38485fbf4f9d251df6840fe5154fe9b33bafb9 Mon Sep 17 00:00:00 2001 From: Hassan Kibirige Date: Mon, 6 May 2024 15:26:27 +0300 Subject: [PATCH] ENH: Fewer spurious legend + after_scale warnings --- doc/changelog.qmd | 8 ++++++++ plotnine/guides/guide_legend.py | 16 ++++++++++++++-- plotnine/layer.py | 2 +- tests/test_guide_internals.py | 16 ++++++++++++++++ 4 files changed, 39 insertions(+), 3 deletions(-) create mode 100644 tests/test_guide_internals.py diff --git a/doc/changelog.qmd b/doc/changelog.qmd index f5ef3c866..3f62e23eb 100644 --- a/doc/changelog.qmd +++ b/doc/changelog.qmd @@ -1,6 +1,14 @@ --- title: Changelog --- +## v0.13.6 +(not-yet-released) + +### Enhancements + +- Stopped spurious warnings of the form ``PlotnineWarning: Failed to apply + `after_scale` modifications to the legend.`` when the `after_scale` + mapping is for another aesthetic. ## v0.13.5 (2024-04-26) diff --git a/plotnine/guides/guide_legend.py b/plotnine/guides/guide_legend.py index 995097b8d..1b967e70e 100644 --- a/plotnine/guides/guide_legend.py +++ b/plotnine/guides/guide_legend.py @@ -160,16 +160,28 @@ def create_geoms(self): continue matched = self.legend_aesthetics(l) + matched_set = set(matched) # This layer does not contribute to the legend - if not set(matched) - exclude: + if not matched_set - exclude: continue data = self.key[matched].copy() # Modify aesthetics + + # When doing after_scale evaluations, we only consider those + # for the aesthetics of this legend. The reduces the spurious + # warnings where an evaluation of another aesthetic failed yet + # it is not needed. + aes_modifiers = { + ae: expr + for ae, expr in l.mapping._scaled.items() + if ae in matched_set + } + try: - data = l.use_defaults(data) + data = l.use_defaults(data, aes_modifiers=aes_modifiers) except PlotnineError: warn( "Failed to apply `after_scale` modifications " diff --git a/plotnine/layer.py b/plotnine/layer.py index 79ad1358d..1d21d452d 100644 --- a/plotnine/layer.py +++ b/plotnine/layer.py @@ -386,7 +386,7 @@ def use_defaults( data = self.data if aes_modifiers is None: - aes_modifiers = self.mapping._scaled + aes_modifiers = {} return self.geom.use_defaults(data, aes_modifiers) diff --git a/tests/test_guide_internals.py b/tests/test_guide_internals.py new file mode 100644 index 000000000..e43ae9fd6 --- /dev/null +++ b/tests/test_guide_internals.py @@ -0,0 +1,16 @@ +import warnings + +from plotnine import ( + aes, + geom_point, + ggplot, +) +from plotnine.data import mtcars + + +def test_no_after_scale_warning(): + p = ggplot(mtcars, aes("wt", "mpg")) + geom_point() + + with warnings.catch_warnings(): + warnings.simplefilter("error") + p.draw_test() # type: ignore