ComplexHeatmap-py 0.1.0__py3-none-any.whl

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (52) hide show
  1. ComplexHeatmap.py +7 -0
  2. complexheatmap/__init__.py +221 -0
  3. complexheatmap/_base.py +56 -0
  4. complexheatmap/_options.py +165 -0
  5. complexheatmap/anno_funcs.py +2781 -0
  6. complexheatmap/annotations.py +1611 -0
  7. complexheatmap/colors.py +848 -0
  8. complexheatmap/data/dmr_summary/cgi_anno.csv +9 -0
  9. complexheatmap/data/dmr_summary/dist_tss.csv +9 -0
  10. complexheatmap/data/dmr_summary/gene_anno.csv +9 -0
  11. complexheatmap/data/dmr_summary/label.csv +9 -0
  12. complexheatmap/data/dmr_summary/mat_enrich_gf.csv +9 -0
  13. complexheatmap/data/dmr_summary/mat_enrich_st.csv +9 -0
  14. complexheatmap/data/dmr_summary/mat_pct_st.csv +9 -0
  15. complexheatmap/data/dmr_summary/mean_meth.csv +9 -0
  16. complexheatmap/data/dmr_summary/n_corr.csv +9 -0
  17. complexheatmap/data/dmr_summary/n_gr.csv +9 -0
  18. complexheatmap/data/gene_expression.csv +156 -0
  19. complexheatmap/data/gr.csv +2416 -0
  20. complexheatmap/data/measles.csv +60 -0
  21. complexheatmap/data/meth/enhancer.csv +1001 -0
  22. complexheatmap/data/meth/expr.csv +1001 -0
  23. complexheatmap/data/meth/meth.csv +1001 -0
  24. complexheatmap/data/meth/row_meta.csv +1001 -0
  25. complexheatmap/data/rand_mat.csv +19 -0
  26. complexheatmap/data/random_meth_expr_data/anno.csv +21 -0
  27. complexheatmap/data/random_meth_expr_data/anno_states.csv +1001 -0
  28. complexheatmap/data/random_meth_expr_data/mat_expr.csv +1001 -0
  29. complexheatmap/data/random_meth_expr_data/mat_meth.csv +1001 -0
  30. complexheatmap/data/random_meth_expr_data/row_meta.csv +1001 -0
  31. complexheatmap/data/sample_order.txt +172 -0
  32. complexheatmap/data/tcga_lung_adenocarcinoma.csv +27 -0
  33. complexheatmap/decorate.py +159 -0
  34. complexheatmap/dendrogram.py +937 -0
  35. complexheatmap/density.py +276 -0
  36. complexheatmap/genomic.py +348 -0
  37. complexheatmap/grid.py +1580 -0
  38. complexheatmap/heatmap.py +2244 -0
  39. complexheatmap/heatmap_list.py +1569 -0
  40. complexheatmap/legend.py +992 -0
  41. complexheatmap/oncoprint.py +488 -0
  42. complexheatmap/text.py +655 -0
  43. complexheatmap/three_d.py +188 -0
  44. complexheatmap/translate.py +338 -0
  45. complexheatmap/units.py +718 -0
  46. complexheatmap/upset.py +886 -0
  47. complexheatmap/utils.py +183 -0
  48. complexheatmap_py-0.1.0.dist-info/METADATA +96 -0
  49. complexheatmap_py-0.1.0.dist-info/RECORD +52 -0
  50. complexheatmap_py-0.1.0.dist-info/WHEEL +5 -0
  51. complexheatmap_py-0.1.0.dist-info/licenses/LICENSE +24 -0
  52. complexheatmap_py-0.1.0.dist-info/top_level.txt +2 -0
