Skip to content

Commit

Permalink
feat: add function to merge handles for identical labels in legend (#516
Browse files Browse the repository at this point in the history
)

* Add function to merge handles for identical labels in legend

This function is useful, when using multiple plotting functions and one only wants to use a single label.
This function combines all the handles for identical labels into a single handle.

* Make merge_legend_handles_labels function available
  • Loading branch information
cverstege authored Sep 13, 2024
1 parent fcb11df commit 7329a18
Show file tree
Hide file tree
Showing 2 changed files with 27 additions and 0 deletions.
2 changes: 2 additions & 0 deletions src/mplhep/__init__.py
Original file line number Diff line number Diff line change
Expand Up @@ -18,6 +18,7 @@
hist2dplot,
histplot,
make_square_add_cbar,
merge_legend_handles_labels,
mpl_magic,
rescale_to_axessize,
sort_legend,
Expand Down Expand Up @@ -70,6 +71,7 @@
"rescale_to_axessize",
"box_aspect",
"make_square_add_cbar",
"merge_legend_handles_labels",
"append_axes",
"sort_legend",
"save_variations",
Expand Down
25 changes: 25 additions & 0 deletions src/mplhep/plot.py
Original file line number Diff line number Diff line change
Expand Up @@ -1408,3 +1408,28 @@ def sort_legend(ax, order=None):
if isinstance(order, OrderedDict):
ordered_label_list = [order[k] for k in ordered_label_list]
return ordered_label_values, ordered_label_list


def merge_legend_handles_labels(handles, labels):
"""
Merge handles for identical labels.
This is useful when combining multiple plot functions into a single label.
handles : List of handles
labels : List of labels
"""

seen_labels = []
seen_label_handles = []
for handle, label in zip(handles, labels):
if label not in seen_labels:
seen_labels.append(label)
seen_label_handles.append([handle])
else:
idx = seen_labels.index(label)
seen_label_handles[idx].append(handle)

for i in range(len(seen_labels)):
seen_label_handles[i] = tuple(seen_label_handles[i])

return seen_label_handles, seen_labels

0 comments on commit 7329a18

Please sign in to comment.