Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

feat: add function to merge handles for identical labels in legend #516

Merged
merged 2 commits into from
Sep 13, 2024
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
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
Loading