Skip to content

API reference¤

Top Level¤

mplhep ¤

Primary namespace for mplhep. Holds primary plotting and most common functions.

mplhep.histplot ¤

histplot(H, bins=None, *, yerr: ArrayLike | bool | None = None, w2=None, w2method=None, stack: bool = False, density: bool = False, binwnorm=None, histtype: str = 'step', xerr=False, label=None, sort=None, edges=True, binticks=False, xoffsets=None, ax: Axes | None = None, flow='hint', **kwargs)

Create a 1D histogram plot from np.histogram-like inputs.

Parameters:

Name Type Description Default
H object

Histogram object with containing values and optionally bins. Can be:

  • np.histogram tuple
  • PlottableProtocol histogram object
  • boost_histogram classic (<0.13) histogram object
  • raw histogram values, provided bins is specified.

Or list thereof.

required
bins iterable

Histogram bins, if not part of H.

None
yerr iterable or bool

Histogram uncertainties. Following modes are supported: - True, sqrt(N) errors or poissonian interval when w2 is specified - shape(N) array of for one sided errors or list thereof - shape(Nx2) array of for two sided errors or list thereof

None
w2method

Function calculating CLs with signature low, high = fcn(w, w2). Here low and high are given in absolute terms, not relative to w. Default is None. If w2 has integer values (likely to be data) poisson interval is calculated, otherwise the resulting error is symmetric sqrt(w2). Specifying poisson or sqrt will force that behaviours.

None
stack bool

Whether to stack or overlay non-axis dimension (if it exists). N.B. in contrast to ROOT, stacking is performed in a single call aka histplot([h1, h2, ...], stack=True) as opposed to multiple calls.

False
density bool

If true, convert sum weights to probability density (i.e. integrates to 1 over domain of axis) (Note: this option conflicts with binwnorm)

False
binwnorm float

If true, convert sum weights to bin-width-normalized, with unit equal to supplied value (usually you want to specify 1.)

None
histtype str

Type of histogram to plot:

  • "step": skyline/step/outline of a histogram using plt.stairs <https://matplotlib.org/stable/api/_as_gen/matplotlib.axes.Axes.stairs.html#matplotlib-axes-axes-stairs>_
  • "fill": filled histogram using plt.stairs <https://matplotlib.org/stable/api/_as_gen/matplotlib.axes.Axes.stairs.html#matplotlib-axes-axes-stairs>_
  • "errorbar": single marker histogram using plt.errorbar <https://matplotlib.org/stable/api/_as_gen/matplotlib.axes.Axes.errorbar.html#matplotlib-axes-axes-errorbar>_
  • "bar": If multiple data are given the bars are arranged side by side using plt.bar <https://matplotlib.org/stable/api/_as_gen/matplotlib.axes.Axes.bar.html#matplotlib-axes-axes-bar>_ If only one histogram is provided, it will be treated as "fill" histtype
  • "barstep": If multiple data are given the steps are arranged side by side using plt.stairs <https://matplotlib.org/stable/api/_as_gen/matplotlib.axes.Axes.stairs.html#matplotlib-axes-axes-stairs>_ . Supports yerr representation. If one histogram is provided, it will be treated as "step" histtype.
  • "band": filled band spanning the yerr range of the histogram using plt.stairs <https://matplotlib.org/stable/api/_as_gen/matplotlib.axes.Axes.stairs.html#matplotlib-axes-axes-stairs>_
'step'
label str or list

Label for legend entry.

None
sort

Append '_r' for reverse.

None
ax Axes

Axes object (if None, last one is fetched or one is created)

None
flow str, optional { "show", "sum", "hint", "none"}

Whether plot the under/overflow bin. If "show", add additional under/overflow bin. If "sum", add the under/overflow bin content to first/last bin.

'hint'
**kwargs

Keyword arguments passed to underlying matplotlib functions - {'stairs', 'errorbar'}.

{}

Other Parameters:

Name Type Description
w2 iterable

Sum of the histogram weights squared for poissonian interval error calculation

xerr

Size of xerr if histtype == 'errorbar'. If True, bin-width will be used.

edges bool

Specifies whether to draw first and last edges of the histogram

binticks bool

Attempts to draw x-axis ticks coinciding with bin boundaries if feasible.

xoffsets

If True, the bin "centers" of plotted histograms will be offset within their bin.

Returns:

Type Description
List[Hist1DArtists]

mplhep.hist2dplot ¤

hist2dplot(H, xbins=None, ybins=None, labels=None, labels_fontsize=None, labels_round=None, labels_color=None, cbar: bool = True, cbarsize='7%', cbarpad=0.2, cbarpos='right', cbarextend=True, cmin=None, cmax=None, ax: Axes | None = None, flow='hint', binwnorm=None, **kwargs)

Create a 2D histogram plot from np.histogram-like inputs.

Parameters:

Name Type Description Default
H object

Histogram object with containing values and optionally bins. Can be:

  • np.histogram tuple
  • boost_histogram histogram object
  • raw histogram values as list of list or 2d-array
required
xbins 1D array-like

Histogram bins along x axis, if not part of H.

None
ybins 1D array-like

Histogram bins along y axis, if not part of H.

None
labels 2D array (H-like) or bool

Array of per-bin labels to display. If True will display numerical values

None, optional
labels_fontsize float

Fontsize of labels.

None
labels_color str

Color of labels. If not given, will be decided automatically.

None
labels_round int

Round labels to given number of decimals

None
cbar bool

Draw a colorbar. In contrast to mpl behaviors the cbar axes is appended in such a way that it doesn't modify the original axes width:height ratio.

