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

Conversation

cverstege
Copy link

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.
I think this comes in handy. e.g. when doing a step plot for a main line and a band around for the uncertainty.

I'm open for feedback.

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.
@andrzejnovak
Copy link
Member

Hi @cverstege , this looks ok for me and we already collect some "random" helpers. For posterity, could you add a couple of snippets of how you use it as a comment to this PR?

@cverstege
Copy link
Author

cverstege commented Sep 13, 2024

Sure. Here's one example:

import mplhep as hep
import numpy as np
import matplotlib.pyplot as plt


if __name__=="__main__":
    s = np.random.normal(size=1000)
    hist, bins = np.histogram(s)
    error = np.sqrt(hist)

    hep.style.use("CMS")
    fig, (ax1, ax2) = plt.subplots(2, 1)
    for ax in (ax1, ax2):
        hep.histplot(hist, bins=bins, yerr=error, histtype="band", label="same label", ax=ax, zorder=-1)
        hep.histplot(hist, bins=bins, histtype="step", color="black", label="same label", ax=ax, zorder=0)
    ax1.legend(loc="upper right")
    handles, labels = ax2.get_legend_handles_labels()
    handles, labels = hep.merge_legend_handles_labels(handles, labels)
    ax2.legend(handles, labels, loc="upper right")
    plt.savefig("test.png")

@cverstege
Copy link
Author

And here the plot for reference. The upper one is not using the new function, while the lower one has the combined legend entry.
test

@andrzejnovak andrzejnovak changed the title Add function to merge handles for identical labels in legend feat: add function to merge handles for identical labels in legend Sep 13, 2024
@andrzejnovak andrzejnovak merged commit 7329a18 into scikit-hep:master Sep 13, 2024
11 checks passed
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Labels
None yet
Projects
None yet
Development

Successfully merging this pull request may close these issues.

2 participants