Matplotlib styles for HEP
mplhep is a Python library providing Matplotlib styles and utility functions tailored for High Energy Physics (HEP) plotting. It simplifies the creation of plots compatible with various LHC experiments (ATLAS, CMS, LHCb, ALICE) and offers tools for 1D and 2D histograms, including comparison plots. The library is actively maintained, with the current version being 1.1.2, and sees regular patch and minor releases.
Warnings
- breaking mplhep versions 1.0.0 and later have dropped support for Python 3.8. Attempting to install or run with Python 3.8 will result in errors.
- deprecated For Matplotlib versions 3.6 and later, the `axes.Grouper.join()` method, previously used for sharing axes, is deprecated. Older mplhep versions (prior to v1.0.0.rc8) might have compatibility issues or warnings.
- breaking The `v1.0.0` release (and its release candidates like `v1.0.0.rc4`) included significant API refactors (`refactor!`) and introduced new functionalities, such as comparison plotters. Code written for pre-1.0.0 versions, especially regarding label positioning and comparison plots, may require updates.
- gotcha As of `v1.0.0.rc5`, `mplhep` introduced `mplhep.hist()` as a wrapper designed to match the `matplotlib.pyplot.hist()` API. While `hep.histplot()` remains available, `hep.hist()` provides an alternative for users accustomed to `plt.hist()`'s signature.
Install
-
pip install mplhep
Imports
- mplhep
import mplhep as hep
- matplotlib.pyplot
import matplotlib.pyplot as plt
- hep.style.use
hep.style.use("CMS") - hep.histplot
hep.histplot(...)
Quickstart
import matplotlib.pyplot as plt
import mplhep as hep
import numpy as np
# Set the CMS experiment style
hep.style.use("CMS")
# Generate some dummy data for a histogram
data = np.random.normal(loc=5, scale=2, size=1000)
bins = np.linspace(0, 10, 20)
hist, edges = np.histogram(data, bins=bins)
# Create a figure and axes
fig, ax = plt.subplots()
# Plot the histogram using mplhep's histplot
hep.histplot(hist, edges, ax=ax, label="My Data")
# Add experiment label (e.g., CMS)
hep.cms.label(loc=0, data=True, lumi=20, year=2018, ax=ax)
# Add a legend and show the plot
ax.legend()
ax.set_xlabel("X-axis [GeV]")
ax.set_ylabel("Entries")
plt.tight_layout()
plt.show()