True
cbarsize str or float

Colorbar width.

"7%"
cbarpad float

Colorbar distance from main axis.

0.2
cbarpos ('right', 'left', 'bottom', 'top')

Colorbar position w.r.t main axis.

'right'
cbarextend bool

Extends figure size to keep original axes size same as without cbar. Only safe for 1 axes per fig.

False
cmin float

Colorbar minimum.

None
cmax float

Colorbar maximum.

None
ax Axes

Axes object (if None, last one is fetched or one is created)

None
flow str, optional {"show", "sum","hint", None}
Whether plot the under/overflow bin. If "show", add additional under/overflow bin. If "sum", add the under/overflow bin content to first/last bin. "hint" would highlight the bins with under/overflow contents
'hint'
binwnorm float

If true, convert sum weights to bin-width-normalized, with unit equal to supplied value (usually you want to specify 1.)

None
**kwargs

Keyword arguments passed to underlying matplotlib function - pcolormesh.

{}

Returns:

Type Description
Hist2DArtist

mplhep.funcplot ¤

funcplot(func, range, ax, stack=False, npoints=1000, **kwargs)

Plot a 1D function on a given range.

Parameters:

Name Type Description Default
func function or list of functions

The 1D function or list of functions to plot. The function(s) should support vectorization (i.e. accept a numpy array as input).

required
range tuple

The range of the function(s). The function(s) will be plotted on the interval [range[0], range[1]].

required
ax Axes

The Axes instance for plotting.

required
stack bool

Whether to use ax.stackplot() to plot the function(s) as a stacked plot. Default is False.

False
npoints int

The number of points to use for plotting. Default is 1000.

1000
**kwargs

Additional keyword arguments forwarded to ax.plot() (in case stack=False) or ax.stackplot() (in case stack=True).

{}

mplhep.add_text ¤

add_text(text: str, loc: str | None = None, x: float | str | None = None, y: float | str | None = None, pad: float | None = None, xpad: float | None = None, ypad: float | None = None, fontsize: float | None = None, white_background: bool = False, text_class: type[Text] = mtext.Text, ax: Axes | None = None, **kwargs: Any) -> mtext.Text

Add text to an axis with flexible positioning options.

Parameters:

Name Type Description Default
text str

The text to add to the axes.

required
loc str | None

Location shortcut similar to plt.legend(). Can be:

  • Inside axes: "upper left", "upper right", "lower left", "lower right"
  • Outside axes: "over left", "over right", "under left", "under right"
  • Alternative spellings: "top left", "top right", "bottom left", "bottom right"

If provided, overrides x and y parameters.

None
x float | str | None

Horizontal position of the text in normalized axes coordinates (0-1). String aliases: "left", "right", "left_in", "right_in", "right_out". Ignored if loc is provided.

None
y float | str | None

Vertical position of the text in normalized axes coordinates (0-1). String aliases: "top", "bottom", "top_in", "bottom_in", "top_out", "bottom_out". Ignored if loc is provided.

None
pad float | None

Padding percentage from edges for "in" positions, by default 5.0. Applied to the shorter dimension and scaled proportionally for the longer dimension.

None
xpad float | None

Horizontal padding percentage, overrides pad value for x-direction if provided.

None
ypad float | None

Vertical padding percentage, overrides pad value for y-direction if provided.

None
fontsize int | float | None

Font size, by default None (uses rcParams default).

None
white_background bool

Draw a white rectangle under the text, by default False.

False
text_class type[Text]

Text class to use for creating the text object, by default mtext.Text.

Text
ax Axes | None

Axes object to add text to. If None, uses current axes.

None
**kwargs Any

Additional keyword arguments passed to the text constructor. Notably 'ha' (horizontal alignment) and 'va' (vertical alignment) are set automatically based on position but can be overridden.

{}

Raises:

Type Description
ValueError

If both loc and x/y parameters are specified, or if x/y positions are not valid floats or recognized string aliases.

Returns:

Type Description
Text

The text object that was added to the axes.

mplhep.append_text ¤

append_text(s: str, txt_obj: Text, loc: str = 'right', pad: str | float = 'auto', ax: Axes | None = None, text_class: type[Text] = mtext.Text, _debug_x_override: float | None = None, **kwargs: Any) -> mtext.Text

Append text relative to an existing text object.

Parameters:

Name Type Description Default
s str

The text string to append.

required
txt_obj Text

The existing text object to append to.

required
loc str

Location relative to the existing text. Options are "right", "below", "above", or "left".

"right"
pad str | float

Padding between texts. If "auto", uses automatic spacing. If float, specifies padding as percentage of axes size.

"auto"
ax Axes | None

Axes object. If None, uses current axes.

None
text_class type[Text]

Text class to use for creating the new text object.

Text
**kwargs Any

Additional keyword arguments passed to the text constructor.

{}

Returns:

Type Description
Text

The appended text object.

Plotting¤

mplhep.plot ¤

mplhep.plot.histplot ¤

histplot(H, bins=None, *, yerr: ArrayLike | bool | None = None, w2=None, w2method=None, stack: bool = False, density: bool = False, binwnorm=None, histtype: str = 'step', xerr=False, label=None, sort=None, edges=True, binticks=False, xoffsets=None, ax: Axes | None = None, flow='hint', **kwargs)

Create a 1D histogram plot from np.histogram-like inputs.

Parameters:

Name Type Description Default
H object

Histogram object with containing values and optionally bins. Can be:

  • np.histogram tuple
  • PlottableProtocol histogram object
  • boost_histogram classic (<0.13) histogram object
  • raw histogram values, provided bins is specified.

Or list thereof.

