From e2679d7a15595e200ce948ef63cc943b58ab716e Mon Sep 17 00:00:00 2001 From: Tim Hoffmann <2836374+timhoffm@users.noreply.github.com> Date: Sat, 28 Mar 2026 03:14:52 +0100 Subject: [PATCH] MNT: Minor cleanup of label formatting in PathCollection.legend_elements --- lib/matplotlib/collections.py | 15 ++++++++++----- 1 file changed, 10 insertions(+), 5 deletions(-) diff --git a/lib/matplotlib/collections.py b/lib/matplotlib/collections.py index 27b3789a3105..b2f8255367e8 100644 --- a/lib/matplotlib/collections.py +++ b/lib/matplotlib/collections.py @@ -1271,7 +1271,15 @@ def legend_elements(self, prop="colors", num="auto", "alpha": self.get_alpha(), **kwargs} - for val, lab in zip(values, label_values): + # Pre-format all labels + # TODO: check whether we can switch to + # formatted_labels = fmt.format_ticks(label_values) + # There are subtle differences for some formatters as that passes the + # indices to __call__ as well. + fmt.set_locs(label_values) + formatted_labels = [fmt(lab) for lab in label_values] + + for val, formatted in zip(values, formatted_labels): if prop == "colors": color = self.cmap(self.norm(val)) elif prop == "sizes": @@ -1281,10 +1289,7 @@ def legend_elements(self, prop="colors", num="auto", h = mlines.Line2D([0], [0], ls="", color=color, ms=size, marker=self.get_paths()[0], **kw) handles.append(h) - if hasattr(fmt, "set_locs"): - fmt.set_locs(label_values) - l = fmt(lab) - labels.append(l) + labels.append(formatted) return handles, labels