Skip to content

Commit

Permalink
correct ax.legend() order for stack hists
Browse files Browse the repository at this point in the history
  • Loading branch information
0ctagon committed Oct 15, 2024
1 parent 906d9a2 commit bf7f7af
Show file tree
Hide file tree
Showing 2 changed files with 18 additions and 1 deletion.
15 changes: 15 additions & 0 deletions src/mplhep/plot.py
Original file line number Diff line number Diff line change
Expand Up @@ -2,6 +2,7 @@

import collections.abc
import inspect
import itertools
import logging
from collections import OrderedDict
from typing import TYPE_CHECKING, Any, NamedTuple, Union
Expand Down Expand Up @@ -378,6 +379,20 @@ def iterable_not_string(arg):
_chunked_kwargs = [_chunked_kwargs[ix] for ix in order]
_labels = [_labels[ix] for ix in order]

elif stack:
# Sort from top to bottom so ax.legend() works as expected
order = np.argsort(label)[::-1]
plottables = [plottables[ix] for ix in order]
_chunked_kwargs = [_chunked_kwargs[ix] for ix in order]
_labels = [_labels[ix] for ix in order]
if "color" not in kwargs:
# Inverse default color cycle
_colors = itertools.cycle(
plt.rcParams["axes.prop_cycle"][len(plottables) - 1 :: -1]
)
for i in range(len(plottables)):
_chunked_kwargs[i].update(next(_colors))

# ############################
# # Stacking, norming, density
if density is True and binwnorm is not None:
Expand Down
4 changes: 3 additions & 1 deletion src/mplhep/utils.py
Original file line number Diff line number Diff line change
Expand Up @@ -294,6 +294,8 @@ def to_errorbar(self):


def stack(*plottables):
# Sort from top to bottom so ax.legend() works as expected
plottables = plottables[::-1]
baseline = np.nan_to_num(copy.deepcopy(plottables[0].values), 0)
for i in range(1, len(plottables)):
_mask = np.isnan(plottables[i].values)
Expand All @@ -303,7 +305,7 @@ def stack(*plottables):
baseline += np.nan_to_num(plottables[i].values, 0)
plottables[i].values = np.nansum([plottables[i].values, _baseline], axis=0)
plottables[i].values[_mask] = np.nan
return plottables
return plottables[::-1]


def align_marker(
Expand Down

0 comments on commit bf7f7af

Please sign in to comment.