required
bins iterable

Histogram bins, if not part of H.

None
yerr iterable or bool

Histogram uncertainties. Following modes are supported: - True, sqrt(N) errors or poissonian interval when w2 is specified - shape(N) array of for one sided errors or list thereof - shape(Nx2) array of for two sided errors or list thereof

None
w2method

Function calculating CLs with signature low, high = fcn(w, w2). Here low and high are given in absolute terms, not relative to w. Default is None. If w2 has integer values (likely to be data) poisson interval is calculated, otherwise the resulting error is symmetric sqrt(w2). Specifying poisson or sqrt will force that behaviours.

None
stack bool

Whether to stack or overlay non-axis dimension (if it exists). N.B. in contrast to ROOT, stacking is performed in a single call aka histplot([h1, h2, ...], stack=True) as opposed to multiple calls.

False
density bool

If true, convert sum weights to probability density (i.e. integrates to 1 over domain of axis) (Note: this option conflicts with binwnorm)

False
binwnorm float

If true, convert sum weights to bin-width-normalized, with unit equal to supplied value (usually you want to specify 1.)

None
histtype str

Type of histogram to plot:

  • "step": skyline/step/outline of a histogram using plt.stairs <https://matplotlib.org/stable/api/_as_gen/matplotlib.axes.Axes.stairs.html#matplotlib-axes-axes-stairs>_
  • "fill": filled histogram using plt.stairs <https://matplotlib.org/stable/api/_as_gen/matplotlib.axes.Axes.stairs.html#matplotlib-axes-axes-stairs>_
  • "errorbar": single marker histogram using plt.errorbar <https://matplotlib.org/stable/api/_as_gen/matplotlib.axes.Axes.errorbar.html#matplotlib-axes-axes-errorbar>_
  • "bar": If multiple data are given the bars are arranged side by side using plt.bar <https://matplotlib.org/stable/api/_as_gen/matplotlib.axes.Axes.bar.html#matplotlib-axes-axes-bar>_ If only one histogram is provided, it will be treated as "fill" histtype
  • "barstep": If multiple data are given the steps are arranged side by side using plt.stairs <https://matplotlib.org/stable/api/_as_gen/matplotlib.axes.Axes.stairs.html#matplotlib-axes-axes-stairs>_ . Supports yerr representation. If one histogram is provided, it will be treated as "step" histtype.
  • "band": filled band spanning the yerr range of the histogram using plt.stairs <https://matplotlib.org/stable/api/_as_gen/matplotlib.axes.Axes.stairs.html#matplotlib-axes-axes-stairs>_
'step'
label str or list

Label for legend entry.

None
sort

Append '_r' for reverse.

None
ax Axes

Axes object (if None, last one is fetched or one is created)

None
flow str, optional { "show", "sum", "hint", "none"}

Whether plot the under/overflow bin. If "show", add additional under/overflow bin. If "sum", add the under/overflow bin content to first/last bin.

'hint'
**kwargs

Keyword arguments passed to underlying matplotlib functions - {'stairs', 'errorbar'}.

{}

Other Parameters:

Name Type Description
w2 iterable

Sum of the histogram weights squared for poissonian interval error calculation

xerr

Size of xerr if histtype == 'errorbar'. If True, bin-width will be used.

edges bool

Specifies whether to draw first and last edges of the histogram

binticks bool

Attempts to draw x-axis ticks coinciding with bin boundaries if feasible.

xoffsets

If True, the bin "centers" of plotted histograms will be offset within their bin.

Returns:

Type Description
List[Hist1DArtists]

mplhep.plot.hist2dplot ¤

hist2dplot(H, xbins=None, ybins=None, labels=None, labels_fontsize=None, labels_round=None, labels_color=None, cbar: bool = True, cbarsize='7%', cbarpad=0.2, cbarpos='right', cbarextend=True, cmin=None, cmax=None, ax: Axes | None = None, flow='hint', binwnorm=None, **kwargs)

Create a 2D histogram plot from np.histogram-like inputs.

Parameters:

Name Type Description Default
H object

Histogram object with containing values and optionally bins. Can be:

  • np.histogram tuple
  • boost_histogram histogram object
  • raw histogram values as list of list or 2d-array
required
xbins 1D array-like

Histogram bins along x axis, if not part of H.

None
ybins 1D array-like

Histogram bins along y axis, if not part of H.

None
labels 2D array (H-like) or bool

Array of per-bin labels to display. If True will display numerical values

None, optional
labels_fontsize float

Fontsize of labels.

None
labels_color str

Color of labels. If not given, will be decided automatically.

None
labels_round int

Round labels to given number of decimals

None
cbar bool

Draw a colorbar. In contrast to mpl behaviors the cbar axes is appended in such a way that it doesn't modify the original axes width:height ratio.

True
cbarsize str or float

Colorbar width.

"7%"
cbarpad float

Colorbar distance from main axis.

0.2
cbarpos ('right', 'left', 'bottom', 'top')

Colorbar position w.r.t main axis.

'right'
cbarextend bool

Extends figure size to keep original axes size same as without cbar. Only safe for 1 axes per fig.

False
cmin float

Colorbar minimum.

None
cmax float

Colorbar maximum.

None
ax Axes

Axes object (if None, last one is fetched or one is created)

None
flow str, optional {"show", "sum","hint", None}
Whether plot the under/overflow bin. If "show", add additional under/overflow bin. If "sum", add the under/overflow bin content to first/last bin. "hint" would highlight the bins with under/overflow contents
'hint'
binwnorm float

If true, convert sum weights to bin-width-normalized, with unit equal to supplied value (usually you want to specify 1.)

