mplhep: Matplotlib styles for HEP

repository·main·Indexed 42 days ago

https://github.com/scikit-hep/mplhep

A set of helpers and style sheets for Matplotlib designed to simplify the production of High Energy Physics (HEP) plots. It provides styling and labeling compatible with major collaboration requirements, including CMS, ATLAS, LHCb, ALICE, and DUNE. Key features include specialized plotting functions like `mplhep.histplot`, `mplhep.hist2dplot`, and `mplhep.funcplot`, as well as tools for managing figure layouts and experiment-specific annotations.

Tokens
24.5K
Snippets
95
Records
117
Agent score
53%

What's inside mplhep

  1. Overview of mplhep

    main

    mplhep is a matplotlib wrapper designed to simplify the plotting requirements common in High Energy Physics (HEP).

    Key features include:

    • Easy plotting of "prebinned" 1D and 2D histograms.
    • Matplotlib style-sheets that implement the recommended plotting styles used by major LHC experiments, specifically ATLAS, CMS, and LHCb.
  2. Explore mplhep user guides

    main

    The mplhep documentation is organized into several functional areas:

    • Histogram Plotting: Functions for 1D and 2D pre-binned histograms, including support for the Unified Histogram Interface (UHI). Topics include supported input formats, histogram styles, multiple histograms, blinding, error bars, and normalization.
    • Comparison Plotting: High-level functions for comparing data models, such as comparing two histograms or performing Data-MC comparisons.
    • Styling: Tools for applying official experiment styles (ATLAS, CMS, LHCb, ALICE, and DUNE) and configuring experiment labels.
    • Utilities: Helper functions for text placement, subplot creation, saving variations, fitting y-labels, axes manipulation, and a plt.hist wrapper.
    • Advanced Topics: Deep dives into UHI integration and best practices.
  3. Choose between ATLAS1 and ATLAS2 styles

    main

    The ATLAS experiment has two primary recommended styles in mplhep:

    1. ATLAS or ATLAS2: The main recommendation. It provides a palette of 7 colors. The first color, Vermilion, is specifically recommended for representing signal. For large signals, white can also be used.
    2. ATLAS1: Provided for plots that require a larger number of colors (10 colors total).

    Use mplhep.style.use("ATLAS2") for standard signal plots and mplhep.style.use("ATLAS1") when you need more distinct colors.

    import mplhep
    
    # Use the standard 7-color palette
    mplhep.style.use("ATLAS2")
    
    # Use the 10-color palette for complex plots
    # mplhep.style.use("ATLAS1")
  4. Blind signal regions in comparisons

    main

    The blind parameter can be used in mh.comp.hists() and mh.comp.data_model() to hide specific regions in both the main plot and the comparison panel. This is useful for blind analyses where a signal region must remain hidden.

    Pass a tuple (lower_bound, upper_bound) to the blind argument to specify the range to be hidden.

    # Blinding in a two-histogram comparison
    fig, ax_main, ax_comp = mh.comp.hists(
        h1,
        h2,
        blind=(-1.0, 1.0),  # Blind the region from -1 to 1 GeV
        comparison='ratio',
        xlabel='Observable [GeV]',
        ylabel='Events'
    )
  5. Configure experiment label content

    main

    You can customize the information displayed in experiment labels.

    • Common configurations: Use standard parameters to combine multiple pieces of information (like name, status, and run info).
    • Full customization: For complete control over the text content, use llabel (left label) and rlabel (right label) parameters.
    # Example of conceptual customization
    # mh.cms_label(ax, llabel='Custom Left Text', rlabel='Custom Right Text')
  6. Choose between DUNE and DUNE1 styles

    main

    For the DUNE neutrino experiment, there are two ways to access styles:

    • DUNE: This is a pointer to the newest available style. Use this to ensure your plots always use the most up-to-date styling as mplhep is updated.
    • DUNE1: Use this if you need to ensure backwards compatibility and want to prevent your plot styles from changing when the experiment updates its recommendations.
    import mplhep
    
    # Always use the latest DUNE style
    mplhep.style.use("DUNE")
    
    # Use DUNE1 for stable, backwards-compatible styling
    # mplhep.style.use("DUNE1")
  7. How style-specific guide generation works

    main

    To avoid manually maintaining separate guide files for different experiment styles (CMS, ATLAS, LHCb, ALICE, DUNE, and plothist), mplhep uses an automated template-based system.

    The Workflow

    1. Templates: Files named docs/*_template.md contain content with tab placeholders marked by {{TABS_START}} and {{TABS_END}}.
    2. Generation: The generate_style_guides.py script expands these placeholders with style-specific code.
    3. Automation: A MkDocs hook (docs_hooks.py) automatically runs the generation script before every build.
    4. Output: The final documentation is rendered from the generated docs/*.md files (the ones without the _template suffix).

    Template Placeholders

    Inside {{TABS_START}} and {{TABS_END}} blocks, the following placeholders are replaced per style:

    • {{STYLE_NAME}}: Full style name (e.g., "CMS").
    • {{STYLE_CODE}}: The string used in mh.style.use() (e.g., "LHCb2").
    • {{LABEL_CODE}}: The specific label code including all parameters.
    • {{LABEL_CODE_NODATA}}: Label code without the data parameter.
    • {{LABEL_CODE_DATA}}: Label code with data=True.
    • {{LABEL_CODE_AX}}: Label code including the ax parameter.
    • {{LABEL_CODE_LUMI}}: Label code including luminosity.
    • {{MAGIC_CODE}}: The mpl_magic() call (used for ATLAS and ALICE).
    {{TABS_START}}
    {{TAB_HEADER}}
    
        ```python
        # mkdocs: render
        import mplhep as mh
    
        mh.style.use('{{STYLE_CODE}}')
        # ... code ...
        {{LABEL_CODE}}
    {{MAGIC_CODE}}    ax.legend()
        ```
    
    {{TABS_END}}
  8. Quick start with mplhep

    main

    Once installed, you can use mplhep to apply high-energy physics styles (like CMS, ATLAS, or LHCb2) to your Matplotlib plots and use specialized plotting functions like mh.histplot.

    import numpy as np
    import matplotlib.pyplot as plt
    import mplhep as mh
    
    # Load style sheet
    plt.style.use(mh.style.CMS)  # or ATLAS/LHCb2
    
    h, bins = np.histogram(np.random.random(1000))
    fig, ax = plt.subplots()
    mh.histplot(h, bins)
  9. Modify or add experiment styles in documentation

    main

    Documentation styles are managed in generate_style_guides.py.

    To update existing templates

    1. Edit the docs/*_template.md file.
    2. Use {{TABS_START}} and {{TABS_END}} for content that varies by style.
    3. Run python generate_style_guides.py to test the generation.

    To add a new style

    1. Add the new style configuration to the STYLES dictionary in generate_style_guides.py.
    2. Add the style name to the STYLE_ORDER list in generate_style_guides.py.
    3. Run the generation script.

    To modify style-specific code

    1. Edit the corresponding entry in the STYLES dictionary within generate_style_guides.py.
    2. Run python generate_style_guides.py to regenerate the files.
    python generate_style_guides.py
  10. Install mplhep via pip

    main

    You can install mplhep using pip. Depending on your environment and permissions, use one of the following commands:

    • Standard installation (system-wide or current virtual environment): pip install mplhep
    • Local user installation (if you lack administrator permissions): pip install --user mplhep
    • Upgrade an existing installation: pip install --upgrade mplhep

    If you use Conda, activate your desired environment and use the conda-provided pip to install it.

    pip install mplhep