@@ -0,0 +1,992 @@
1
+ """Legend, Legends, and packLegend implementation."""
2
+
3
+ from __future__ import annotations
4
+
5
+ import copy
6
+ import math
7
+ from typing import Any, Callable, Sequence
8
+
9
+ import numpy as np
10
+
11
+ from .colors import grid_pretty, pretty_breaks, to_hex_rgba
12
+ from .grid import (
13
+ GTree,
14
+ Grob,
15
+ Viewport,
16
+ grid_newpage,
17
+ grid_rect,
18
+ grid_segments,
19
+ grid_text,
20
+ pointsGrob,
21
+ popViewport,
22
+ pushViewport,
23
+ rectGrob,
24
+ segmentsGrob,
25
+ textGrob,
26
+ grid_grabExpr,
27
+ )
28
+ from .text import smartAlign
29
+ from .units import (
30
+ Unit,
31
+ as_unit,
32
+ check_gp,
33
+ convertHeight,
34
+ convertWidth,
35
+ gpar,
36
+ recycle_gp,
37
+ subset_gp,
38
+ unit,
39
+ unit_c,
40
+ )
41
+
42
+
43
+ def _is_diff_equal(x: Sequence[float]) -> bool:
44
+ arr = np.asarray(x, dtype=float)
45
+ if len(arr) <= 2:
46
+ return True
47
+ diffs = np.diff(arr)
48
+ mean_d = float(np.mean(diffs))
49
+ if abs(mean_d) < 1e-12:
50
+ return True
51
+ return bool(np.all(np.abs(np.diff(diffs)) / abs(mean_d) < 1e-4))
52
+
53
+
54
+ def _valid_just(just: Any) -> tuple[float, float]:
55
+ from .grid import parse_just
56
+ return parse_just(just)
57
+
58
+
59
+ def _edit_vp_in_legend_grob(gtree: GTree, x: Any = None, y: Any = None, valid_just: Any = None) -> GTree:
60
+ gt = copy.copy(gtree)
61
+ if gt.vp is None:
62
+ gt.vp = Viewport(x=x, y=y, just=valid_just or "centre")
63
+ else:
64
+ vp = copy.copy(gt.vp)
65
+ if x is not None:
66
+ vp.x = as_unit(x, "npc")
67
+ if y is not None:
68
+ vp.y = as_unit(y, "npc")
69
+ if valid_just is not None:
70
+ vp.just = valid_just
71
+ gt.vp = vp
72
+ return gt
73
+
74
+
75
+ class Legends:
76
+ """Container for one or more packed Legend grobs."""
77
+
78
+ def __init__(
79
+ self,
80
+ grob: GTree,
81
+ type: str = "single_legend",
82
+ name: str | None = None,
83
+ n: int = 1,
84
+ multiple: int = 1,
85
+ direction: str = "vertical",
86
+ ) -> None:
87
+ self.grob = grob
88
+ self.type = type
89
+ self.name = name
90
+ self.n = int(n)
91
+ self.multiple = int(multiple)
92
+ self.direction = direction
93
+
94
+ @property
95
+ def width(self) -> Unit:
96
+ return unit(self.grob.width_mm(), "mm")
97
+
98
+ @property
99
+ def height(self) -> Unit:
100
+ return unit(self.grob.height_mm(), "mm")
101
+
102
+ def draw(
103
+ self,
104
+ x: Any = None,
105
+ y: Any = None,
106
+ just: Any = "centre",
107
+ test: bool | str = False,
108
+ ) -> None:
109
+ ux = unit(0.5, "npc") if x is None else as_unit(x, "npc")
110
+ uy = unit(0.5, "npc") if y is None else as_unit(y, "npc")
111
+ lgd_grob = _edit_vp_in_legend_grob(self.grob, x=ux, y=uy, valid_just=_valid_just(just))
112
+ if isinstance(test, str):
113
+ is_test = True
114
+ test_label = test
115
+ else:
116
+ is_test = bool(test)
117
+ test_label = ""
118
+ if is_test:
119
+ grid_newpage()
120
+ lgd_grob.draw()
121
+ if is_test and test_label:
122
+ grid_text(test_label, x=0.5, y=unit(1, "npc") - unit(1, "cm"))
123
+
124
+ def _repr_png_(self) -> bytes:
125
+ import io
126
+ import matplotlib.pyplot as plt
127
+ w_mm = max(20.0, self.grob.width_mm() + 10.0)
128
+ h_mm = max(20.0, self.grob.height_mm() + 10.0)
129
+ dev = grid_newpage(width_in=w_mm / 25.4, height_in=h_mm / 25.4)
130
+ self.draw()
131
+ buf = io.BytesIO()
132
+ dev.fig.savefig(buf, format="png", dpi=120)
133
+ plt.close(dev.fig)
134
+ return buf.getvalue()
135
+
136
+ def __repr__(self) -> str:
137
+ if self.type == "single_legend":
138
+ return "A single legend"
139
+ if self.type == "single_legend_no_title":
140
+ return "A single legend without title"
141
+ return f"A pack of {self.n} legends"
142
+
143
+
144
+ def _points_grobs_for_legend(x: Unit, y: Unit, pch: Any, gp: Any, size: Unit, width: Unit, height: Unit) -> list[Grob]:
145
+ n = len(x)
146
+ pch_list = [pch] * n if isinstance(pch, (int, np.integer, str)) or pch is None else list(pch)
147
+ if any(isinstance(p, (int, np.integer)) and int(p) in (26, 27, 28, 29, 30, 31) for p in pch_list):
148
+ out: list[Grob] = []
149
+ for i in range(n):
150
+ p = int(pch_list[i]) if isinstance(pch_list[i], (int, np.integer)) else pch_list[i]
151
+ gpi = subset_gp(gp, i)
152
+ if p == 26:
153
+ out.append(segmentsGrob(x[i] - width * 0.4, y[i] - height[i] * 0.4, x[i] + width * 0.4, y[i] + height[i] * 0.4, gp=gpi))
154
+ elif p == 27:
155
+ out.append(segmentsGrob(x[i] + width * 0.4, y[i] - height[i] * 0.4, x[i] - width * 0.4, y[i] + height[i] * 0.4, gp=gpi))
156
+ elif p == 28:
157
+ out.append(
158
+ segmentsGrob(
159
+ unit_c(x[i] - width * 0.4, x[i] + width * 0.4),
160
+ unit_c(y[i] - height[i] * 0.4, y[i] - height[i] * 0.4),
161
+ unit_c(x[i] + width * 0.4, x[i] - width * 0.4),
162
+ unit_c(y[i] + height[i] * 0.4, y[i] + height[i] * 0.4),
163
+ gp=gpi,
164
+ )
165
+ )
166
+ elif p in (29, 30, 31):
167
+ raise ValueError("pch in 29..31 is not supported in Legend().")
168
+ else:
169
+ out.append(pointsGrob(x[i], y[i], pch=p, size=size[i], gp=gpi, default_units="mm"))
170
+ return out
171
+ return [pointsGrob(x, y, pch=pch_list, size=size, gp=gp, default_units="mm")]
172
+
173
+
174
+ def _discrete_legend_body(
175
+ at: Sequence[Any],
176
+ labels: Sequence[Any],
177
+ nrow: int | None = None,
178
+ ncol: int = 1,
179
+ by_row: bool = False,
180
+ grid_height: Unit = unit(4, "mm"),
181
+ grid_width: Unit = unit(4, "mm"),
182
+ column_gap: Unit = unit(2, "mm"),
183
+ row_gap: Unit = unit(0, "mm"),
184
+ labels_gp: Any = None,
185
+ border: Any = "white",
186
+ background: str = "#EEEEEE",
187
+ type: str | Sequence[str] = "grid",
188
+ graphics: Sequence[Callable] | dict[Any, Callable] | None = None,
189
+ legend_gp: Any = None,
190
+ pch: Any = 16,
191
+ size: Any = unit(2, "mm"),
192
+ ) -> GTree:
193
+ lbl_list = [str(v) for v in labels]
194
+ n_labels = len(lbl_list)
195
+ if n_labels == 0:
196
+ return GTree(children=[], cl="legend_body", width=unit(0.0, "mm"), height=unit(0.0, "mm"))
197
+
198
+ if nrow is None:
199
+ nrow = int(math.ceil(n_labels / max(1, ncol)))
200
+ else:
201
+ ncol = int(math.ceil(n_labels / max(1, nrow)))
202
+ if len(at) == 1:
203
+ nrow = 1
204
+ ncol = 1
205
+ ncol = min(ncol, n_labels)
206
+
207
+ # Build grid matrix of indices (None where empty)
208
+ idx_grid: list[list[int | None]] = [[None] * ncol for _ in range(nrow)]
209
+ if by_row:
210
+ for idx in range(n_labels):
211
+ r, c = divmod(idx, ncol)
212
+ idx_grid[r][c] = idx
213
+ else:
214
+ for idx in range(n_labels):
215
+ c, r = divmod(idx, nrow)
216
+ idx_grid[r][c] = idx
217
+
218
+ # Trim completely empty columns or rows
219
+ non_empty_cols = [c for c in range(ncol) if any(idx_grid[r][c] is not None for r in range(nrow))]
220
+ ncol = len(non_empty_cols)
221
+ idx_grid = [[idx_grid[r][c] for c in non_empty_cols] for r in range(nrow)]
222
+ non_empty_rows = [r for r in range(nrow) if any(idx_grid[r][c] is not None for c in range(ncol))]
223
+ nrow = len(non_empty_rows)
224
+ idx_grid = [idx_grid[r] for r in non_empty_rows]
225
+
226
+ gh_mm_arr = np.broadcast_to(as_unit(grid_height, "mm").to_mm("y"), (nrow,)).copy()
227
+ gw_mm_arr = np.broadcast_to(as_unit(grid_width, "mm").to_mm("x"), (ncol,)).copy()
228
+ col_gap_mm = convertWidth(column_gap, "mm", valueOnly=True)
229
+ row_gap_mm = convertHeight(row_gap, "mm", valueOnly=True)
230
+ lbl_pad_left_mm = 1.0
231
+
232
+ lgp_labels = check_gp(labels_gp or gpar(fontsize=10))
233
+ col_max_w = np.zeros(ncol, dtype=float)
234
+ for c in range(ncol):
235
+ for r in range(nrow):
236
+ idx = idx_grid[r][c]
237
+ if idx is not None:
238
+ col_max_w[c] = max(col_max_w[c], textGrob(lbl_list[idx], gp=lgp_labels).width_mm())
239
+
240
+ row_h_no_gap = np.zeros(nrow, dtype=float)
241
+ pt4_mm = convertHeight(unit(4, "points"), "mm", valueOnly=True)
242
+ for r in range(nrow):
243
+ th = 0.0
244
+ for c in range(ncol):
245
+ idx = idx_grid[r][c]
246
+ if idx is not None:
247
+ th = max(th, textGrob(lbl_list[idx], gp=lgp_labels).height_mm())
248
+ row_h_no_gap[r] = max(th + pt4_mm, gh_mm_arr[r])
249
+
250
+ row_h = row_h_no_gap.copy()
251
+ if nrow > 1:
252
+ row_h[:-1] += row_gap_mm
253
+
254
+ tot_w = float(np.sum(gw_mm_arr) + lbl_pad_left_mm * ncol + np.sum(col_max_w) + col_gap_mm * max(0, ncol - 1))
255
+ tot_h = float(np.sum(row_h))
256
+
257
+ lgp_rec = recycle_gp(legend_gp or gpar(), n_labels)
258
+ types = [type] if isinstance(type, str) else list(type)
259
+
260
+ if graphics is not None:
261
+ if isinstance(graphics, dict):
262
+ g_list = [graphics[k] for k in at]
263
+ else:
264
+ g_list = list(graphics)
265
+ if len(g_list) != n_labels:
266
+ raise ValueError("Length of `graphics` must match number of labels.")
267
+ else:
268
+ g_list = None
269
+
270
+ children: list[Grob] = []
271
+ prev_x = 0.0
272
+ for c in range(ncol):
273
+ col_indices = [idx_grid[r][c] for r in range(nrow) if idx_grid[r][c] is not None]
274
+ ni = len(col_indices)
275
+ # y centers from top
276
+ y_top = np.array([0.0] + list(np.cumsum(row_h[: ni - 1])), dtype=float)
277
+ y_bot_from_top = tot_h - y_top
278
+ y_center = y_bot_from_top - 0.5 * row_h_no_gap[:ni]
279
+
280
+ lx = prev_x + gw_mm_arr[c] + lbl_pad_left_mm
281
+ children.append(
282
+ textGrob(
283
+ [lbl_list[i] for i in col_indices],
284
+ x=np.full(ni, lx),
285
+ y=y_center,
286
+ just="left",
287
+ gp=lgp_labels,
288
+ default_units="mm",
289
+ )
290
+ )
291
+
292
+ sgd = subset_gp(lgp_rec, col_indices)
293
+ sgd2 = gpar()
294
+ if "grid" in types:
295
+ sgd2["fill"] = sgd.get("fill", [to_hex_rgba(background)] * ni)
296
+ else:
297
+ sgd2["fill"] = background
298
+ eff_border = "asis" if (legend_gp and legend_gp.get("col") == "asis") else border
299
+ if eff_border == "asis":
300
+ sgd2["col"] = sgd2["fill"]
301
+ else:
302
+ sgd2["col"] = eff_border
303
+
304
+ gx = np.full(ni, prev_x)
305
+ if g_list is None:
306
+ children.append(
307
+ rectGrob(
308
+ x=gx,
309
+ y=y_center,
310
+ width=np.full(ni, gw_mm_arr[c]),
311
+ height=row_h_no_gap[:ni],
312
+ just="left",
313
+ gp=sgd2,
314
+ default_units="mm",
315
+ )
316
+ )
317
+ if any(t in ("points", "p") for t in types):
318
+ pch_col = [pch] * ni if isinstance(pch, (int, np.integer, str)) or pch is None else [list(pch)[i] for i in col_indices]
319
+ sz_u = as_unit(size, "mm")
320
+ sz_col = unit_c(*([sz_u] * ni)) if len(sz_u) == 1 else sz_u[col_indices]
321
+ children.extend(
322
+ _points_grobs_for_legend(
323
+ x=unit(gx + gw_mm_arr[c] * 0.5, "mm"),
324
+ y=unit(y_center, "mm"),
325
+ pch=pch_col,
326
+ gp=sgd,
327
+ size=sz_col,
328
+ width=unit(gw_mm_arr[c], "mm"),
329
+ height=unit(row_h_no_gap[:ni], "mm"),
330
+ )
331
+ )
332
+ if any(t in ("lines", "l") for t in types):
333
+ children.append(
334
+ segmentsGrob(
335
+ x0=gx, y0=y_center,
336
+ x1=gx + gw_mm_arr[c], y1=y_center,
337
+ gp=sgd,
338
+ default_units="mm",
339
+ )
340
+ )
341
+ if any(t in ("boxplot", "box") for t in types):
342
+ children.append(
343
+ segmentsGrob(
344
+ x0=gx + gw_mm_arr[c] * 0.5, y0=y_center - row_h_no_gap[:ni] * 0.45,
345
+ x1=gx + gw_mm_arr[c] * 0.5, y1=y_center + row_h_no_gap[:ni] * 0.45,
346
+ gp=sgd, default_units="mm",
347
+ )
348
+ )
349
+ children.append(
350
+ rectGrob(
351
+ x=gx + gw_mm_arr[c] * 0.5, y=y_center,
352
+ width=np.full(ni, gw_mm_arr[c] * 0.9), height=row_h_no_gap[:ni] * 0.5,
353
+ gp=sgd, default_units="mm",
354
+ )
355
+ )
356
+ children.append(
357
+ segmentsGrob(
358
+ x0=gx + gw_mm_arr[c] * 0.05, y0=y_center,
359
+ x1=gx + gw_mm_arr[c] * 0.95, y1=y_center,
360
+ gp=sgd, default_units="mm",
361
+ )
362
+ )
363
+ else:
364
+ for r_k, idx in enumerate(col_indices):
365
+ fn = g_list[idx]
366
+ cell_w_mm = gw_mm_arr[c]
367
+ cell_h_mm = row_h_no_gap[r_k]
368
+ # Draw directly into cell viewport inside legend
369
+ def _make_cell_grob(fn_local, cx, cy, cw, ch):
370
+ vp_c = Viewport(x=unit(cx, "mm"), y=unit(cy, "mm"), width=unit(cw, "mm"), height=unit(ch, "mm"))
371
+ cap = grid_grabExpr(lambda: fn_local(unit(0.5, "npc"), unit(0.5, "npc"), unit(1.0, "npc"), unit(1.0, "npc")), width_in=cw / 25.4, height_in=ch / 25.4)
372
+ return GTree(children=[cap], vp=vp_c, width=unit(cw, "mm"), height=unit(ch, "mm"))
373
+ children.append(_make_cell_grob(fn, prev_x + cell_w_mm * 0.5, y_center[r_k], cell_w_mm, cell_h_mm))
374
+
375
+ prev_x += gw_mm_arr[c] + col_max_w[c] + lbl_pad_left_mm + col_gap_mm
376
+
377
+ return GTree(
378
+ children=children,
379
+ cl="legend_body",
380
+ vp=Viewport(width=unit(tot_w, "mm"), height=unit(tot_h, "mm")),
381
+ width=unit(tot_w, "mm"),
382
+ height=unit(tot_h, "mm"),
383
+ )
384
+
385
+
386
+ def _apply_break_dist(at: np.ndarray, col_fun: Callable, break_dist: Sequence[float] | float) -> tuple[np.ndarray, Callable]:
387
+ n = len(at)
388
+ bd = [float(break_dist)] * (n - 1) if np.ndim(break_dist) == 0 else [float(v) for v in break_dist]
389
+ if len(bd) != n - 1:
390
+ raise ValueError(f"Length of `break_dist` must be {n - 1}.")
391
+ y = np.concatenate([[0.0], np.cumsum(bd) / np.sum(bd)])
392
+ sorted_at = np.sort(at)
393
+
394
+ def new_col_fun(vals: Any) -> Any:
395
+ mapped = np.interp(np.asarray(vals, dtype=float), y, sorted_at)
396
+ return col_fun(mapped)
397
+
398
+ new_col_fun.breaks = y # type: ignore[attr-defined]
399
+ new_at = y if at[0] <= at[-1] else y[::-1].copy()
400
+ return new_at, new_col_fun
401
+
402
+
403
+ def _vertical_continuous_legend_body(
404
+ at: Sequence[float],
405
+ labels: Sequence[Any],
406
+ col_fun: Callable,
407
+ break_dist: Any = None,
408
+ grid_width: Unit = unit(4, "mm"),
409
+ legend_height: Unit | None = None,
410
+ tick_length: Unit = unit(0.8, "mm"),
411
+ labels_gp: Any = None,
412
+ border: Any = None,
413
+ legend_gp: Any = None,
414
+ ) -> GTree:
415
+ at_arr = np.asarray(at, dtype=float)
416
+ lbl_arr = [str(v) for v in labels]
417
+ n = len(at_arr)
418
+ if np.array_equal(np.argsort(at_arr), np.arange(n - 1, -1, -1)):
419
+ if break_dist is not None and np.ndim(break_dist) > 0:
420
+ break_dist = list(reversed(break_dist))
421
+ else:
422
+ od = np.argsort(at_arr)
423
+ if break_dist is not None and not np.array_equal(od, np.arange(n)):
424
+ raise ValueError("`at` must be sorted when `break_dist` is set.")
425
+ at_arr = at_arr[od]
426
+ lbl_arr = [lbl_arr[i] for i in od]
427
+
428
+ if break_dist is not None:
429
+ at_arr, col_fun = _apply_break_dist(at_arr, col_fun, break_dist)
430
+
431
+ lgp_labels = check_gp(labels_gp or gpar(fontsize=10))
432
+ lgp_rec = recycle_gp(lgp_labels, n)
433
+ lbl_max_w = max((textGrob(lbl_arr[i], gp=subset_gp(lgp_rec, i)).width_mm() for i in range(n)), default=0.0)
434
+ min_h = sum(textGrob(lbl_arr[i], gp=subset_gp(lgp_rec, i)).height_mm() for i in range(n)) + convertHeight(unit(6 * max(0, n - 1), "points"), "mm", valueOnly=True)
435
+
436
+ if legend_height is not None:
437
+ lh_mm = convertHeight(legend_height, "mm", valueOnly=True)
438
+ if lh_mm < min_h:
439
+ lh_mm = min_h
440
+ else:
441
+ lh_mm = max(min_h, 21.1)
442
+
443
+ gw_mm = convertWidth(grid_width, "mm", valueOnly=True)
444
+ tick_mm = convertWidth(tick_length, "mm", valueOnly=True)
445
+ at_diff_equal = _is_diff_equal(at_arr)
446
+ lbl_pad_left = 1.0 if at_diff_equal else 4.0
447
+
448
+ offset_mm = convertHeight(unit(2, "points"), "mm", valueOnly=True)
449
+ ymin, ymax = offset_mm, lh_mm - offset_mm
450
+ span = at_arr[-1] - at_arr[0]
451
+ y_mm = ((at_arr - at_arr[0]) / span) * (ymax - ymin) + ymin if abs(span) > 1e-12 else np.linspace(ymin, ymax, n)
452
+ labels_y = y_mm.copy()
453
+
454
+ if not at_diff_equal:
455
+ pt4 = convertHeight(unit(4, "points"), "mm", valueOnly=True)
456
+ lh_items = np.array([textGrob(lbl_arr[i], gp=subset_gp(lgp_rec, i)).height_mm() + pt4 for i in range(n)])
457
+ y_bot = labels_y - 0.5 * lh_items
458
+ y_top = labels_y + 0.5 * lh_items
459
+ yrng = (offset_mm - 0.5 * lh_items[0], lh_mm - offset_mm + 0.5 * lh_items[-1])
460
+ aligned = smartAlign(y_bot, y_top, yrng)
461
+ labels_y = 0.5 * (aligned[:, 0] + aligned[:, 1])
462
+
463
+ adjust_text_pos = not bool(np.all(np.abs(labels_y - y_mm) < 1e-4))
464
+ if not adjust_text_pos:
465
+ lbl_pad_left = 1.0
466
+
467
+ tot_w = gw_mm + lbl_pad_left + lbl_max_w
468
+ children: list[Grob] = [
469
+ textGrob(lbl_arr, x=np.full(n, gw_mm + lbl_pad_left), y=labels_y, just="left", gp=lgp_labels, default_units="mm")
470
+ ]
471
+
472
+ # Sample smooth gradient segments
473
+ at_grad = at_arr if at_diff_equal else np.linspace(at_arr[0], at_arr[-1], n)
474
+ pts_list = []
475
+ for i in range(len(at_grad) - 1):
476
+ m = max(10, int(round(abs(at_grad[i + 1] - at_grad[i]) / max(1e-12, abs(at_arr[-1] - at_arr[0])) * 100)))
477
+ pts_list.append(np.linspace(at_grad[i], at_grad[i + 1], m, endpoint=False))
478
+ pts_list.append(np.array([at_grad[-1]]))
479
+ at2 = np.concatenate(pts_list)
480
+ colors = [to_hex_rgba(c) for c in np.atleast_1d(col_fun(at2))]
481
+ n_c = len(colors)
482
+ step_h = (lh_mm - 2.0 * offset_mm) / n_c
483
+ y2 = np.linspace(offset_mm, lh_mm - offset_mm, n_c, endpoint=False) + 0.5 * step_h
484
+ if at_arr[0] > at_arr[-1]:
485
+ y2 = y2[::-1]
486
+ y2_all = np.concatenate([[lh_mm - 0.5 * offset_mm], y2, [0.5 * offset_mm]])
487
+ else:
488
+ y2_all = np.concatenate([[0.5 * offset_mm], y2, [lh_mm - 0.5 * offset_mm]])
489
+ hh_all = np.concatenate([[offset_mm], np.full(n_c, step_h), [offset_mm]])
490
+ cols_all = [colors[0]] + colors + [colors[-1]]
491
+
492
+ children.append(
493
+ rectGrob(
494
+ x=np.zeros(len(cols_all)),
495
+ y=y2_all,
496
+ width=np.full(len(cols_all), gw_mm),
497
+ height=hh_all,
498
+ just="left",
499
+ gp=gpar(col=cols_all, fill=cols_all),
500
+ default_units="mm",
501
+ )
502
+ )
503
+
504
+ lgp_tick = check_gp(legend_gp)
505
+ if border is None and "col" in lgp_tick:
506
+ border = lgp_tick["col"]
507
+ if "col" not in lgp_tick:
508
+ lgp_tick["col"] = "white" if border is None else border
509
+
510
+ children.append(segmentsGrob(np.zeros(n), y_mm, np.full(n, tick_mm), y_mm, gp=lgp_tick, default_units="mm"))
511
+ children.append(segmentsGrob(np.full(n, gw_mm), y_mm, np.full(n, gw_mm - tick_mm), y_mm, gp=lgp_tick, default_units="mm"))
512
+
513
+ if adjust_text_pos:
514
+ x_b0 = np.full(n, gw_mm)
515
+ x_b1 = np.full(n, gw_mm + lbl_pad_left / 3.0)
516
+ x_b2 = np.full(n, gw_mm + lbl_pad_left * 2.0 / 3.0)
517
+ x_b3 = np.full(n, gw_mm + lbl_pad_left - 0.5)
518
+ children.append(segmentsGrob(x_b0, y_mm, x_b1, y_mm, default_units="mm"))
519
+ children.append(segmentsGrob(x_b3, labels_y, x_b2, labels_y, default_units="mm"))
520
+ children.append(segmentsGrob(x_b1, y_mm, x_b2, labels_y, default_units="mm"))
521
+
522
+ if border is not None:
523
+ bg_gp = check_gp(lgp_tick)
524
+ bg_gp["fill"] = "transparent"
525
+ children.append(rectGrob(x=0.0, y=0.5 * lh_mm, width=gw_mm, height=lh_mm, just="left", gp=bg_gp, default_units="mm"))
526
+
527
+ return GTree(
528
+ children=children,
529
+ cl="legend_body",
530
+ vp=Viewport(width=unit(tot_w, "mm"), height=unit(lh_mm, "mm")),
531
+ width=unit(tot_w, "mm"),
532
+ height=unit(lh_mm, "mm"),
533
+ )
534
+
535
+
536
+ def _horizontal_continuous_legend_body(
537
+ at: Sequence[float],
538
+ labels: Sequence[Any],
539
+ col_fun: Callable,
540
+ break_dist: Any = None,
541
+ grid_height: Unit = unit(4, "mm"),
542
+ legend_width: Unit | None = None,
543
+ tick_length: Unit = unit(0.8, "mm"),
544
+ labels_gp: Any = None,
545
+ labels_rot: float = 0.0,
546
+ border: Any = None,
547
+ legend_gp: Any = None,
548
+ legend_extension: Unit = unit(0, "mm"),
549
+ ) -> GTree:
550
+ at_arr = np.asarray(at, dtype=float)
551
+ lbl_arr = [str(v) for v in labels]
552
+ n = len(at_arr)
553
+ if np.array_equal(np.argsort(at_arr), np.arange(n - 1, -1, -1)):
554
+ if break_dist is not None and np.ndim(break_dist) > 0:
555
+ break_dist = list(reversed(break_dist))
556
+ else:
557
+ od = np.argsort(at_arr)
558
+ if break_dist is not None and not np.array_equal(od, np.arange(n)):
559
+ raise ValueError("`at` must be sorted when `break_dist` is set.")
560
+ at_arr = at_arr[od]
561
+ lbl_arr = [lbl_arr[i] for i in od]
562
+
563
+ if break_dist is not None:
564
+ at_arr, col_fun = _apply_break_dist(at_arr, col_fun, break_dist)
565
+
566
+ rot = float(labels_rot) % 360.0
567
+ lgp_labels = check_gp(labels_gp or gpar(fontsize=10))
568
+ lbl_widths = np.array([textGrob(lbl_arr[i], gp=lgp_labels, rot=rot).width_mm() for i in range(n)])
569
+ lbl_max_h = max((textGrob(lbl_arr[i], gp=lgp_labels, rot=rot).height_mm() for i in range(n)), default=0.0)
570
+
571
+ min_lw = float(np.sum(lbl_widths)) + 2.1 * n
572
+ lw_mm = min_lw if legend_width is None else convertWidth(legend_width, "mm", valueOnly=True)
573
+ gh_mm = convertHeight(grid_height, "mm", valueOnly=True)
574
+ tick_mm = convertHeight(tick_length, "mm", valueOnly=True)
575
+ at_diff_equal = _is_diff_equal(at_arr)
576
+ lbl_pad_top = 1.0
577
+
578
+ offset_mm = convertWidth(unit(2, "points"), "mm", valueOnly=True)
579
+ xmin, xmax = offset_mm, lw_mm - offset_mm
580
+ span = at_arr[-1] - at_arr[0]
581
+ x_mm = ((at_arr - at_arr[0]) / span) * (xmax - xmin) + xmin if abs(span) > 1e-12 else np.linspace(xmin, xmax, n)
582
+
583
+ if rot == 0:
584
+ lbl_just = "top"
585
+ elif 0 < rot < 180:
586
+ lbl_just = "right"
587
+ else:
588
+ lbl_just = "left"
589
+
590
+ w_pad = lbl_widths + 1.0
591
+ ext_mm = max(convertWidth(legend_extension, "mm", valueOnly=True), 0.5 * w_pad[0] - offset_mm)
592
+ xrng = (-ext_mm, lw_mm - offset_mm + 0.5 * w_pad[-1])
593
+ aligned = smartAlign(x_mm - 0.5 * w_pad, x_mm + 0.5 * w_pad, xrng)
594
+ labels_x = 0.5 * (aligned[:, 0] + aligned[:, 1])
595
+
596
+ adjust_text_pos = not bool(np.all(np.abs(labels_x - x_mm) < 1e-4))
597
+ if adjust_text_pos:
598
+ lbl_pad_top = 4.0
599
+
600
+ tot_h = gh_mm + lbl_pad_top + lbl_max_h
601
+ labels_y = tot_h - gh_mm - lbl_pad_top
602
+ children: list[Grob] = [
603
+ textGrob(lbl_arr, x=labels_x, y=np.full(n, labels_y), just=lbl_just, gp=lgp_labels, rot=rot, default_units="mm")
604
+ ]
605
+
606
+ at_grad = at_arr if at_diff_equal else np.linspace(at_arr[0], at_arr[-1], n)
607
+ pts_list = []
608
+ for i in range(len(at_grad) - 1):
609
+ m = max(10, int(round(abs(at_grad[i + 1] - at_grad[i]) / max(1e-12, abs(at_arr[-1] - at_arr[0])) * 100)))
610
+ pts_list.append(np.linspace(at_grad[i], at_grad[i + 1], m, endpoint=False))
611
+ pts_list.append(np.array([at_grad[-1]]))
612
+ at2 = np.concatenate(pts_list)
613
+ colors = [to_hex_rgba(c) for c in np.atleast_1d(col_fun(at2))]
614
+ n_c = len(colors)
615
+ step_w = (lw_mm - 2.0 * offset_mm) / n_c
616
+ x2 = np.linspace(offset_mm, lw_mm - offset_mm, n_c, endpoint=False) + 0.5 * step_w
617
+ x2_all = np.concatenate([[0.5 * offset_mm], x2, [lw_mm - 0.5 * offset_mm]])
618
+ ww_all = np.concatenate([[offset_mm], np.full(n_c, step_w), [offset_mm]])
619
+ cols_all = [colors[0]] + colors + [colors[-1]]
620
+
621
+ children.append(
622
+ rectGrob(
623
+ x=x2_all,
624
+ y=np.full(len(cols_all), tot_h),
625
+ width=ww_all,
626
+ height=np.full(len(cols_all), gh_mm),
627
+ just="top",
628
+ gp=gpar(col=cols_all, fill=cols_all),
629
+ default_units="mm",
630
+ )
631
+ )
632
+
633
+ lgp_tick = check_gp(legend_gp)
634
+ if "col" not in lgp_tick:
635
+ lgp_tick["col"] = "white" if border is None else border
636
+ children.append(segmentsGrob(x_mm, np.full(n, tot_h - gh_mm), x_mm, np.full(n, tot_h - gh_mm + tick_mm), gp=lgp_tick, default_units="mm"))
637
+ children.append(segmentsGrob(x_mm, np.full(n, tot_h - tick_mm), x_mm, np.full(n, tot_h), gp=lgp_tick, default_units="mm"))
638
+
639
+ if adjust_text_pos:
640
+ y_b0 = np.full(n, tot_h - gh_mm)
641
+ y_b1 = np.full(n, tot_h - gh_mm - lbl_pad_top / 3.0)
642
+ y_b2 = np.full(n, tot_h - gh_mm - lbl_pad_top * 2.0 / 3.0)
643
+ y_b3 = np.full(n, tot_h - gh_mm - lbl_pad_top + 0.5)
644
+ children.append(segmentsGrob(x_mm, y_b0, x_mm, y_b1, default_units="mm"))
645
+ children.append(segmentsGrob(labels_x, y_b3, labels_x, y_b2, default_units="mm"))
646
+ children.append(segmentsGrob(x_mm, y_b1, labels_x, y_b2, default_units="mm"))
647
+
648
+ if border is not None:
649
+ bg_gp = check_gp(lgp_tick)
650
+ bg_gp["fill"] = "transparent"
651
+ children.append(rectGrob(x=0.5 * lw_mm, y=tot_h, width=lw_mm, height=gh_mm, just="top", gp=bg_gp, default_units="mm"))
652
+
653
+ return GTree(
654
+ children=children,
655
+ cl="legend_body",
656
+ vp=Viewport(width=unit(lw_mm, "mm"), height=unit(tot_h, "mm")),
657
+ width=unit(lw_mm, "mm"),
658
+ height=unit(tot_h, "mm"),
659
+ )
660
+
661
+
662
+ def Legend(
663
+ at: Sequence[Any] | None = None,
664
+ labels: Sequence[Any] | None = None,
665
+ col_fun: Callable | None = None,
666
+ name: str | None = None,
667
+ grob: Grob | None = None,
668
+ break_dist: Sequence[float] | float | None = None,
669
+ nrow: int | None = None,
670
+ ncol: int = 1,
671
+ by_row: bool = False,
672
+ grid_height: Any = unit(4, "mm"),
673
+ grid_width: Any = unit(4, "mm"),
674
+ tick_length: Any = unit(0.8, "mm"),
675
+ gap: Any = unit(2, "mm"),
676
+ column_gap: Any = None,
677
+ row_gap: Any = unit(0, "mm"),
678
+ labels_gp: Any = None,
679
+ labels_rot: float = 0.0,
680
+ border: Any = None,
681
+ background: str = "#EEEEEE",
682
+ type: str | Sequence[str] = "grid",
683
+ graphics: Any = None,
684
+ legend_gp: Any = None,
685
+ pch: Any = 16,
686
+ size: Any = unit(2, "mm"),
687
+ legend_height: Any = None,
688
+ legend_width: Any = None,
689
+ direction: str = "vertical",
690
+ title: str | None = "",
691
+ title_gp: Any = None,
692
+ title_position: str = "topleft",
693
+ title_gap: Any = unit(2, "mm"),
694
+ ) -> Legends:
695
+ """Construct a single discrete, continuous, or custom legend (`Legends` object)."""
696
+ if at is None and labels is not None:
697
+ at = list(range(len(labels)))
698
+ if labels is None and at is not None:
699
+ labels = list(at)
700
+
701
+ lgp_labels = check_gp(labels_gp or gpar(fontsize=10))
702
+ if "fontsize" not in lgp_labels:
703
+ lgp_labels["fontsize"] = 10.0
704
+ lgp_title = check_gp(title_gp or gpar(fontsize=10, fontface="bold"))
705
+ if "fontsize" not in lgp_title:
706
+ lgp_title["fontsize"] = 10.0
707
+ if "fontface" not in lgp_title:
708
+ lgp_title["fontface"] = "bold"
709
+
710
+ direction = direction.lower()
711
+ if direction not in ("vertical", "horizontal"):
712
+ raise ValueError(f"Invalid legend `direction`: {direction!r}")
713
+ title_position = title_position.lower()
714
+ valid_tp = ("topleft", "topcenter", "leftcenter", "lefttop", "leftcenter-rot", "lefttop-rot")
715
+ if title_position not in valid_tp:
716
+ raise ValueError(f"Invalid `title_position`: {title_position!r}")
717
+
718
+ col_gap_u = as_unit(gap if column_gap is None else column_gap, "mm")
719
+ row_gap_u = as_unit(row_gap, "mm")
720
+ gh_u = as_unit(grid_height, "mm")
721
+ gw_u = as_unit(grid_width, "mm")
722
+ tick_u = as_unit(tick_length, "mm")
723
+ title_pad_mm = convertHeight(as_unit(title_gap, "mm"), "mm", valueOnly=True)
724
+
725
+ if grob is not None:
726
+ bw = grob.width_mm()
727
+ bh = grob.height_mm()
728
+ legend_body = GTree(children=[grob], cl="legend_body", vp=Viewport(width=unit(bw, "mm"), height=unit(bh, "mm")), width=unit(bw, "mm"), height=unit(bh, "mm"))
729
+ elif col_fun is None:
730
+ if at is None or labels is None:
731
+ raise ValueError("Provide `at` and/or `labels`, or `col_fun`, or `grob`.")
732
+ eff_border = "white" if border is None else border
733
+ legend_body = _discrete_legend_body(
734
+ at=list(at),
735
+ labels=list(labels),
736
+ nrow=nrow,
737
+ ncol=ncol,
738
+ by_row=by_row,
739
+ grid_height=gh_u,
740
+ grid_width=gw_u,
741
+ column_gap=col_gap_u,
742
+ row_gap=row_gap_u,
743
+ labels_gp=lgp_labels,
744
+ border=eff_border,
745
+ background=background,
746
+ type=type,
747
+ graphics=graphics,
748
+ legend_gp=legend_gp,
749
+ pch=pch,
750
+ size=as_unit(size, "mm"),
751
+ )
752
+ else:
753
+ if at is None:
754
+ brk = getattr(col_fun, "breaks", None)
755
+ if brk is None:
756
+ raise ValueError("Provide `at` when `col_fun` has no `breaks` attribute.")
757
+ if break_dist is None:
758
+ le1 = grid_pretty((float(np.min(brk)), float(np.max(brk))))
759
+ le2 = pretty_breaks((float(np.min(brk)), float(np.max(brk))), n=3)
760
+ at_vals = le1 if abs(len(le1) - 5) < abs(len(le2) - 5) else le2
761
+ else:
762
+ at_vals = np.asarray(brk, dtype=float)
763
+ labels = [f"{v:g}" for v in at_vals]
764
+ else:
765
+ at_vals = list(at)
766
+ if labels is None:
767
+ labels = list(at_vals)
768
+
769
+ if direction == "vertical":
770
+ if title_position in ("leftcenter", "lefttop"):
771
+ raise ValueError("'topleft', 'topcenter', 'leftcenter-rot' and 'lefttop-rot' are only allowed for vertical continuous legend.")
772
+ legend_body = _vertical_continuous_legend_body(
773
+ at=at_vals,
774
+ labels=list(labels),
775
+ col_fun=col_fun,
776
+ break_dist=break_dist,
777
+ grid_width=gw_u,
778
+ legend_height=None if legend_height is None else as_unit(legend_height, "mm"),
779
+ tick_length=tick_u,
780
+ labels_gp=lgp_labels,
781
+ border=border,
782
+ legend_gp=legend_gp,
783
+ )
784
+ else:
785
+ if title_position in ("leftcenter-rot", "lefttop-rot"):
786
+ raise ValueError("'topleft', 'topcenter', 'lefttop' and 'leftcenter' are only allowed for horizontal continuous legend.")
787
+ ext_u = unit(0.0, "mm")
788
+ if title_position == "lefttop" and title:
789
+ tg = textGrob(title, gp=lgp_title)
790
+ if tg.height_mm() <= convertHeight(gh_u, "mm", valueOnly=True):
791
+ ext_u = unit(tg.width_mm() + title_pad_mm, "mm")
792
+ legend_body = _horizontal_continuous_legend_body(
793
+ at=at_vals,
794
+ labels=list(labels),
795
+ col_fun=col_fun,
796
+ break_dist=break_dist,
797
+ grid_height=gh_u,
798
+ legend_width=None if legend_width is None else as_unit(legend_width, "mm"),
799
+ tick_length=tick_u,
800
+ labels_gp=lgp_labels,
801
+ labels_rot=labels_rot,
802
+ border=border,
803
+ legend_gp=legend_gp,
804
+ legend_extension=ext_u,
805
+ )
806
+
807
+ from .text import GridText
808
+
809
+ has_title = False
810
+ if isinstance(title, GridText):
811
+ has_title = len(title) > 0 and bool(title.as_list()[0].strip())
812
+ elif title is not None and str(title).strip() != "":
813
+ has_title = True
814
+
815
+ if not has_title:
816
+ return Legends(grob=legend_body, type="single_legend_no_title", name=name, n=1, multiple=1, direction="vertical")
817
+
818
+ tg = textGrob(title, gp=lgp_title)
819
+ t_w = tg.width_mm()
820
+ t_h = tg.height_mm()
821
+ b_w = legend_body.width_mm()
822
+ b_h = legend_body.height_mm()
823
+
824
+ if title_position in ("topleft", "topcenter"):
825
+ tot_w = max(t_w, b_w) if title_position == "topleft" else max(t_w, b_w)
826
+ tot_h = t_h + title_pad_mm + b_h
827
+ tx = unit(0.0, "npc") if title_position == "topleft" else unit(0.5, "npc")
828
+ tjust = ("left", "top") if title_position == "topleft" else "top"
829
+ gf = GTree(
830
+ children=[
831
+ textGrob(title, x=tx, y=unit(1.0, "npc"), just=tjust, gp=lgp_title),
832
+ _edit_vp_in_legend_grob(legend_body, x=unit(0.0, "npc"), y=unit(0.0, "npc"), valid_just=(0.0, 0.0)),
833
+ ],
834
+ vp=Viewport(width=unit(tot_w, "mm"), height=unit(tot_h, "mm")),
835
+ cl="legend",
836
+ width=unit(tot_w, "mm"),
837
+ height=unit(tot_h, "mm"),
838
+ )
839
+ elif title_position in ("leftcenter", "lefttop"):
840
+ tot_w = t_w + title_pad_mm + b_w
841
+ tot_h = max(t_h, b_h)
842
+ ty = unit(1.0, "npc") if title_position == "lefttop" else unit(0.5, "npc")
843
+ tjust = ("left", "top") if title_position == "lefttop" else "left"
844
+ gf = GTree(
845
+ children=[
846
+ textGrob(title, x=unit(0.0, "npc"), y=ty, just=tjust, gp=lgp_title),
847
+ _edit_vp_in_legend_grob(legend_body, x=unit(1.0, "npc"), y=unit(1.0, "npc"), valid_just=(1.0, 1.0)),
848
+ ],
849
+ vp=Viewport(width=unit(tot_w, "mm"), height=unit(tot_h, "mm")),
850
+ cl="legend",
851
+ width=unit(tot_w, "mm"),
852
+ height=unit(tot_h, "mm"),
853
+ )
854
+ else: # leftcenter-rot, lefttop-rot
855
+ tot_w = t_h + title_pad_mm + b_w
856
+ tot_h = max(t_w, b_h)
857
+ if title_position == "lefttop-rot":
858
+ ty = unit(1.0, "npc")
859
+ tjust = ("right", "top")
860
+ else:
861
+ ty = unit(0.5, "npc")
862
+ tjust = "top"
863
+ gf = GTree(
864
+ children=[
865
+ textGrob(title, x=unit(0.0, "npc"), y=ty, just=tjust, gp=lgp_title, rot=90.0),
866
+ _edit_vp_in_legend_grob(legend_body, x=unit(1.0, "npc"), y=unit(1.0, "npc"), valid_just=(1.0, 1.0)),
867
+ ],
868
+ vp=Viewport(width=unit(tot_w, "mm"), height=unit(tot_h, "mm")),
869
+ cl="legend",
870
+ width=unit(tot_w, "mm"),
871
+ height=unit(tot_h, "mm"),
872
+ )
873
+
874
+ return Legends(grob=gf, type="single_legend", name=name, n=1, multiple=1, direction="vertical")
875
+
876
+
877
+ def _split_by_max(vals: Sequence[float], max_val: float, gap: float = 0.0) -> list[list[int]]:
878
+ n = len(vals)
879
+ chunks: list[list[int]] = []
880
+ cur: list[int] = []
881
+ acc = 0.0
882
+ for i, v in enumerate(vals):
883
+ step = v + (gap if cur else 0.0)
884
+ if cur and acc + step >= max_val:
885
+ chunks.append(cur)
886
+ cur = [i]
887
+ acc = v
888
+ else:
889
+ cur.append(i)
890
+ acc += step
891
+ if cur:
892
+ chunks.append(cur)
893
+ return chunks
894
+
895
+
896
+ def packLegend(
897
+ *legends: Legends,
898
+ gap: Any = unit(4, "mm"),
899
+ row_gap: Any = None,
900
+ column_gap: Any = None,
901
+ direction: str = "vertical",
902
+ max_width: Any = None,
903
+ max_height: Any = None,
904
+ list: Sequence[Legends] | None = None,
905
+ ) -> Legends:
906
+ """Pack multiple `Legends` objects vertically or horizontally with optional wrapping."""
907
+ lgd_list = [lg for lg in (list if list is not None else legends) if lg is not None]
908
+ if not lgd_list:
909
+ empty = GTree(children=[], cl="packed_legends", width=unit(0.0, "mm"), height=unit(0.0, "mm"))
910
+ return Legends(grob=empty, type="packed_legends", n=0, multiple=1, direction=direction)
911
+ if len(lgd_list) == 1:
912
+ return lgd_list[0]
913
+
914
+ direction = direction.lower()
915
+ rg_mm = convertHeight(as_unit(gap if row_gap is None else row_gap, "mm"), "mm", valueOnly=True)
916
+ cg_mm = convertWidth(as_unit(gap if column_gap is None else column_gap, "mm"), "mm", valueOnly=True)
917
+ grobs = [lg.grob for lg in lgd_list]
918
+ n_lgd = len(grobs)
919
+
920
+ children: list[Grob] = []
921
+ if direction == "vertical":
922
+ heights = [g.height_mm() for g in grobs]
923
+ widths = [g.width_mm() for g in grobs]
924
+ if max_height is None:
925
+ chunks = [[i for i in range(n_lgd)]]
926
+ else:
927
+ mh = convertHeight(as_unit(max_height, "mm"), "mm", valueOnly=True)
928
+ chunks = _split_by_max(heights, mh, rg_mm)
929
+ nc = len(chunks)
930
+ col_widths = [max(widths[i] for i in ch) for ch in chunks]
931
+ col_heights = [sum(heights[i] for i in ch) + rg_mm * max(0, len(ch) - 1) for ch in chunks]
932
+ tot_w = sum(col_widths) + cg_mm * max(0, nc - 1)
933
+ tot_h = max(col_heights)
934
+
935
+ cur_x = 0.0
936
+ for ci, ch in enumerate(chunks):
937
+ cur_top = tot_h
938
+ for i in ch:
939
+ g = grobs[i]
940
+ h_i = heights[i]
941
+ cur_bot = cur_top - h_i
942
+ children.append(
943
+ _edit_vp_in_legend_grob(
944
+ g,
945
+ x=unit(cur_x, "mm"),
946
+ y=unit(cur_bot, "mm"),
947
+ valid_just=(0.0, 0.0),
948
+ )
949
+ )
950
+ cur_top = cur_bot - rg_mm
951
+ cur_x += col_widths[ci] + cg_mm
952
+ mult = nc
953
+ else:
954
+ heights = [g.height_mm() for g in grobs]
955
+ widths = [g.width_mm() for g in grobs]
956
+ if max_width is None:
957
+ chunks = [[i for i in range(n_lgd)]]
958
+ else:
959
+ mw = convertWidth(as_unit(max_width, "mm"), "mm", valueOnly=True)
960
+ chunks = _split_by_max(widths, mw, cg_mm)
961
+ nr = len(chunks)
962
+ row_heights = [max(heights[i] for i in ch) for ch in chunks]
963
+ row_widths = [sum(widths[i] for i in ch) + cg_mm * max(0, len(ch) - 1) for ch in chunks]
964
+ tot_w = max(row_widths)
965
+ tot_h = sum(row_heights) + rg_mm * max(0, nr - 1)
966
+
967
+ cur_top = tot_h
968
+ for ri, ch in enumerate(chunks):
969
+ cur_x = 0.0
970
+ for i in ch:
971
+ g = grobs[i]
972
+ w_i = widths[i]
973
+ children.append(
974
+ _edit_vp_in_legend_grob(
975
+ g,
976
+ x=unit(cur_x + w_i, "mm"),
977
+ y=unit(cur_top, "mm"),
978
+ valid_just=(1.0, 1.0),
979
+ )
980
+ )
981
+ cur_x += w_i + cg_mm
982
+ cur_top -= row_heights[ri] + rg_mm
983
+ mult = nr
984
+
985
+ gt = GTree(
986
+ children=children,
987
+ cl="packed_legends",
988
+ vp=Viewport(width=unit(tot_w, "mm"), height=unit(tot_h, "mm")),
989
+ width=unit(tot_w, "mm"),
990
+ height=unit(tot_h, "mm"),
991
+ )
992
+ return Legends(grob=gt, type="packed_legends", n=n_lgd, multiple=mult, direction=direction)