None
**kwargs

Keyword arguments passed to underlying matplotlib function - pcolormesh.

{}

Returns:

Type Description
Hist2DArtist

mplhep.plot.funcplot ¤

funcplot(func, range, ax, stack=False, npoints=1000, **kwargs)

Plot a 1D function on a given range.

Parameters:

Name Type Description Default
func function or list of functions

The 1D function or list of functions to plot. The function(s) should support vectorization (i.e. accept a numpy array as input).

required
range tuple

The range of the function(s). The function(s) will be plotted on the interval [range[0], range[1]].

required
ax Axes

The Axes instance for plotting.

required
stack bool

Whether to use ax.stackplot() to plot the function(s) as a stacked plot. Default is False.

False
npoints int

The number of points to use for plotting. Default is 1000.

1000
**kwargs

Additional keyword arguments forwarded to ax.plot() (in case stack=False) or ax.stackplot() (in case stack=True).

{}

mplhep.comp ¤

Comparison/compound plotting module.

This module provides functions to create comparison plots, such as ratio plots, data vs. model comparisons, and more.

mplhep.comp.ratio ¤

ratio(h1, h2, ax, xlabel='', h1_label='h1', h2_label='h2', comparison='ratio', comparison_ylabel=None, comparison_ylim=None, h1_w2method='sqrt', **histplot_kwargs)

Plot the comparison between two histograms.

Parameters:

Name Type Description Default
h1 histogram(Hist, boost_histogram, histogram, TH1)

The first histogram for comparison.

required
h2 histogram(Hist, boost_histogram, histogram, TH1)

The second histogram for comparison.

required
ax Axes

The axes to plot the comparison.

required
xlabel str

The label for the x-axis. Default is "".

''
h1_label str

The label for the first histogram. Default is "h1".

'h1'
h2_label str

The label for the second histogram. Default is "h2".

'h2'
comparison str

The type of comparison to plot ("ratio", "split_ratio", "pull", "difference", "relative_difference", "efficiency", or "asymmetry"). Default is "ratio". When the split_ratio option is used, both the h1 and h2 uncertainties are scaled down by the h2 bin contents, and the h2 adjusted uncertainties are shown separately as a hatched area.

'ratio'
comparison_ylabel str

The label for the y-axis. Default is the explicit formula used to compute the comparison plot.

None
comparison_ylim tuple or None

The y-axis limits for the comparison plot. Default is None. If None, standard y-axis limits are setup.

None
h1_w2method str

What kind of bin uncertainty to use for h1: "sqrt" for the Poisson standard deviation derived from the variance stored in the histogram object, "poisson" for asymmetrical uncertainties based on a Poisson confidence interval. Default is "sqrt". Asymmetrical uncertainties are not supported for the asymmetry and efficiency comparisons.

'sqrt'
**histplot_kwargs optional

Arguments to be passed to histplot(), called in case the comparison is "pull", or plot_error_hist(), called for every other comparison case. In the former case, the default arguments are histtype="stepfilled" and color="darkgrey". In the later case, the default argument is color="black".

{}

Returns:

Name Type Description
ax Axes

The axes with the plotted comparison.

See Also

plot_two_hist_comparison : Compare two histograms and plot the comparison.

mplhep.comp.data_model ¤

data_model(data_hist, stacked_components=None, stacked_labels=None, stacked_colors=None, unstacked_components=None, unstacked_labels=None, unstacked_colors=None, xlabel=None, ylabel=None, data_label='Data', stacked_kwargs=None, unstacked_kwargs_list=None, model_sum_kwargs=None, model_uncertainty=True, model_uncertainty_label='Model stat. unc.', data_w2method='poisson', fig=None, ax_main=None, ax_comparison=None, plot_only=None, **comparison_kwargs)

Compare data to model. The data uncertainties are computed using the Poisson confidence interval.

Parameters:

Name Type Description Default
data_hist histogram(Hist, boost_histogram, histogram, TH1)

The histogram for the data.

required
stacked_components list of histogram (e.g. Hist, boost_histogram, np.histogram, TH1)

The list of histograms to be stacked composing the model. Default is None.

None
stacked_labels list of str

The labels of the model stacked components. Default is None.

None
stacked_colors list of str

The colors of the model stacked components. Default is None.

None
unstacked_components list of histogram (e.g. Hist, boost_histogram, np.histogram, TH1)

The list of histograms not to be stacked composing the model. Default is None.

None
unstacked_labels list of str

The labels of the model unstacked components. Default is None.

None
unstacked_colors list of str

The colors of the model unstacked components. Default is None.

None
xlabel str

The label for the x-axis. Default is None.

None
ylabel str

The label for the y-axis. Default is None.

None
data_label str

The label for the data. Default is "Data".

'Data'
stacked_kwargs dict

The keyword arguments used when plotting the stacked components in plot_hist() or plot_function(), one of which is called only once. Default is None.

None
unstacked_kwargs_list list of dict

The list of keyword arguments used when plotting the unstacked components in plot_hist() or plot_function(), one of which is called once for each unstacked component. Default is None.

None
model_sum_kwargs dict

The keyword arguments for the plot_hist() function for the sum of the model components. Has no effect if all the model components are stacked or if the model is one unstacked element. The special keyword "show" can be used with a boolean to specify whether to show or not the sum of the model components. Default is None. If None is provided, this is set to {"show": True, "label": "Sum", "color": "navy"}.

None
model_uncertainty bool

If False, set the model uncertainties to zeros. Default is True.

True
model_uncertainty_label str

The label for the model uncertainties. Default is "Model stat. unc.".

