Shamrock 2025.10.0
Astrophysical Code
Loading...
Searching...
No Matches
legend.py
1"""
2Legend helpers for plots with a family of curves colored via a colormap
3sweep (e.g. ``cmap(i / N)``), where a single gradient-swatch legend entry
4is preferable to one label per curve.
5"""
6
7__all__ = []
8
9try:
10 from matplotlib.legend_handler import HandlerBase
11 from matplotlib.lines import Line2D
12
13 _HAS_MATPLOTLIB = True
14except ImportError:
15 _HAS_MATPLOTLIB = False
16
17if _HAS_MATPLOTLIB:
18 __all__ = ["HandlerColormapLine", "add_cmap_legend_entry"]
19
20 class HandlerColormapLine(HandlerBase):
21 """Legend handler that draws a horizontal colormap gradient swatch."""
22
23 def __init__(self, cmap, num_stripes=8):
24 self.cmap = cmap
25 self.num_stripes = num_stripes
26 super().__init__()
27
28 def create_artists(
29 self, legend, orig_handle, xdescent, ydescent, width, height, fontsize, trans
30 ):
31 y_center = height / 2 - ydescent
32 stripe_lw = height * 0.6
33 stripes = []
34 for i in range(self.num_stripes):
35 s = Line2D(
36 [
37 xdescent + i * width / self.num_stripes,
38 xdescent + (i + 1) * width / self.num_stripes,
39 ],
40 [y_center, y_center],
41 color=self.cmap(i / (self.num_stripes - 1)),
42 lw=stripe_lw,
43 solid_capstyle="butt",
44 transform=trans,
45 )
46 stripes.append(s)
47 return stripes
48
50 ax, cmap, label, num_stripes=8, extra_handles=None, extra_labels=None, **legend_kwargs
51 ):
52 """Add a colormap-gradient swatch entry to ax's legend, optionally
53 combined with normal labeled handles (extra_handles/extra_labels)."""
54 proxy = Line2D([0], [0], color="none")
55 handles = [proxy]
56 labels = [label]
57 if extra_handles:
58 handles = extra_handles + handles
59 labels = extra_labels + labels
60
61 handler_map = {proxy: HandlerColormapLine(cmap, num_stripes=num_stripes)}
62 legend_kwargs.setdefault("handlelength", 3)
63 legend_kwargs.setdefault("handleheight", 1)
64 legend_kwargs.setdefault("fontsize", 9)
65
66 return ax.legend(handles, labels, handler_map=handler_map, **legend_kwargs)
add_cmap_legend_entry(ax, cmap, label, num_stripes=8, extra_handles=None, extra_labels=None, **legend_kwargs)
Definition legend.py:51