pqplot 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.
pqplot/tracks.py ADDED
@@ -0,0 +1,787 @@
1
+ """Data layers drawn into the track panels of a karyogram."""
2
+
3
+ from __future__ import annotations
4
+
5
+ import warnings
6
+ from collections.abc import Iterator, Mapping
7
+ from typing import Literal
8
+
9
+ import matplotlib.pyplot as plt
10
+ import numpy as np
11
+ from matplotlib.artist import Artist
12
+ from matplotlib.axes import Axes
13
+ from matplotlib.cm import ScalarMappable
14
+ from matplotlib.collections import LineCollection, PathCollection
15
+ from matplotlib.colors import Colormap, Normalize
16
+ from matplotlib.lines import Line2D
17
+ from matplotlib.patches import StepPatch
18
+ from matplotlib.ticker import MaxNLocator
19
+ from matplotlib.transforms import IdentityTransform, ScaledTranslation, Transform
20
+ from matplotlib.typing import ColorType
21
+
22
+ from pqplot.colors import category_colors, value_scale
23
+ from pqplot.columns import column, rows_by_chrom
24
+ from pqplot.genome import chrom_key
25
+ from pqplot.ideograms import MIN_PAINT_POINTS
26
+ from pqplot.labels import capacity, spread
27
+ from pqplot.panels import Orientation
28
+ from pqplot.spans import Spans
29
+
30
+ LEADER_POINTS = (5.0, 7.0, 10.0)
31
+ """Start, elbow and end of a label leader, in points from the track edge."""
32
+
33
+
34
+ class TrackPanels:
35
+ """Draws data into one track, across every chromosome of a karyogram.
36
+
37
+ Get one from `Karyogram.track`. Each method takes a table with one row
38
+ per point or bin, splits the rows by chromosome and draws each group
39
+ into its chromosome's panel. Rows on chromosomes without a panel are
40
+ skipped. Positions are in bp. Panels of one track share their value
41
+ axis, so one call scales them all.
42
+
43
+ Each column argument is a column name in `data` or the values
44
+ themselves. Extra keyword arguments go to the matplotlib call. Arrays
45
+ and Series among them with one value per row, such as ``c`` or ``s``,
46
+ are split by chromosome too.
47
+
48
+ Parameters
49
+ ----------
50
+ panels : dict of str to matplotlib.axes.Axes
51
+ Track panels keyed by chromosome name, in drawing order.
52
+ orientation : {"horizontal", "vertical"}
53
+ Direction of the chromosomes.
54
+ side : {"before", "after"}
55
+ Side of the body the track sits on. Marks and labels start from
56
+ the edge that faces the body.
57
+ legend : dict of str to matplotlib.artist.Artist
58
+ Legend entries of the karyogram, which `intervals` and `mark` add
59
+ to.
60
+
61
+ Examples
62
+ --------
63
+ >>> from pqplot import Genome, Karyogram, Track
64
+ >>> kary = Karyogram(Genome.bundled("hg38"), tracks=[Track("cnv")])
65
+ >>> type(kary.track("cnv")).__name__
66
+ 'TrackPanels'
67
+ """
68
+
69
+ def __init__(
70
+ self,
71
+ panels: dict[str, Axes],
72
+ orientation: Orientation,
73
+ side: Literal["before", "after"],
74
+ legend: dict[str, Artist],
75
+ ):
76
+ self._panels = {chrom_key(name): (name, panel) for name, panel in panels.items()}
77
+ self._orientation = orientation
78
+ self._side = side
79
+ self._legend = legend
80
+
81
+ def mark(
82
+ self,
83
+ data: object = None,
84
+ *,
85
+ chrom: object = "chrom",
86
+ pos: object = "pos",
87
+ color: object = None,
88
+ palette: Mapping[object, ColorType] | None = None,
89
+ size: float = 16.0,
90
+ **kwargs,
91
+ ) -> dict[str, PathCollection]:
92
+ """Draw a triangle at each position, on the track edge that faces the body.
93
+
94
+ Each triangle points at the body. The track's value axis is hidden.
95
+
96
+ Parameters
97
+ ----------
98
+ data : DataFrame or dict, optional
99
+ Table with one row per mark.
100
+ chrom : str or array-like, default "chrom"
101
+ Chromosome of each mark.
102
+ pos : str or array-like, default "pos"
103
+ Position in bp.
104
+ color : str or array-like, optional
105
+ Category of each mark. Categories get colors from `palette` and
106
+ appear in `Karyogram.legend`. By default, every mark gets the
107
+ first color of the theme's cycle.
108
+ palette : mapping, optional
109
+ Color of each category, in legend order. By default, the
110
+ theme's color cycle in order of first appearance.
111
+ size : float, default 16
112
+ Marker area in points squared, as in `matplotlib.axes.Axes.scatter`.
113
+ **kwargs
114
+ Passed to `matplotlib.axes.Axes.scatter`.
115
+
116
+ Returns
117
+ -------
118
+ dict of str to matplotlib.collections.PathCollection
119
+ Marks keyed by chromosome name.
120
+
121
+ Raises
122
+ ------
123
+ KeyError
124
+ If `palette` lacks a category.
125
+
126
+ Examples
127
+ --------
128
+ >>> from pqplot import Genome, Karyogram, Track
129
+ >>> kary = Karyogram(Genome.bundled("hg38"), tracks=[Track("hits", "after", 5)])
130
+ >>> gwas = {"chrom": ["1", "2"], "pos": [55e6, 21e6], "trait": ["LDL", "LDL"]}
131
+ >>> list(kary.track("hits").mark(gwas, color="trait"))
132
+ ['chr1', 'chr2']
133
+ """
134
+ along = column(data, pos).astype(float)
135
+ categories = None if color is None else column(data, color)
136
+ marker = {(1, 0): "<", (-1, 0): ">", (0, -1): "^", (0, 1): "v"}[self._away()]
137
+
138
+ def handle(swatch: np.ndarray) -> Artist:
139
+ return Line2D(
140
+ [],
141
+ [],
142
+ marker=marker,
143
+ markersize=np.sqrt(size),
144
+ linestyle="none",
145
+ color=swatch,
146
+ markeredgewidth=0,
147
+ )
148
+
149
+ codes, swatches = category_colors(categories, len(along), palette, self._legend, handle)
150
+ inset = np.array(self._away()) * np.sqrt(size) / 2 / 72
151
+ kwargs = {"linewidths": 0, "clip_on": False, "zorder": 3, **kwargs}
152
+ self._hide_values()
153
+ marks = {}
154
+ for name, panel, rows in self._groups(data, chrom):
155
+ transform = self._across_axes(panel) + ScaledTranslation(
156
+ *inset, panel.figure.dpi_scale_trans
157
+ )
158
+ marks[name] = panel.scatter(
159
+ *self._xy(along[rows], np.full(len(rows), self._inner())),
160
+ s=size,
161
+ marker=marker,
162
+ c=swatches[codes[rows]],
163
+ transform=transform,
164
+ **kwargs,
165
+ )
166
+ return marks
167
+
168
+ def label(
169
+ self,
170
+ data: object = None,
171
+ *,
172
+ chrom: object = "chrom",
173
+ pos: object = "pos",
174
+ text: object = "text",
175
+ fontsize: float | str = "x-small",
176
+ **kwargs,
177
+ ) -> dict[str, LabelLane]:
178
+ """Write a label for each position, joined to it by a leader line.
179
+
180
+ Labels start from the track edge that faces the body. Crowded
181
+ labels spread apart at draw time and keep their order. Labels that
182
+ still do not fit are hidden from the last row up, with a warning,
183
+ so put the important rows first. Labels do not count in the
184
+ layout, so size the track to fit the longest one. The track's value
185
+ axis is hidden.
186
+
187
+ Parameters
188
+ ----------
189
+ data : DataFrame or dict, optional
190
+ Table with one row per label.
191
+ chrom : str or array-like, default "chrom"
192
+ Chromosome of each label.
193
+ pos : str or array-like, default "pos"
194
+ Position in bp the label points at.
195
+ text : str or array-like, default "text"
196
+ Label text.
197
+ fontsize : float or str, default "x-small"
198
+ Font size of the labels.
199
+ **kwargs
200
+ Passed to `matplotlib.text.Text`.
201
+
202
+ Returns
203
+ -------
204
+ dict of str to LabelLane
205
+ Labels keyed by chromosome name.
206
+
207
+ Examples
208
+ --------
209
+ >>> from pqplot import Genome, Karyogram, Track
210
+ >>> kary = Karyogram(Genome.bundled("hg38"), tracks=[Track("genes", "after", 5)])
211
+ >>> genes = {"chrom": ["1", "2"], "start": [55e6, 21e6], "symbol": ["PCSK9", "APOB"]}
212
+ >>> lanes = kary.track("genes").label(genes, pos="start", text="symbol")
213
+ >>> [t.get_text() for t in lanes["chr1"].texts]
214
+ ['PCSK9']
215
+ """
216
+ along = column(data, pos).astype(float)
217
+ texts = column(data, text).astype(str)
218
+ self._hide_values()
219
+ return {
220
+ name: LabelLane(
221
+ panel,
222
+ along[rows],
223
+ texts[rows],
224
+ orientation=self._orientation,
225
+ away=self._away(),
226
+ fontsize=fontsize,
227
+ **kwargs,
228
+ )
229
+ for name, panel, rows in self._groups(data, chrom)
230
+ }
231
+
232
+ def scatter(
233
+ self,
234
+ data: object = None,
235
+ *,
236
+ chrom: object = "chrom",
237
+ pos: object = "pos",
238
+ value: object = "value",
239
+ **kwargs,
240
+ ) -> dict[str, PathCollection]:
241
+ """Draw one marker per row at its position and value.
242
+
243
+ A numeric ``c`` gets one color scale across every chromosome, unless
244
+ ``norm``, ``vmin`` or ``vmax`` sets it. Markers have no edge unless
245
+ ``linewidths`` sets one, because themes that ring markers in the
246
+ background color would hide small, dense points.
247
+
248
+ Parameters
249
+ ----------
250
+ data : DataFrame or dict, optional
251
+ Table with one row per point.
252
+ chrom : str or array-like, default "chrom"
253
+ Chromosome of each point.
254
+ pos : str or array-like, default "pos"
255
+ Position in bp.
256
+ value : str or array-like, default "value"
257
+ Value on the track's value axis.
258
+ **kwargs
259
+ Passed to `matplotlib.axes.Axes.scatter`.
260
+
261
+ Returns
262
+ -------
263
+ dict of str to matplotlib.collections.PathCollection
264
+ Markers keyed by chromosome name.
265
+
266
+ Examples
267
+ --------
268
+ >>> from pqplot import Genome, Karyogram, Track
269
+ >>> kary = Karyogram(Genome.bundled("hg38"), tracks=[Track("cnv")])
270
+ >>> import numpy as np
271
+ >>> bins = {"chrom": ["1", "2"], "mid": [5e5, 7e5], "log2": np.array([0.4, -1.2])}
272
+ >>> points = kary.track("cnv").scatter(bins, pos="mid", value="log2", c=bins["log2"])
273
+ >>> list(points)
274
+ ['chr1', 'chr2']
275
+ """
276
+ along, values = column(data, pos), column(data, value)
277
+ kwargs = {"linewidths": 0, **kwargs}
278
+ colors = np.asarray(kwargs.get("c", ()))
279
+ if (
280
+ colors.dtype.kind in "fiu"
281
+ and colors.size
282
+ and not {"norm", "vmin", "vmax"} & set(kwargs)
283
+ ):
284
+ kwargs |= {"vmin": np.nanmin(colors), "vmax": np.nanmax(colors)}
285
+ return {
286
+ name: panel.scatter(
287
+ *self._xy(along[rows], values[rows]), **_split_styles(kwargs, rows, len(along))
288
+ )
289
+ for name, panel, rows in self._groups(data, chrom)
290
+ }
291
+
292
+ def line(
293
+ self,
294
+ data: object = None,
295
+ *,
296
+ chrom: object = "chrom",
297
+ pos: object = "pos",
298
+ value: object = "value",
299
+ **kwargs,
300
+ ) -> dict[str, Line2D]:
301
+ """Draw a line through the rows of each chromosome, in position order.
302
+
303
+ Parameters
304
+ ----------
305
+ data : DataFrame or dict, optional
306
+ Table with one row per point.
307
+ chrom : str or array-like, default "chrom"
308
+ Chromosome of each point.
309
+ pos : str or array-like, default "pos"
310
+ Position in bp.
311
+ value : str or array-like, default "value"
312
+ Value on the track's value axis.
313
+ **kwargs
314
+ Passed to `matplotlib.axes.Axes.plot`.
315
+
316
+ Returns
317
+ -------
318
+ dict of str to matplotlib.lines.Line2D
319
+ Lines keyed by chromosome name.
320
+
321
+ Examples
322
+ --------
323
+ >>> from pqplot import Genome, Karyogram, Track
324
+ >>> kary = Karyogram(Genome.bundled("hg38"), tracks=[Track("gc")])
325
+ >>> gc = {"chrom": ["1", "1"], "pos": [2e6, 1e6], "value": [0.41, 0.38]}
326
+ >>> kary.track("gc").line(gc)["chr1"].get_ydata().tolist()
327
+ [1000000.0, 2000000.0]
328
+ """
329
+ along, values = column(data, pos), column(data, value)
330
+ lines = {}
331
+ for name, panel, rows in self._groups(data, chrom):
332
+ rows = rows[np.argsort(along[rows], kind="stable")]
333
+ (lines[name],) = panel.plot(*self._xy(along[rows], values[rows]), **kwargs)
334
+ return lines
335
+
336
+ def area(
337
+ self,
338
+ data: object = None,
339
+ *,
340
+ chrom: object = "chrom",
341
+ start: object = "start",
342
+ end: object = "end",
343
+ value: object = "value",
344
+ baseline: float = 0.0,
345
+ **kwargs,
346
+ ) -> dict[str, StepPatch]:
347
+ """Fill from a baseline to each bin's value, as steps.
348
+
349
+ Bins of one chromosome must not overlap. Gaps between them stay
350
+ empty.
351
+
352
+ Parameters
353
+ ----------
354
+ data : DataFrame or dict, optional
355
+ Table with one row per bin.
356
+ chrom : str or array-like, default "chrom"
357
+ Chromosome of each bin.
358
+ start, end : str or array-like, default "start" and "end"
359
+ Span of each bin in bp.
360
+ value : str or array-like, default "value"
361
+ Height of each bin on the track's value axis.
362
+ baseline : float, default 0
363
+ Value the fill starts from.
364
+ **kwargs
365
+ Passed to `matplotlib.axes.Axes.stairs`.
366
+
367
+ Returns
368
+ -------
369
+ dict of str to matplotlib.patches.StepPatch
370
+ Fills keyed by chromosome name.
371
+
372
+ Examples
373
+ --------
374
+ >>> from pqplot import Genome, Karyogram, Track
375
+ >>> kary = Karyogram(Genome.bundled("hg38"), tracks=[Track("genes")])
376
+ >>> density = {"chrom": ["1", "1"], "start": [0, 1e6], "end": [1e6, 2e6], "value": [3, 8]}
377
+ >>> kary.track("genes").area(density)["chr1"].get_data().edges.tolist()
378
+ [0.0, 1000000.0, 2000000.0]
379
+ """
380
+ starts, ends = column(data, start).astype(float), column(data, end).astype(float)
381
+ values = column(data, value).astype(float)
382
+ across = "horizontal" if self._orientation == "vertical" else "vertical"
383
+ areas = {}
384
+ for name, panel, rows in self._groups(data, chrom):
385
+ rows = rows[np.argsort(starts[rows], kind="stable")]
386
+ edges, heights = _steps(starts[rows], ends[rows], values[rows])
387
+ areas[name] = panel.stairs(
388
+ heights, edges, baseline=baseline, fill=True, orientation=across, **kwargs
389
+ )
390
+ return areas
391
+
392
+ def heatmap(
393
+ self,
394
+ data: object = None,
395
+ *,
396
+ chrom: object = "chrom",
397
+ start: object = "start",
398
+ end: object = "end",
399
+ value: object = "value",
400
+ cmap: str | Colormap | None = None,
401
+ norm: Normalize | None = None,
402
+ **kwargs,
403
+ ) -> ScalarMappable:
404
+ """Color each bin across the full track width by its value.
405
+
406
+ Parameters
407
+ ----------
408
+ data : DataFrame or dict, optional
409
+ Table with one row per bin.
410
+ chrom : str or array-like, default "chrom"
411
+ Chromosome of each bin.
412
+ start, end : str or array-like, default "start" and "end"
413
+ Span of each bin in bp.
414
+ value : str or array-like, default "value"
415
+ Number colored through `cmap` and `norm`.
416
+ cmap : str or matplotlib.colors.Colormap, optional
417
+ Colormap. By default, the theme's.
418
+ norm : matplotlib.colors.Normalize, optional
419
+ Scaling of `value`. By default, its minimum to its maximum.
420
+ **kwargs
421
+ Passed to `pqplot.spans.Spans`.
422
+
423
+ Returns
424
+ -------
425
+ matplotlib.cm.ScalarMappable
426
+ The color scale, for a colorbar.
427
+
428
+ Examples
429
+ --------
430
+ >>> from pqplot import Genome, Karyogram, Track
431
+ >>> kary = Karyogram(Genome.bundled("hg38"), tracks=[Track("expr")])
432
+ >>> bins = {"chrom": ["1", "1"], "start": [0, 1e6], "end": [1e6, 2e6], "value": [3, 8]}
433
+ >>> kary.track("expr").heatmap(bins, cmap="magma").norm.vmax
434
+ 8.0
435
+ """
436
+ starts, ends = column(data, start).astype(float), column(data, end).astype(float)
437
+ values = column(data, value).astype(float)
438
+ scale = value_scale(values, cmap, norm)
439
+ for _, panel, rows in self._groups(data, chrom):
440
+ colors = scale.to_rgba(values[rows])
441
+ self._add_spans(panel, starts[rows], ends[rows], colors, 0.0, **kwargs)
442
+ return scale
443
+
444
+ def intervals(
445
+ self,
446
+ data: object = None,
447
+ *,
448
+ chrom: object = "chrom",
449
+ start: object = "start",
450
+ end: object = "end",
451
+ color: object = None,
452
+ palette: Mapping[object, ColorType] | None = None,
453
+ **kwargs,
454
+ ) -> dict[str, Spans]:
455
+ """Draw a box across the track width over each interval.
456
+
457
+ Intervals narrower than `MIN_PAINT_POINTS` widen at draw time, so
458
+ small features such as peaks stay visible.
459
+
460
+ Parameters
461
+ ----------
462
+ data : DataFrame or dict, optional
463
+ Table with one row per interval.
464
+ chrom : str or array-like, default "chrom"
465
+ Chromosome of each interval.
466
+ start, end : str or array-like, default "start" and "end"
467
+ Span of each interval in bp.
468
+ color : str or array-like, optional
469
+ Category of each interval. Categories get colors from `palette`
470
+ and appear in `Karyogram.legend`. By default, every interval
471
+ gets the first color of the theme's cycle.
472
+ palette : mapping, optional
473
+ Color of each category, in legend order. By default, the
474
+ theme's color cycle in order of first appearance.
475
+ **kwargs
476
+ Passed to `pqplot.spans.Spans`.
477
+
478
+ Returns
479
+ -------
480
+ dict of str to pqplot.spans.Spans
481
+ Boxes keyed by chromosome name.
482
+
483
+ Raises
484
+ ------
485
+ KeyError
486
+ If `palette` lacks a category.
487
+
488
+ Examples
489
+ --------
490
+ >>> from pqplot import Genome, Karyogram, Track
491
+ >>> kary = Karyogram(Genome.bundled("hg38"), tracks=[Track("peaks")])
492
+ >>> peaks = {"chrom": ["1", "2"], "start": [1e6, 3e6], "end": [1.0002e6, 3.0001e6]}
493
+ >>> list(kary.track("peaks").intervals(peaks))
494
+ ['chr1', 'chr2']
495
+ """
496
+ starts, ends = column(data, start).astype(float), column(data, end).astype(float)
497
+ categories = None if color is None else column(data, color)
498
+ codes, swatches = category_colors(categories, len(starts), palette, self._legend)
499
+ return {
500
+ name: self._add_spans(
501
+ panel, starts[rows], ends[rows], swatches[codes[rows]], MIN_PAINT_POINTS, **kwargs
502
+ )
503
+ for name, panel, rows in self._groups(data, chrom)
504
+ }
505
+
506
+ def _groups(self, data: object, chrom: object) -> Iterator[tuple[str, Axes, np.ndarray]]:
507
+ """Yield each drawn chromosome with its panel and rows, in drawing order."""
508
+ rows = rows_by_chrom(column(data, chrom))
509
+ for key, (name, panel) in self._panels.items():
510
+ if key in rows:
511
+ yield name, panel, rows[key]
512
+
513
+ def _xy(self, along: np.ndarray, values: np.ndarray) -> tuple[np.ndarray, np.ndarray]:
514
+ return (values, along) if self._orientation == "vertical" else (along, values)
515
+
516
+ def _hide_values(self) -> None:
517
+ """Hide the value axis, which means nothing for marks and labels."""
518
+ for _, panel in self._panels.values():
519
+ (panel.xaxis if self._orientation == "vertical" else panel.yaxis).set_visible(False)
520
+
521
+ def _away(self) -> tuple[int, int]:
522
+ """Return the display direction that points away from the body."""
523
+ sign = 1 if self._side == "after" else -1
524
+ return (sign, 0) if self._orientation == "vertical" else (0, -sign)
525
+
526
+ def _inner(self) -> float:
527
+ """Return the across position of the edge facing the body, as an axes fraction."""
528
+ return 0.0 if sum(self._away()) > 0 else 1.0
529
+
530
+ def _across_axes(self, panel: Axes) -> Transform:
531
+ """Return the transform with along in data and across in axes fractions."""
532
+ return (
533
+ panel.get_yaxis_transform()
534
+ if self._orientation == "vertical"
535
+ else panel.get_xaxis_transform()
536
+ )
537
+
538
+ def _add_spans(
539
+ self,
540
+ panel: Axes,
541
+ starts: np.ndarray,
542
+ ends: np.ndarray,
543
+ colors: np.ndarray,
544
+ min_points: float,
545
+ **kwargs,
546
+ ) -> Spans:
547
+ """Add spans that fill the track width, with a thin edge to hide seams."""
548
+ transform = self._across_axes(panel)
549
+ kwargs = {"facecolors": colors, "edgecolors": colors, "linewidths": 0.25, **kwargs}
550
+ spans = Spans(
551
+ starts,
552
+ ends,
553
+ (0.0, 1.0),
554
+ orientation=self._orientation,
555
+ min_points=min_points,
556
+ transform=transform,
557
+ **kwargs,
558
+ )
559
+ panel.add_collection(spans, autolim=False)
560
+ return spans
561
+
562
+
563
+ def _split_styles(styles: dict, rows: np.ndarray, length: int) -> dict:
564
+ """Pick out the rows of style arrays that hold one value per row."""
565
+ return {
566
+ key: np.asarray(style)[rows]
567
+ if hasattr(style, "__array__") and np.ndim(style) >= 1 and len(style) == length
568
+ else style
569
+ for key, style in styles.items()
570
+ }
571
+
572
+
573
+ def _steps(
574
+ starts: np.ndarray, ends: np.ndarray, values: np.ndarray
575
+ ) -> tuple[np.ndarray, np.ndarray]:
576
+ """Return step edges and heights for sorted bins, with NaN steps over gaps."""
577
+ gap = np.append(False, starts[1:] > ends[:-1])
578
+ slot = np.arange(len(starts)) + np.cumsum(gap)
579
+ heights = np.full(len(starts) + gap.sum(), np.nan)
580
+ heights[slot] = values
581
+ edges = np.empty(len(heights) + 1)
582
+ edges[0] = starts[0]
583
+ edges[slot + 1] = ends
584
+ edges[slot[gap]] = starts[gap]
585
+ return edges, heights
586
+
587
+
588
+ class LabelLane(Artist):
589
+ """Labels in a track panel, spread along the chromosome at each draw.
590
+
591
+ Each label sits beyond the panel edge that faces the body, joined to
592
+ its position by a leader line. At draw time, labels closer than one
593
+ line of text spread apart with `pqplot.labels.spread`, keeping their
594
+ order. Labels that do not fit are hidden from the last one up, with a
595
+ warning.
596
+
597
+ Parameters
598
+ ----------
599
+ panel : matplotlib.axes.Axes
600
+ Track panel to draw in.
601
+ positions : numpy.ndarray
602
+ Positions in bp the labels point at.
603
+ texts : numpy.ndarray of str
604
+ Label texts, most important first.
605
+ orientation : {"horizontal", "vertical"}
606
+ Direction of the chromosome.
607
+ away : tuple of int
608
+ Display direction that points away from the body.
609
+ fontsize : float or str
610
+ Font size of the labels.
611
+ **kwargs
612
+ Passed to `matplotlib.text.Text`.
613
+
614
+ Attributes
615
+ ----------
616
+ texts : list of matplotlib.text.Text
617
+ Labels, in the order given.
618
+ leaders : matplotlib.collections.LineCollection
619
+ Leader lines, one per label.
620
+
621
+ Examples
622
+ --------
623
+ >>> import numpy as np
624
+ >>> from pqplot import Genome, Karyogram, Track
625
+ >>> kary = Karyogram(Genome.bundled("hg38"), chroms=["1"], tracks=[Track("genes", "after", 5)])
626
+ >>> panel = kary.panel("1", "genes")
627
+ >>> lane = LabelLane(panel, np.array([5e7]), np.array(["TP73"]),
628
+ ... orientation="vertical", away=(1, 0), fontsize="x-small")
629
+ >>> lane.texts[0].get_text()
630
+ 'TP73'
631
+ """
632
+
633
+ def __init__(
634
+ self,
635
+ panel: Axes,
636
+ positions: np.ndarray,
637
+ texts: np.ndarray,
638
+ *,
639
+ orientation: Orientation,
640
+ away: tuple[int, int],
641
+ fontsize: float | str,
642
+ **kwargs,
643
+ ):
644
+ super().__init__()
645
+ self.positions = positions
646
+ self.orientation = orientation
647
+ self.away = np.array(away)
648
+ rotation = 0 if orientation == "vertical" else 90
649
+ # Align the end of each label nearest the body to its anchor.
650
+ ha = "left" if away[0] > 0 or away[1] > 0 else "right"
651
+ self.texts = [
652
+ panel.text(
653
+ 0,
654
+ 0,
655
+ text,
656
+ transform=IdentityTransform(),
657
+ fontsize=fontsize,
658
+ rotation=rotation,
659
+ rotation_mode="anchor",
660
+ ha=ha,
661
+ va="center",
662
+ clip_on=False,
663
+ in_layout=False,
664
+ zorder=3,
665
+ **kwargs,
666
+ )
667
+ for text in texts
668
+ ]
669
+ self.leaders = LineCollection(
670
+ [],
671
+ colors=plt.rcParams["axes.edgecolor"],
672
+ linewidths=0.4,
673
+ transform=IdentityTransform(),
674
+ clip_on=False,
675
+ zorder=2.95,
676
+ )
677
+ self.leaders.set_in_layout(False)
678
+ panel.add_collection(self.leaders, autolim=False)
679
+ self.set_zorder(2.9)
680
+ self.set_in_layout(False)
681
+ panel.add_artist(self)
682
+
683
+ def draw(self, renderer) -> None:
684
+ """Place the labels and leaders for the current panel size.
685
+
686
+ Examples
687
+ --------
688
+ >>> import numpy as np
689
+ >>> from pqplot import Genome, Karyogram, Track
690
+ >>> kary = Karyogram(Genome.bundled("hg38"), chroms=["1"], tracks=[Track("g", "after", 5)])
691
+ >>> lane = LabelLane(kary.panel("1", "g"), np.array([5e7]), np.array(["TP73"]),
692
+ ... orientation="vertical", away=(1, 0), fontsize="x-small")
693
+ >>> kary.figure.draw_without_rendering()
694
+ >>> lane.texts[0].get_position() != (0, 0)
695
+ True
696
+ """
697
+ if not self.texts:
698
+ return
699
+ along = 1 if self.orientation == "vertical" else 0
700
+ box = self.axes.bbox
701
+ points = renderer.points_to_pixels
702
+ line = points(self.texts[0].get_fontsize()) * 1.2
703
+ low, high = sorted((box.p0[along], box.p1[along]))
704
+ low, high = low + line / 2, high - line / 2
705
+ fits = min(len(self.texts), capacity(line, low, high))
706
+ if fits < len(self.texts):
707
+ warnings.warn(
708
+ f"{len(self.texts) - fits} labels do not fit; hiding the last ones. "
709
+ "Use a smaller font or fewer labels.",
710
+ stacklevel=2,
711
+ )
712
+ xy = np.zeros((len(self.positions), 2))
713
+ xy[:, along] = self.positions
714
+ targets = self.axes.transData.transform(xy)[:, along]
715
+ shown = np.arange(fits)
716
+ order = shown[np.argsort(targets[shown], kind="stable")]
717
+ placed = np.empty(fits)
718
+ placed[np.argsort(order)] = spread(targets[order], line, low, high)
719
+ inner = box.p0 if self.away.sum() > 0 else box.p1
720
+ edge = inner[1 - along]
721
+ start, elbow, end = (edge + self.away[1 - along] * points(d) for d in LEADER_POINTS)
722
+ segments = []
723
+ for i, text in enumerate(self.texts):
724
+ text.set_visible(i < fits)
725
+ if i >= fits:
726
+ continue
727
+ path = np.empty((3, 2))
728
+ path[:, along] = [targets[i], targets[i], placed[i]]
729
+ path[:, 1 - along] = [start, elbow, end]
730
+ segments.append(path)
731
+ anchor = path[-1].copy()
732
+ anchor[1 - along] += self.away[1 - along] * points(1)
733
+ text.set_position(anchor)
734
+ self.leaders.set_segments(segments)
735
+
736
+
737
+ class _OuterTicks(MaxNLocator):
738
+ """Keeps only the lowest and highest round ticks in view, for narrow tracks."""
739
+
740
+ def __init__(self):
741
+ super().__init__(nbins=2, steps=[1, 2, 2.5, 5, 10])
742
+
743
+ def tick_values(self, vmin: float, vmax: float) -> np.ndarray:
744
+ ticks = super().tick_values(vmin, vmax)
745
+ low, high = sorted((vmin, vmax))
746
+ slack = 1e-9 * (high - low)
747
+ inside = ticks[(ticks >= low - slack) & (ticks <= high + slack)]
748
+ return inside[[0, -1]] if len(inside) > 2 else inside
749
+
750
+
751
+ def style_track(panel: Axes, orientation: Orientation, labels: bool) -> None:
752
+ """Show only the value axis of a track panel, and only when `labels` is set.
753
+
754
+ The value axis goes on the side away from the chromosome names: the top
755
+ in a vertical karyogram and the right in a horizontal one. It ticks only
756
+ its outermost round values, so narrow tracks stay legible.
757
+
758
+ Parameters
759
+ ----------
760
+ panel : matplotlib.axes.Axes
761
+ Track panel.
762
+ orientation : {"horizontal", "vertical"}
763
+ Direction of the chromosomes.
764
+ labels : bool
765
+ Whether this panel shows the value axis.
766
+
767
+ Examples
768
+ --------
769
+ >>> import matplotlib.pyplot as plt
770
+ >>> fig, panel = plt.subplots()
771
+ >>> style_track(panel, "vertical", labels=True)
772
+ >>> panel.xaxis.get_ticks_position()
773
+ 'top'
774
+ """
775
+ if orientation == "vertical":
776
+ along, value = panel.yaxis, panel.xaxis
777
+ value.tick_top()
778
+ else:
779
+ along, value = panel.xaxis, panel.yaxis
780
+ value.tick_right()
781
+ along.set_visible(False)
782
+ value.set_major_locator(_OuterTicks())
783
+ value.set_visible(labels)
784
+ value.set_tick_params(labelsize="x-small", length=2)
785
+ panel.patch.set_visible(False)
786
+ for spine in panel.spines.values():
787
+ spine.set_visible(False)