'Model stat. unc.'
data_w2method str

What kind of bin uncertainty to use for data_hist: "sqrt" for the Poisson standard deviation derived from the variance stored in the histogram object, "poisson" for asymmetrical uncertainties based on a Poisson confidence interval. Default is "poisson".

'poisson'
fig Figure or None

The figure to use for the plot. If fig, ax_main and ax_comparison are None, a new figure will be created. Default is None.

None
ax_main Axes or None

The main axes for the histogram comparison. If fig, ax_main and ax_comparison are None, a new axes will be created. Default is None.

None
ax_comparison Axes or None

The axes for the comparison plot. If fig, ax_main and ax_comparison are None, a new axes will be created. Default is None.

None
plot_only str

If "ax_main" or "ax_comparison", only the main or comparison axis is plotted on the figure. Both axes are plotted if None is specified, which is the default. This can only be used when fig, ax_main and ax_comparison are not provided by the user.

None
**comparison_kwargs optional

Arguments to be passed to plot_comparison(), including the choice of the comparison function and the treatment of the uncertainties (see documentation of plot_comparison() for details). If they are not provided explicitly, the following arguments are passed by default: h1_label="Data", h2_label="Pred.", comparison="split_ratio".

{}

Returns:

Name Type Description
fig Figure

The Figure object containing the plots.

ax_main Axes

The Axes object for the main plot.

ax_comparison Axes

The Axes object for the comparison plot.

See Also

plot_comparison : Plot the comparison between two histograms.

mplhep.comp.model ¤

model(stacked_components=None, stacked_labels=None, stacked_colors=None, unstacked_components=None, unstacked_labels=None, unstacked_colors=None, xlabel=None, ylabel=None, stacked_kwargs=None, unstacked_kwargs_list=None, model_sum_kwargs=None, function_range=None, model_uncertainty=True, model_uncertainty_label='Model stat. unc.', fig=None, ax=None)

Plot model made of a collection of histograms.

Parameters:

Name Type Description Default
stacked_components list of histogram (e.g. Hist, boost_histogram, np.histogram, TH1)

The list of histograms to be stacked composing the model. Default is None.

None
stacked_labels list of str

The labels of the model stacked components. Default is None.

None
stacked_colors list of str

The colors of the model stacked components. Default is None.

None
unstacked_components list of histogram (e.g. Hist, boost_histogram, np.histogram, TH1)

The list of histograms not to be stacked composing the model. Default is None.

None
unstacked_labels list of str

The labels of the model unstacked components. Default is None.

None
unstacked_colors list of str

The colors of the model unstacked components. Default is None.

None
xlabel str

The label for the x-axis. Default is None.

None
ylabel str

The label for the y-axis. Default is None.

None
stacked_kwargs dict

The keyword arguments used when plotting the stacked components in plot_hist() or plot_function(), one of which is called only once. Default is None.

None
unstacked_kwargs_list list of dict

The list of keyword arguments used when plotting the unstacked components in plot_hist() or plot_function(), one of which is called once for each unstacked component. Default is None.

None
model_sum_kwargs dict

The keyword arguments for the plot_hist() function for the sum of the model components. Has no effect if all the model components are stacked or if the model is one unstacked element. The special keyword "show" can be used with a boolean to specify whether to show or not the sum of the model components. Default is None. If None is provided, this is set to {"show": True, "label": "Model", "color": "navy"}.

None
function_range tuple, optional (mandatory if the model is made of functions)

The range for the x-axis if the model is made of functions.

None
model_uncertainty bool

If False, set the model uncertainties to zeros. Default is True.

True
model_uncertainty_label str

The label for the model uncertainties. Default is "Model stat. unc.".

'Model stat. unc.'
fig Figure or None

The Figure object to use for the plot. Create a new one if none is provided.

None
ax Axes or None

The Axes object to use for the plot. Create a new one if none is provided.

None

Returns:

Name Type Description
fig Figure

The Figure object containing the plot.

ax Axes

The Axes object containing the plot.

mplhep.comp.hists ¤

hists(h1, h2, xlabel=None, ylabel=None, h1_label='h1', h2_label='h2', fig=None, ax_main=None, ax_comparison=None, **comparison_kwargs)

Compare two histograms.

Parameters:

Name Type Description Default
h1 histogram(Hist, boost_histogram, histogram, TH1)

The first histogram to compare.

required
h2 histogram(Hist, boost_histogram, histogram, TH1)

The second histogram to compare.

required
xlabel str

The label for the x-axis. Default is None.

None
ylabel str

The label for the y-axis. Default is None.

None
h1_label str

The label for the first histogram. Default is "h1".

'h1'
h2_label str

The label for the second histogram. Default is "h2".

'h2'
fig Figure or None

The figure to use for the plot. If fig, ax_main and ax_comparison are None, a new figure will be created. Default is None.

None
ax_main Axes or None

The main axes for the histogram comparison. If fig, ax_main and ax_comparison are None, a new axes will be created. Default is None.

None
ax_comparison Axes or None

The axes for the comparison plot. If fig, ax_main and ax_comparison are None, a new axes will be created. Default is None.

None
**comparison_kwargs optional

Arguments to be passed to plot_comparison(), including the choice of the comparison function and the treatment of the uncertainties (see documentation of plot_comparison() for details).

{}

Returns:

Name Type Description
fig Figure

The created figure.

ax_main Axes

The main axes for the histogram comparison.

ax_comparison Axes

The axes for the comparison plot.

See Also

plot_comparison : Plot the comparison between two histograms.

Labeling¤

mplhep.label ¤

Labeling module.

