From 7b3e4dfd211190113d6d4e64d46882e1b2402ab6 Mon Sep 17 00:00:00 2001 From: Michael Waskom Date: Sat, 11 Jun 2022 16:02:41 -0400 Subject: [PATCH] Fix hue_order as a subset in scatterplot (#2848) Fixes #2590 --- doc/releases/v0.12.0.txt | 2 ++ seaborn/_oldcore.py | 7 +++++++ tests/test_relational.py | 11 +++++++++++ 3 files changed, 20 insertions(+) diff --git a/doc/releases/v0.12.0.txt b/doc/releases/v0.12.0.txt index 82881a3b15..a026fb99a8 100644 --- a/doc/releases/v0.12.0.txt +++ b/doc/releases/v0.12.0.txt @@ -61,6 +61,8 @@ Other updates - |Fix| Fixed a bug in :class:`PairGrid` where and error would be raised when defining `hue` only in the mapping methods (:pr:`2847`). +- |Fix| Fixed a bug in :func:`scatterplot` where an error would be raised when `hue_order` was a subset of the hue levels (:pr:`2848`). + - |Fix| Subplot titles will no longer be reset when calling :meth:`FacetGrid.map` or :meth:`FacetGrid.map_dataframe` (:pr:`2705`). - |Fix| In :func:`lineplot`, allowed the `dashes` keyword to set the style of a line without mapping a `style` variable (:pr:`2449`). diff --git a/seaborn/_oldcore.py b/seaborn/_oldcore.py index c9218c1f84..8821a5de3b 100644 --- a/seaborn/_oldcore.py +++ b/seaborn/_oldcore.py @@ -149,6 +149,13 @@ def _lookup_single(self, key): # Use a value that's in the original data vector value = self.lookup_table[key] except KeyError: + + if self.norm is None: + # Currently we only get here in scatterplot with hue_order, + # because scatterplot does not consider hue a grouping variable + # So unused hue levels are in the data, but not the lookup table + return (0, 0, 0, 0) + # Use the colormap to interpolate between existing datapoints # (e.g. in the context of making a continuous legend) try: diff --git a/tests/test_relational.py b/tests/test_relational.py index eb8d635c56..f98cace2dc 100644 --- a/tests/test_relational.py +++ b/tests/test_relational.py @@ -9,6 +9,7 @@ from seaborn.external.version import Version from seaborn.palettes import color_palette +from seaborn._oldcore import categorical_order from seaborn.relational import ( _RelationalPlotter, @@ -1623,6 +1624,16 @@ def test_supplied_color_array(self, long_df): _draw_figure(ax.figure) assert_array_equal(ax.collections[0].get_facecolors(), colors) + def test_hue_order(self, long_df): + + order = categorical_order(long_df["a"]) + unused = order.pop() + + ax = scatterplot(data=long_df, x="x", y="y", hue="a", hue_order=order) + points = ax.collections[0] + assert (points.get_facecolors()[long_df["a"] == unused] == 0).all() + assert [t.get_text() for t in ax.legend_.texts] == order + def test_linewidths(self, long_df): f, ax = plt.subplots()