This module provides functions to create and manage HEP labels for plots.

mplhep.label.add_text ¤

add_text(text: str, loc: str | None = None, x: float | str | None = None, y: float | str | None = None, pad: float | None = None, xpad: float | None = None, ypad: float | None = None, fontsize: float | None = None, white_background: bool = False, text_class: type[Text] = mtext.Text, ax: Axes | None = None, **kwargs: Any) -> mtext.Text

Add text to an axis with flexible positioning options.

Parameters:

Name Type Description Default
text str

The text to add to the axes.

required
loc str | None

Location shortcut similar to plt.legend(). Can be:

  • Inside axes: "upper left", "upper right", "lower left", "lower right"
  • Outside axes: "over left", "over right", "under left", "under right"
  • Alternative spellings: "top left", "top right", "bottom left", "bottom right"

If provided, overrides x and y parameters.

None
x float | str | None

Horizontal position of the text in normalized axes coordinates (0-1). String aliases: "left", "right", "left_in", "right_in", "right_out". Ignored if loc is provided.

None
y float | str | None

Vertical position of the text in normalized axes coordinates (0-1). String aliases: "top", "bottom", "top_in", "bottom_in", "top_out", "bottom_out". Ignored if loc is provided.

None
pad float | None

Padding percentage from edges for "in" positions, by default 5.0. Applied to the shorter dimension and scaled proportionally for the longer dimension.

None
xpad float | None

Horizontal padding percentage, overrides pad value for x-direction if provided.

None
ypad float | None

Vertical padding percentage, overrides pad value for y-direction if provided.

None
fontsize int | float | None

Font size, by default None (uses rcParams default).

None
white_background bool

Draw a white rectangle under the text, by default False.

False
text_class type[Text]

Text class to use for creating the text object, by default mtext.Text.

Text
ax Axes | None

Axes object to add text to. If None, uses current axes.

None
**kwargs Any

Additional keyword arguments passed to the text constructor. Notably 'ha' (horizontal alignment) and 'va' (vertical alignment) are set automatically based on position but can be overridden.

{}

Raises:

Type Description
ValueError

If both loc and x/y parameters are specified, or if x/y positions are not valid floats or recognized string aliases.

Returns:

Type Description
Text

The text object that was added to the axes.

mplhep.label.append_text ¤

append_text(s: str, txt_obj: Text, loc: str = 'right', pad: str | float = 'auto', ax: Axes | None = None, text_class: type[Text] = mtext.Text, _debug_x_override: float | None = None, **kwargs: Any) -> mtext.Text

Append text relative to an existing text object.

Parameters:

Name Type Description Default
s str

The text string to append.

required
txt_obj Text

The existing text object to append to.

required
loc str

Location relative to the existing text. Options are "right", "below", "above", or "left".

"right"
pad str | float

Padding between texts. If "auto", uses automatic spacing. If float, specifies padding as percentage of axes size.

"auto"
ax Axes | None

Axes object. If None, uses current axes.

None
text_class type[Text]

Text class to use for creating the new text object.

Text
**kwargs Any

Additional keyword arguments passed to the text constructor.

{}

Returns:

Type Description
Text

The appended text object.

mplhep.label.exp_text ¤

exp_text(exp: str = '', text: str = '', supp: str | None = None, lumi: str | None = None, loc: int | None = None, *, ax: Axes | None = None, fontsize: float | str | tuple[float | str, float | str, float | str, float | str] | None = None, fontweight: tuple[str, str, str, str] = ('bold', 'normal', 'normal', 'normal'), fontstyle: tuple[str, str, str, str] = ('normal', 'italic', 'normal', 'normal'), **kwargs: Any) -> tuple[mtext.Text, mtext.Text | None, mtext.Text | None, mtext.Text | None]

Add typical LHC experiment primary label to the axes.

Parameters:

Name Type Description Default
exp str

Experiment name, by default "".

''
text str

Secondary experiment label, typically not-bold and smaller font-size. For example "Simulation" or "Preliminary", by default "".

''
supp str | None

Supplementary text to add (e.g., "Private Work"), by default None.

None
lumi str

Luminosity information text, by default None.

None
loc int | None

Label position: - 0 : Above axes, left aligned - 1 : Top left corner - 2 : Top left corner, multiline - 3 : Split EXP above axes, rest of label in top left corner - 4 : ATLAS-style (top left corner with luminosity below) By default None (uses 0).

None
ax Axes

Axes object (if None, last one is fetched), by default None.

None
fontsize int | float | str | tuple[float | str, float | str, float | str, float | str]

Font size specification. Can be: - None: Uses rcParams default with relative scaling (exp=1.3x, text=1x, lumi=0.77x, supp=0.77x) - float: Base size with relative scaling applied - str: Matplotlib size string ("small", "large", etc.) with relative scaling applied - tuple: (exp_size, text_size, lumi_size, supp_size) for explicit control Each element can be float or matplotlib size string

None
fontweight tuple[str, str, str, str]

Tuple of fontweights for (exp, text, lumi, supp), by default ("bold", "normal", "normal", "normal").

('bold', 'normal', 'normal', 'normal')
fontstyle tuple[str, str, str, str]

Tuple of fontstyles for (exp, text, lumi, supp), by default ("normal", "italic", "normal", "normal").

('normal', 'italic', 'normal', 'normal')
**kwargs Any

Additional keyword arguments passed to text functions.

{}

Returns:

Type Description
tuple[Text, Text | None, Text | None, Text | None]

Tuple of text objects: (exp_label, secondary_text, luminosity_text, supplementary_text). Elements are None if not created.

mplhep.label.exp_label ¤

exp_label(*, exp: str = '', text: str = '', supp: str | None = None, loc: int | None = None, data: bool = False, year: str | float | None = None, lumi: str | float | None = None, lumi_format: str = '{0}', com: str | float | None = None, llabel: str | None = None, rlabel: str | None = None, fontsize: float | str | tuple[float | str, float | str, float | str, float | str] | None = None, fontweight: tuple[str, str, str, str] = ('bold', 'normal', 'normal', 'normal'), fontstyle: tuple[str, str, str, str] = ('normal', 'italic', 'normal', 'normal'), label: str | None = None, pub: Any = None, ax: Axes | None = None, **kwargs: Any) -> tuple[mtext.Text, mtext.Text | None, mtext.Text | None, mtext.Text | None]

A convenience wrapper for adding experiment labels with luminosity information.

This function combines experiment text and luminosity information in a single call, providing common labeling layouts for LHC experiment plots.

Parameters:

Name Type Description Default
exp str

Experiment name (e.g., "CMS", "ATLAS"), by default "".

''
text str

Secondary text to append after experiment name, typically "Preliminary", "Supplementary", "Private Work", or "Work in Progress", by default "".

''
supp str | None

Supplementary text to add below main label, by default None.

None
loc int | None

Label position layout: - 0 : Above axes, left aligned - 1 : Top left corner, single line - 2 : Top left corner, multiline - 3 : Split - experiment above axes, secondary text in top left corner - 4 : ATLAS-style - top left corner with luminosity below By default None (uses 0).

None
data bool

If False, prepends "Simulation" to the label text. Default False.

False
year str | float | None

Year when data was collected, by default None.

None
lumi str | float | None

Integrated luminosity value in fb⁻¹, by default None.

None
lumi_format str

Format string for luminosity display, by default "{0}". Example: "{0:.1f}" for one decimal place.

'{0}'
com str | float | None

Center-of-mass energy in TeV, by default None (uses 13). Common values: 7, 8, 13, 13.6, 14.

None
llabel str | None

Manual override for left-hand label text. Overrides "data" and "text" parameters.

None
rlabel str | None

Manual override for right-hand label text. Overrides "year", "lumi", "com" parameters.

None
fontsize int | float | str | tuple[float | str, float | str, float | str, float | str] | None

Font size specification: - None: Uses rcParams default with relative scaling - float/int: Base size with relative scaling applied - str: Matplotlib size string ("small", "large", etc.) with relative scaling - tuple: (exp_size, text_size, lumi_size, supp_size) for explicit control

None
fontweight tuple[str, str, str, str]

Font weights for (exp, text, lumi, supp) elements, by default ("bold", "normal", "normal", "normal").

('bold', 'normal', 'normal', 'normal')
fontstyle tuple[str, str, str, str]

Font styles for (exp, text, lumi, supp) elements, by default ("normal", "italic", "normal", "normal").

('normal', 'italic', 'normal', 'normal')
ax Axes | None

Axes object to add labels to. If None, uses current axes.

None
**kwargs Any

Additional keyword arguments passed to text functions.

{}

Returns:

Type Description
tuple[Text, Text | None, Text | None, Text | None]

Tuple of text objects: (exp_label, secondary_text, luminosity_text, supplementary_text). Elements are None if not created.

mplhep.label.savelabels ¤

savelabels(fname: str = '', ax: Axes | None = None, labels: list[tuple[str, str]] | list[str] | None = None, **kwargs: Any) -> None

Save multiple copies of a figure with different label variations.

This function automatically generates multiple versions of a plot with different experiment label text variations, useful for creating preliminary and final versions of plots.

Parameters:

Name Type Description Default
fname str

Primary filename to be passed to plt.savefig. Can include path and extension.

''
ax Axes | None

Axes object containing the labels to modify. If None, uses current axes.

None
labels list[tuple[str, str]] | list[str] | None

Label variations to create. Can be:

  • None: Uses default variations [("", ""), ("Preliminary", "pas"), ("Supplementary", "supp"), ("Work in Progress", "wip")]
  • List of strings: Creates filename suffixes automatically
  • List of tuples: (label_text, filename_suffix) pairs

If filename suffix contains "." it's treated as absolute filename. If current label contains "Simulation", it will be preserved.

None
**kwargs Any

Additional keyword arguments passed to plt.savefig.

{}

mplhep.label.save_variations ¤

save_variations(fig: Figure, name: str, text_list: list[str] | None = None, exp: str | None = None) -> None

Lite savelabels

Parameters:

Name Type Description Default
fig Figure

Figure object to save variations of.

required
name str

Savename to pass to plt.savefig().

required
text_list list[str] | None

Variations of ExpText text object to cycle through, by default None.

None
exp str | None

Change experiment name label, by default None.

None

Experiment styling¤

mplhep.style ¤

Styling module.

This module provides matplotlib stylesheets for various HEP experiments.

mplhep.style.use ¤

use(styles=None)

Set the experiment specific plotting style

Example:

>>> import mplhep as mh
>>> mh.style.use("ATLAS")
>>> mh.style.use(mh.style.CMS)

Parameters:

Name Type Description Default
styles str or style or dict or None

The experiment style. Will understand a dictionary of rcParams, a mplhep style or its string alias. Pass None to reset to mpl defaults.

None

mplhep.atlas ¤

mplhep.atlas.label ¤

label(text=None, **kwargs)

mplhep.atlas.text ¤

text(text='', **kwargs)

mplhep.cms ¤

mplhep.cms.label ¤

label(text=None, label=None, **kwargs)

mplhep.cms.text ¤

text(text='', **kwargs)

mplhep.lhcb ¤

LHCb-like plot styles

All of these styles resemble the LHCb plotting style; however it is an approximation and not an official style. The style LHCb should improve over time by inputs and may be changed in the future in favor of a style that resembles morethe actual LHCb style.

To use a specific style, use LHCb1, LHCb2 etc. as they won't change in the future.

Notes on LHCb2 style:

An updated version of LHCb that includes minor ticks by default on and on all axes as well as improved legends and larger minus sign (by using unicode).

Contributed and adjusted by Jonas Eschle [email protected] based on the works of Kevin Dungs, Tim Head, Thomas Schietinger, Andrew Powell, Chris Parkes, Elena Graverini and Niels Tuning

mplhep.lhcb.label ¤

label(text=None, label=None, **kwargs)

mplhep.lhcb.text ¤

text(text='', **kwargs)

mplhep.alice ¤

mplhep.alice.label ¤

label(text=None, label=None, **kwargs)

mplhep.alice.text ¤

text(text='', **kwargs)

mplhep.dune ¤

mplhep.dune.label ¤

label(text=None, label=None, **kwargs)

Add DUNE experiment label to a plot.

mplhep.dune.text ¤

text(text='', **kwargs)

Add DUNE experiment text to a plot.

Utilities¤

mplhep.utils ¤

mplhep.utils.merge_legend_handles_labels ¤

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

mplhep.utils.set_fitting_ylabel_fontsize ¤

set_fitting_ylabel_fontsize(ax: Axes) -> float

Get the suitable font size for a ylabel text that fits within the plot's y-axis limits.

Parameters:

Name Type Description Default
ax Axes

The matplotlib subplot to adjust the ylabel font size for.

required

Returns:

Type Description
float

The adjusted font size for the ylabel text.

mplhep.utils.yscale_legend ¤

yscale_legend(ax: Axes | None = None, otol: float = 0, soft_fail: bool = False, N: int = 3) -> mpl.axes.Axes

Automatically scale y-axis up to fit in legend().

Parameters:

Name Type Description Default
ax Axes

Axes object (if None, last one is fetched or one is created)

None
otol float

Tolerance for overlap, default 0. Set otol > 0 for less strict scaling.

0
soft_fail bool

Set soft_fail=True to return even if it could not fit the legend.

False
N int

Maximum number of scaling iterations, default 10.

3

Returns:

Name Type Description
ax Axes

mplhep.utils.yscale_anchored_text ¤

yscale_anchored_text(ax: Axes | None = None, otol: float = 0, soft_fail: bool = False, N: int = 3) -> mpl.axes.Axes

Automatically scale y-axis up to fit AnchoredText

Parameters:

Name Type Description Default
ax Axes

Axes object (if None, last one is fetched or one is created)

None
otol float

Tolerance for overlap, default 0. Set otol > 0 for less strict scaling.

0
soft_fail bool

Set soft_fail=True to return even if it could not fit the legend.

False
N int

Maximum number of scaling iterations, default 10.

3

Returns:

Name Type Description
ax Axes

mplhep.utils.set_ylow ¤

set_ylow(ax: Axes | None = None, ylow: float | None = None) -> mpl.axes.Axes

Set lower y limit to 0 or a specific value if not data/errors go lower.

Parameters:

Name Type Description Default
ax Axes

Axes object (if None, last one is fetched or one is created)

None
ylow float

Set lower y limit to a specific value.

None

Returns:

Name Type Description
ax Axes

mplhep.utils.mpl_magic ¤

mpl_magic(ax=None, ylow: float | None = None, otol=1, soft_fail=False, N=2)

Consolidate all ex-post style adjustments: ylow yscale_legend yscale_anchored_text

Parameters:

Name Type Description Default
ax Axes

Axes object (if None, last one is fetched or one is created)

None
ylow float

Set lower y limit to a specific value for ylow function

None
otol float

Tolerance for overlap for yscale_legend, default 0

1
soft_fail bool

Set to True to return even if legend could not fit in 10 iterations

False
N int

Maximum number of scaling iterations for yscale functions, default 10

2

Returns:

Name Type Description
ax Axes

mplhep.utils.rescale_to_axessize ¤

rescale_to_axessize(ax, w, h)

Adjust figure size to axes size in inches Parameters: w, h: width, height in inches

mplhep.utils.box_aspect ¤

box_aspect(ax, aspect=1)

Adjust figure size to axes size in inches Parameters: aspect: float, optional aspect ratio

mplhep.utils.make_square_add_cbar ¤

make_square_add_cbar(ax, size=0.4, pad=0.1)

Make input axes square and return an appended axes to the right for a colorbar. Both axes resize together to fit figure automatically. Works with tight_layout().

mplhep.utils.append_axes ¤

append_axes(ax, size=0.1, pad=0.1, position='right', extend=False)

Append a side ax to the current figure and return it. Figure is automatically extended along the direction of the added axes to accommodate it. Unfortunately can not be reliably chained.

Parameters:

Name Type Description Default
ax Axes

The axes to append to

required
size float or str

Size of the appended axes. If str ending with '%', interpreted as percentage of parent axes size.

0.1
pad float or str

Padding between axes. If str ending with '%', interpreted as percentage of parent axes size.

0.1
position str

Position of appended axes ('right', 'left', 'top', 'bottom')

'right'
extend bool

Whether to extend the figure size to accommodate the new axes

False

Returns:

Type Description
Axes

The appended axes object

mplhep.utils.sort_legend ¤

sort_legend(ax, order=None)

ax : axes with legend labels in it order : Ordered dict with renames or array with order