clone2vec 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.
clone2vec/plotting.py ADDED
@@ -0,0 +1,3540 @@
1
+ from __future__ import annotations
2
+ from typing import Literal
3
+ from collections.abc import Iterable
4
+
5
+ import scanpy as sc
6
+ import numpy as np
7
+ import pandas as pd
8
+ import seaborn as sns
9
+ import scipy.sparse as sp
10
+
11
+ import matplotlib
12
+ import matplotlib.pyplot as plt
13
+
14
+ logg = sc.logging
15
+
16
+ # Curate public API for tab-completion: only plotting functions
17
+ __all__ = [
18
+ "group_scatter",
19
+ "group_kde",
20
+ "loss_history",
21
+ "clone_size",
22
+ "nesting_clones",
23
+ "volcano",
24
+ "shap_volcano",
25
+ "barplot",
26
+ "heatmap",
27
+ "catboost_perfomance",
28
+ "clones2cells",
29
+ "predictors_comparison",
30
+ "graph",
31
+ "group_connectivity",
32
+ "embedding_axis",
33
+ "small_cbar",
34
+ "fancy_legend",
35
+ "scaled_dotplot",
36
+ "scatter2vars",
37
+ "pca_loadings",
38
+ ]
39
+
40
+ def __dir__():
41
+ return sorted(__all__)
42
+
43
+ def pca_loadings(
44
+ adata: sc.AnnData,
45
+ key: str = "gPCs",
46
+ comp: int = 0,
47
+ n_genes: int = 5,
48
+ kind: Literal["h", "v"] = "v",
49
+ ax: matplotlib.axes.Axes | None = None,
50
+ show: bool = True,
51
+ return_fig: bool = False,
52
+ title: str | None = None,
53
+ full_border: bool = False,
54
+ figsize: tuple[float, float] | None = None,
55
+ ) -> matplotlib.axes.Axes | matplotlib.figure.Figure | None:
56
+ """
57
+ Plot PCA loadings for a given component.
58
+
59
+ Parameters
60
+ ----------
61
+ adata: sc.AnnData
62
+ Annotated data matrix.
63
+ key: str
64
+ Key for PCA loadings in `adata.varm`.
65
+ comp: int
66
+ Component to plot.
67
+ n_genes: int
68
+ Number of genes to plot.
69
+ kind: Literal["h", "v"]
70
+ Kind of plot, either "h" for horizontal or "v" for vertical.
71
+ ax: matplotlib.axes.Axes | None
72
+ Axes object to plot on.
73
+ show: bool
74
+ Whether to show the plot.
75
+ return_fig: bool
76
+ Whether to return the figure object.
77
+ title: str | None
78
+ Title for the plot.
79
+ full_border: bool
80
+ Whether to draw full border around the plot.
81
+ figsize: tuple[float, float] | None
82
+ Figure size.
83
+
84
+ Returns
85
+ -------
86
+ ax: matplotlib.axes.Axes | None
87
+ Axes object with the plot.
88
+ """
89
+ loadings = pd.Series(adata.varm[key][:, comp], index=adata.var_names).sort_values()
90
+ loadings = pd.concat([loadings[:n_genes], loadings[-n_genes:]])
91
+
92
+ if figsize is None:
93
+ figsize = (4, 4)
94
+
95
+ if ax:
96
+ show = False
97
+ return_ax = False
98
+ else:
99
+ fig, ax = plt.subplots(figsize=figsize)
100
+ if show:
101
+ return_ax = False
102
+ else:
103
+ return_ax = True
104
+
105
+ if title is None:
106
+ if key == "gPCs":
107
+ title = f"gPC{comp + 1} loadings"
108
+ elif key == "PCs":
109
+ title = f"PC{comp + 1} loadings"
110
+ else:
111
+ title = f"{key}{comp} loadings"
112
+
113
+ barplot(
114
+ loadings,
115
+ cmap="RdBu_r",
116
+ kind=kind,
117
+ vmax=np.abs(loadings).max(),
118
+ vmin=-np.abs(loadings).max(),
119
+ left_spines=True,
120
+ bottom_spines=True,
121
+ top_spines=full_border,
122
+ right_spines=full_border,
123
+ title=title,
124
+ arrow=([] if full_border else None),
125
+ ax=ax,
126
+ show=False,
127
+ return_fig=False,
128
+ )
129
+
130
+ if return_fig:
131
+ return fig
132
+ elif return_ax:
133
+ return ax
134
+ elif show:
135
+ plt.show()
136
+
137
+
138
+ def group_connectivity(
139
+ adata: sc.AnnData,
140
+ basis: str = "X_umap",
141
+ color_bg: bool = False,
142
+ alpha_bg: float = 0.5,
143
+ s_bg: float | None = None,
144
+ clip: tuple[float, float] = (1, 2),
145
+ ax: matplotlib.axes.Axes | None = None,
146
+ return_fig: bool = False,
147
+ uns_key: str = "group_connectivity",
148
+ title: str | None = None,
149
+ show: bool = True,
150
+ linewidth: float = 1.,
151
+ figsize: tuple[float, float] | None = None,
152
+ ) -> matplotlib.axes.Axes | matplotlib.figure.Figure | None:
153
+ """
154
+ Plot group connectivity on top of the embedding.
155
+
156
+ Parameters
157
+ ----------
158
+ adata: sc.AnnData
159
+ Annotated data matrix.
160
+ basis: str
161
+ Key for embedding coordinates in `adata.obsm`.
162
+ color_bg: bool
163
+ Whether to color the background points.
164
+ alpha_bg: float
165
+ Alpha value for the background points.
166
+ s_bg: float | None
167
+ Size of the background points.
168
+ clip: tuple[float, float]
169
+ Clip values for the connectivity matrix.
170
+ ax: matplotlib.axes.Axes | None
171
+ Axes object to plot on.
172
+ return_fig: bool
173
+ Whether to return the figure object.
174
+ uns_key: str
175
+ Key for group connectivity in `adata.uns`.
176
+ title: str | None
177
+ Title for the plot.
178
+ show: bool
179
+ Whether to show the plot.
180
+ linewidth: float
181
+ Linewidth for the connections.
182
+ figsize: tuple[float, float] | None
183
+ Figure size.
184
+
185
+ Returns
186
+ -------
187
+ ax: matplotlib.axes.Axes | matplotlib.figure.Figure | None
188
+ Axes object with the plot.
189
+ """
190
+ from .utils import get_connectivity_matrix
191
+
192
+ emb = adata.obsm[basis].copy()
193
+ groupby = adata.uns[uns_key]["groupby"]
194
+
195
+ sc.pl._utils.add_colors_for_categorical_sample_annotation(adata, groupby)
196
+ palette = dict(zip(
197
+ adata.obs[groupby].cat.categories,
198
+ adata.uns[f"{groupby}_colors"],
199
+ ))
200
+
201
+ if figsize is None:
202
+ figsize = (4, 4)
203
+
204
+ if ax:
205
+ show = False
206
+ return_ax = False
207
+ else:
208
+ fig, ax = plt.subplots(figsize=figsize)
209
+ if show:
210
+ return_ax = False
211
+ else:
212
+ return_ax = True
213
+
214
+ if not color_bg:
215
+ alpha = 0
216
+ else:
217
+ alpha = alpha_bg
218
+
219
+ if title is None:
220
+ title = f"{groupby} connectivity"
221
+
222
+ sc.pl.embedding(
223
+ adata,
224
+ basis=basis,
225
+ color=groupby,
226
+ ax=ax,
227
+ alpha=alpha,
228
+ show=False,
229
+ s=s_bg,
230
+ title=title,
231
+ )
232
+ if not color_bg:
233
+ sc.pl.embedding(
234
+ adata,
235
+ basis=basis,
236
+ color=None,
237
+ ax=ax,
238
+ show=False,
239
+ alpha=alpha_bg,
240
+ s=s_bg,
241
+ title=title,
242
+ )
243
+
244
+ connectivity = get_connectivity_matrix(adata, uns_key).copy()
245
+ connectivity.values[connectivity.values < clip[0]] = 0
246
+ connectivity.values[connectivity.values > clip[1]] = clip[1]
247
+
248
+ emb = pd.DataFrame(
249
+ emb, index=adata.obs_names, columns=["emb1", "emb2"]
250
+ ).groupby(adata.obs[groupby], observed=True).mean()
251
+ for group in emb.index:
252
+ ax.scatter(
253
+ x=emb.loc[group, "emb1"],
254
+ y=emb.loc[group, "emb2"],
255
+ color=palette[group],
256
+ edgecolor="black",
257
+ linewidth=connectivity.loc[group, group] * linewidth,
258
+ s=50,
259
+ zorder=2,
260
+ )
261
+
262
+ rows, cols = connectivity.values.nonzero()
263
+ for row, col in zip(rows, cols):
264
+ lw = connectivity.values[row, col] * linewidth
265
+ ax.annotate(
266
+ "",
267
+ xytext=(emb.iloc[row]["emb1"], emb.iloc[row]["emb2"]),
268
+ xy=(emb.iloc[col]["emb1"], emb.iloc[col]["emb2"]),
269
+ xycoords="data",
270
+ arrowprops={
271
+ "arrowstyle": "-|>",
272
+ "lw": lw,
273
+ "color": "black",
274
+ "alpha": 1,
275
+ "mutation_scale": 10,
276
+ },
277
+ zorder=1,
278
+ )
279
+
280
+ if return_fig:
281
+ return fig
282
+ elif return_ax:
283
+ return ax
284
+ elif show:
285
+ plt.show()
286
+
287
+
288
+ def graph(
289
+ adata: sc.AnnData,
290
+ graph_key: str = "connectivities",
291
+ basis: str = "X_umap",
292
+ oriented: bool = False,
293
+ ax: matplotlib.axes.Axes | None = None,
294
+ return_fig: bool = False,
295
+ show: bool = False,
296
+ linewidth: float = 1.,
297
+ linecolor: str = "black",
298
+ linealpha: float = 1.,
299
+ arrowstyle: str | None = None,
300
+ mutation_scale: float = 10.,
301
+ width_condition: "Callable" | None = None,
302
+ color_condition: "Callable" | None = None,
303
+ figsize: tuple[float, float] | None = None,
304
+ **kwargs,
305
+ ) -> matplotlib.axes.Axes | matplotlib.figure.Figure | None:
306
+ """
307
+ Draws graph on top of the embedding.
308
+
309
+ Parameters
310
+ ----------
311
+ adata : sc.AnnData
312
+ AnnData object with graph in obsp[graph_key].
313
+ graph_key : str, optional
314
+ Key in obsp to store graph. Default is "connectivities".
315
+ basis : str, optional
316
+ Key in obsm to store embedding. Default is "X_umap".
317
+ oriented : bool, optional
318
+ Whether to draw oriented edges. Default is False.
319
+ ax : matplotlib.axes.Axes, optional
320
+ Axes to draw on. Default is None.
321
+ return_fig : bool, optional
322
+ Whether to return figure. Default is False.
323
+ linewidth : float, optional
324
+ Line width. Default is 1.
325
+ linecolor : str, optional
326
+ Line color. Default is "black".
327
+ linealpha : float, optional
328
+ Line alpha. Default is 1.
329
+ arrowstyle : str, optional
330
+ Arrow style. Default is None.
331
+ mutation_scale : float, optional
332
+ Mutation scale. Default is 10.
333
+ width_condition : Callable, optional
334
+ Function to calculate line width. Default is None.
335
+ color_condition : Callable, optional
336
+ Function to calculate line color. Default is None.
337
+ figsize : tuple[float, float], optional
338
+ Figure size. Default is None.
339
+ **kwargs : dict, optional
340
+ Additional keyword arguments for sc.pl.embedding.
341
+
342
+ Returns
343
+ -------
344
+ matplotlib.axes.Axes | matplotlib.figure.Figure | None
345
+ Draws with the graph on top.
346
+ """
347
+
348
+ if figsize is None:
349
+ figsize = (4, 4)
350
+
351
+ if ax:
352
+ show = False
353
+ return_ax = False
354
+ else:
355
+ fig, ax = plt.subplots(figsize=figsize)
356
+ if show:
357
+ return_ax = False
358
+ else:
359
+ return_ax = True
360
+
361
+ sc.pl.embedding(
362
+ adata,
363
+ basis=basis,
364
+ ax=ax,
365
+ show=False,
366
+ **kwargs,
367
+ )
368
+
369
+ graph = adata.obsp[graph_key]
370
+ if sp.issparse(graph):
371
+ graph = graph.tocoo()
372
+ if sum((graph - graph.T).data >= 1e-10) == 0:
373
+ oriented = False
374
+
375
+ if not oriented:
376
+ graph = sp.triu(graph + graph.T)
377
+
378
+ starts = graph.row
379
+ ends = graph.col
380
+ else:
381
+ if ((graph - graph.T) >= 1e-10).sum() == 0:
382
+ oriented = False
383
+
384
+ if not oriented:
385
+ graph = np.triu(graph + graph.T)
386
+
387
+ starts, ends = graph.nonzero()
388
+
389
+ emb = adata.obsm[basis]
390
+ for start, end in zip(starts, ends):
391
+ x_start, y_start = emb[start, :2]
392
+ x_end, y_end = emb[end, :2]
393
+
394
+ if arrowstyle is None:
395
+ if oriented:
396
+ arrowstyle = "-|>"
397
+ else:
398
+ arrowstyle = "-"
399
+
400
+ if color_condition:
401
+ linecolor = color_condition(adata[start], adata[end])
402
+
403
+ if width_condition:
404
+ linewidth = width_condition(adata[start], adata[end])
405
+
406
+ ax.annotate(
407
+ "",
408
+ xytext=(x_start, y_start),
409
+ xy=(x_end, y_end),
410
+ xycoords="data",
411
+ arrowprops={
412
+ "arrowstyle": arrowstyle,
413
+ "lw": linewidth,
414
+ "color": linecolor,
415
+ "alpha": linealpha,
416
+ "mutation_scale": linewidth * mutation_scale,
417
+ }
418
+ )
419
+
420
+ if return_fig:
421
+ return fig
422
+ elif return_ax:
423
+ return ax
424
+ elif show:
425
+ plt.show()
426
+
427
+ def group_scatter(
428
+ adata: sc.AnnData,
429
+ groupby: str,
430
+ groups: list[str] | str | None = None,
431
+ s: list[float] | float = 30,
432
+ ncols: int = 4,
433
+ group_color: list[str] | str = "black",
434
+ frameon: list[bool] | bool = False,
435
+ square: bool = True,
436
+ kwargs_background: list[dict] | dict | None = None,
437
+ kwargs_group: list[dict] | dict | None = None,
438
+ ax: matplotlib.axes.Axes | list[matplotlib.axes.Axes] | None = None,
439
+ title: list[str] | str = None,
440
+ return_fig: bool = False,
441
+ basis: list[str] | str = "X_umap",
442
+ show: bool = True,
443
+ figsize: tuple[float, float] | None = None,
444
+ ) -> plt.Figure | matplotlib.axes.Axes | np.ndarray | list[matplotlib.axes.Axes] | None:
445
+ """
446
+ Plots the spatial distribution of a single clone on a 2D embedding.
447
+
448
+ First plots all cells as a background, then overlays the selected clone using a distinct color.
449
+
450
+ Parameters
451
+ ----------
452
+ adata : AnnData
453
+ AnnData object with cell metadata and embeddings.
454
+ groupby : str
455
+ Column in `adata.obs` indicating clonal identity.
456
+ groups : list[str] | str | None
457
+ Clones to be highlighted. If None, all groups are shown.
458
+ frameon : list[bool] | bool, optional
459
+ Whether to show axes frame in the plot. Default is False.
460
+ square : bool, optional
461
+ Whether to set the aspect ratio of the plot to be equal. Default is True.
462
+ s : list[float] | float, optional
463
+ Dot size for the highlighted clone. Default is 30.
464
+ kwargs_background : list[dict] | dict | None, optional
465
+ Additional plotting arguments for the background cells.
466
+ kwargs_group : list[dict] | dict | None, optional
467
+ Additional plotting arguments for the highlighted clone.
468
+ group_color : list[str] | str, optional
469
+ Color to use for the highlighted clone. Default is "black".
470
+ ax : matplotlib.axes.Axes | list[matplotlib.axes.Axes] | None, optional
471
+ Axes object to draw the plot on. If None, a new figure is created.
472
+ title : list[str] | str, optional
473
+ Plot title. If None, uses the clone name.
474
+ return_fig : bool, optional
475
+ If True, returns the Matplotlib Figure object. Default is False.
476
+ basis : list[str] | str, optional
477
+ Embedding key in `adata.obsm` to use for coordinates. Default is "X_umap".
478
+ show : bool, optional
479
+ Whether to show the plot. Default is True.
480
+ figsize : tuple[float, float], optional
481
+ Figure size. Default is None.
482
+
483
+ Returns
484
+ -------
485
+ None | matplotlib.figure.Figure | matplotlib.axes.Axes | np.ndarray | list[matplotlib.axes.Axes]
486
+ Returns Figure if `return_fig` is True; otherwise returns None.
487
+ """
488
+ if groups is None:
489
+ try:
490
+ groups = adata.obs[groupby].cat.categories
491
+ except:
492
+ groups = list(set(adata.obs[groupby]))
493
+ if len(groups) > 40:
494
+ raise ValueError("More than 40 groups found in adata.obs[groupby].cat.categories. Please provide a list of groups to plot.")
495
+ if isinstance(groups, str):
496
+ groups = [groups]
497
+ if not isinstance(s, list):
498
+ s = [s] * len(groups)
499
+ elif len(s) != len(groups):
500
+ raise ValueError("s must be a float or a list of floats with length equal to the number of groups")
501
+ if isinstance(group_color, str):
502
+ group_color = [group_color] * len(groups)
503
+ elif len(group_color) != len(groups):
504
+ raise ValueError("group_color must be a str or a list of str with length equal to the number of groups")
505
+ if isinstance(frameon, bool):
506
+ frameon = [frameon] * len(groups)
507
+ elif len(frameon) != len(groups):
508
+ raise ValueError("frameon must be a bool or a list of bool with length equal to the number of groups")
509
+ if kwargs_background is None:
510
+ kwargs_background = [{} for i in range(len(groups))]
511
+ if isinstance(kwargs_background, dict):
512
+ kwargs_background = [kwargs_backgroundcopy() for i in range(len(groups))]
513
+ elif len(kwargs_background) != len(groups):
514
+ raise ValueError("kwargs_background must be a dict or a list of dict with length equal to the number of groups")
515
+ if kwargs_group is None:
516
+ kwargs_group = [{} for i in range(len(groups))]
517
+ if isinstance(kwargs_group, dict):
518
+ kwargs_group = [kwargs_group.copy() for i in range(len(groups))]
519
+ elif len(kwargs_group) != len(groups):
520
+ raise ValueError("kwargs_group must be a dict or a list of dict with length equal to the number of groups")
521
+ if title is None:
522
+ title = [None for i in range(len(groups))]
523
+ elif isinstance(title, str):
524
+ title = [title for i in range(len(groups))]
525
+ elif len(title) != len(groups):
526
+ raise ValueError("title must be a str or a list of str with length equal to the number of groups")
527
+ if isinstance(basis, str):
528
+ basis = [basis] * len(groups)
529
+ elif len(basis) != len(groups):
530
+ raise ValueError("basis must be a str or a list of str with length equal to the number of groups")
531
+
532
+ ncols = min(len(groups), ncols)
533
+ nrows = len(groups) // ncols
534
+ if len(groups) % ncols != 0:
535
+ nrows += 1
536
+
537
+ if figsize is None:
538
+ figsize = (3.5 * ncols, 3.5 * nrows)
539
+
540
+ if ax:
541
+ show = False
542
+ return_ax = False
543
+ tight_layout = False
544
+ fig = None
545
+ axes = ax
546
+ else:
547
+ fig, axes = plt.subplots(nrows=nrows, ncols=ncols, figsize=figsize)
548
+ tight_layout = True
549
+ if show:
550
+ return_ax = False
551
+ else:
552
+ return_ax = True
553
+
554
+ if isinstance(axes, matplotlib.axes.Axes):
555
+ axes_grid = np.array([[axes]])
556
+ else:
557
+ axes_arr = np.array(axes, dtype=object)
558
+ if axes_arr.ndim == 0:
559
+ axes_grid = np.array([[axes_arr.item()]])
560
+ elif axes_arr.ndim == 1:
561
+ total = nrows * ncols
562
+ if axes_arr.size < total:
563
+ raise ValueError("Provided axes contain fewer panels than required for the number of groups")
564
+ axes_grid = axes_arr.flat[:total].reshape(nrows, ncols)
565
+ elif axes_arr.ndim >= 2:
566
+ total = nrows * ncols
567
+ if axes_arr.size < total:
568
+ raise ValueError("Provided axes contain fewer panels than required for the number of groups")
569
+ axes_grid = axes_arr.flat[:total].reshape(nrows, ncols)
570
+ else:
571
+ raise TypeError("ax must be an Axes, a list/array of Axes, or None")
572
+
573
+ for i in range(len(groups)):
574
+ col = i % ncols
575
+ row = i // ncols
576
+ ax_i = axes_grid[row, col]
577
+
578
+ sc.pl.embedding(
579
+ adata,
580
+ basis=basis[i],
581
+ ax=ax_i,
582
+ show=False,
583
+ frameon=frameon[i],
584
+ **kwargs_background[i]
585
+ )
586
+
587
+ if "s" not in kwargs_group[i]:
588
+ kwargs_group[i]["s"] = s[i]
589
+
590
+ if title[i] is None:
591
+ title[i] = str(groups[i])
592
+
593
+ if "title" not in kwargs_group[i]:
594
+ if "color" not in kwargs_group[i]:
595
+ kwargs_group[i]["title"] = title[i]
596
+ else:
597
+ kwargs_group[i]["title"] = title[i] + "\n(" + kwargs_group[i]["color"] + ")"
598
+
599
+ if "color" in kwargs_group[i]:
600
+ if kwargs_group[i]["color"] in adata.obs.columns:
601
+ if not pd.api.types.is_numeric_dtype(adata.obs[kwargs_group[i]["color"]]):
602
+ adata.obs[kwargs_group[i]["color"]] = adata.obs[kwargs_group[i]["color"]].astype("category")
603
+ sc.pl._utils.add_colors_for_categorical_sample_annotation(adata, kwargs_group[i]["color"])
604
+
605
+ sc.pl.embedding(
606
+ adata[adata.obs[groupby] == groups[i]],
607
+ basis=basis[i],
608
+ ax=ax_i,
609
+ show=False,
610
+ frameon=frameon[i],
611
+ na_color=group_color[i],
612
+ **kwargs_group[i],
613
+ )
614
+
615
+ if square:
616
+ try:
617
+ ax_i.set_aspect("equal", "box")
618
+ except Exception:
619
+ ax_i.set_aspect("equal")
620
+
621
+ for i in range(len(groups), ncols * nrows):
622
+ axes_grid[i // ncols, i % ncols].axis("off")
623
+
624
+ if tight_layout:
625
+ fig.tight_layout()
626
+
627
+ if return_fig:
628
+ return fig
629
+ elif return_ax:
630
+ return axes_grid.flat[:len(groups)]
631
+ elif show:
632
+ plt.show()
633
+
634
+
635
+ def group_kde(
636
+ adata: sc.AnnData,
637
+ groupby: str,
638
+ groups: list[str] | str | None = None,
639
+ basis: str | list[str] = "X_umap",
640
+ bw_method: list[float | str] | float | str = 0.15,
641
+ ncols: int = 4,
642
+ frameon: list[bool] | bool = False,
643
+ square: bool = True,
644
+ ax: matplotlib.axes.Axes | list[matplotlib.axes.Axes] | None = None,
645
+ return_fig: bool = False,
646
+ cmap: list[matplotlib.colors.Colormap | str] | matplotlib.colors.Colormap | str = "Reds",
647
+ title: list[str] | str | None = None,
648
+ kwargs: list[dict] | dict | None = None,
649
+ show: bool = True,
650
+ figsize: tuple[float, float] | None = None,
651
+ ) -> plt.Figure | matplotlib.axes.Axes | np.ndarray | list[matplotlib.axes.Axes] | None:
652
+ """
653
+ Plots kernel density estimates (KDE) of cells from one or multiple groups on a 2D embedding.
654
+
655
+ Uses `scipy.stats.gaussian_kde` to estimate density of a group and overlays it as a contour plot.
656
+
657
+ Parameters
658
+ ----------
659
+ adata : AnnData
660
+ AnnData object containing embeddings and group annotations.
661
+ groupby : str
662
+ Column in `adata.obs` used to identify cell groups.
663
+ groups : list[str] | str | None
664
+ Specific group(s) to visualize.
665
+ basis : str, optional
666
+ Embedding key from `adata.obsm` to use. Default is "X_umap".
667
+ bw_method : list[float | str] | float | str, optional
668
+ Bandwidth for the KDE. Passed to `scipy.stats.gaussian_kde`. Can be a single value or a list per group. Default is 0.1.
669
+ ncols : int, optional
670
+ Number of columns in the subplot grid when plotting multiple groups. Default is 4.
671
+ square : bool, optional
672
+ Whether to set the aspect ratio of the plot to be equal. Default is True.
673
+ frameon : list[bool] | bool, optional
674
+ Whether to show axes frame for each subplot. Can be a single bool or a list per group. Default is False.
675
+ ax : matplotlib.axes.Axes | list[matplotlib.axes.Axes] | None, optional
676
+ Axes object(s) to draw the plot on. If None, a new figure/grid is created.
677
+ return_fig : bool, optional
678
+ If True, returns the Matplotlib Figure object. Default is False.
679
+ cmap : list[ColorMap | str] | ColorMap | str, optional
680
+ Colormap(s) to use for KDE overlay. Can be a single value or a list per group. Default is "Reds".
681
+ title : list[str] | str | None, optional
682
+ Plot title(s). If None, uses "{group} KDE".
683
+ kwargs : list[dict] | dict | None, optional
684
+ Additional arguments passed to `sc.pl.embedding` for the background. Can be a single dict or a list per group.
685
+ show : bool, optional
686
+ Whether to show the plot. Default is True.
687
+ figsize : tuple[float, float] | None, optional
688
+ Figure size. Default is None.
689
+
690
+ Returns
691
+ -------
692
+ None | matplotlib.figure.Figure | matplotlib.axes.Axes | np.ndarray | list[matplotlib.axes.Axes]
693
+ Returns Figure if `return_fig` is True; otherwise returns None or axes.
694
+ """
695
+ from scipy.stats import gaussian_kde
696
+ from matplotlib.colors import ListedColormap
697
+
698
+ # Resolve groups for backward compatibility
699
+ if groups is None:
700
+ try:
701
+ groups = adata.obs[groupby].cat.categories
702
+ except:
703
+ groups = list(set(adata.obs[groupby]))
704
+ if len(groups) > 40:
705
+ raise ValueError("More than 40 groups found in adata.obs[groupby].cat.categories. Please provide a list of groups to plot.")
706
+
707
+ if isinstance(groups, str):
708
+ groups = [groups]
709
+ if groups is None or len(groups) == 0:
710
+ raise ValueError("At least one group must be specified via `group` or `groups`.")
711
+
712
+ # Normalize per-group parameters
713
+ if isinstance(frameon, bool):
714
+ frameon = [frameon] * len(groups)
715
+ elif len(frameon) != len(groups):
716
+ raise ValueError("frameon must be a bool or a list[bool] with length equal to number of groups")
717
+
718
+ if isinstance(basis, str):
719
+ basis = [basis] * len(groups)
720
+ elif len(basis) != len(groups):
721
+ raise ValueError("basis must be a str or a list[str] with length equal to number of groups")
722
+
723
+ if isinstance(bw_method, (float, str)):
724
+ bw_method = [bw_method] * len(groups)
725
+ elif len(bw_method) != len(groups):
726
+ raise ValueError("bw_method must be a scalar or a list with length equal to number of groups")
727
+
728
+ if kwargs is None:
729
+ kwargs = [{} for _ in range(len(groups))]
730
+ elif isinstance(kwargs, dict):
731
+ kwargs = [kwargs.copy() for _ in range(len(groups))]
732
+ elif len(kwargs) != len(groups):
733
+ raise ValueError("kwargs must be a dict or a list[dict] with length equal to number of groups")
734
+
735
+ if title is None:
736
+ title = [None for _ in range(len(groups))]
737
+ elif isinstance(title, str):
738
+ title = [title for _ in range(len(groups))]
739
+ elif len(title) != len(groups):
740
+ raise ValueError("title must be a str or a list[str] with length equal to number of groups")
741
+
742
+ if not isinstance(cmap, list):
743
+ cmap = [cmap for _ in range(len(groups))]
744
+ elif len(cmap) != len(groups):
745
+ raise ValueError("cmap must be a single colormap or a list with length equal to number of groups")
746
+
747
+ # Determine subplot grid
748
+ ncols = min(len(groups), ncols)
749
+ nrows = len(groups) // ncols
750
+ if len(groups) % ncols != 0:
751
+ nrows += 1
752
+
753
+ # Create axes grid or normalize provided axes to a 2D grid
754
+ if figsize is None:
755
+ figsize = (3.5 * ncols, 3.5 * nrows)
756
+
757
+ if ax:
758
+ tight_layout = False
759
+ show = False
760
+ return_ax = False
761
+ fig = None
762
+ axes = ax
763
+ else:
764
+ fig, axes = plt.subplots(nrows=nrows, ncols=ncols, figsize=figsize)
765
+ tight_layout = True
766
+ if show:
767
+ return_ax = False
768
+ else:
769
+ return_ax = True
770
+
771
+ # Normalize axes to 2D array shape (nrows, ncols)
772
+ if isinstance(axes, matplotlib.axes.Axes):
773
+ axes_grid = np.array([[axes]])
774
+ else:
775
+ axes_arr = np.array(axes, dtype=object)
776
+ if axes_arr.ndim == 0:
777
+ axes_grid = np.array([[axes_arr.item()]])
778
+ elif axes_arr.ndim == 1:
779
+ total = nrows * ncols
780
+ if axes_arr.size < total:
781
+ raise ValueError("Provided axes contain fewer panels than required for the number of groups")
782
+ axes_grid = axes_arr.flat[:total].reshape(nrows, ncols)
783
+ elif axes_arr.ndim >= 2:
784
+ total = nrows * ncols
785
+ if axes_arr.size < total:
786
+ raise ValueError("Provided axes contain fewer panels than required for the number of groups")
787
+ axes_grid = axes_arr.flat[:total].reshape(nrows, ncols)
788
+ else:
789
+ raise TypeError("ax must be an Axes, a list/array of Axes, or None")
790
+
791
+ # For each group, draw background and overlay KDE if enough points
792
+ for i in range(len(groups)):
793
+ grp = groups[i]
794
+ ax_i = axes_grid[i // ncols, i % ncols]
795
+
796
+ if title[i] is None:
797
+ title[i] = f"{grp} KDE"
798
+
799
+ kwargs_i = dict(kwargs[i])
800
+ if "title" not in kwargs_i:
801
+ kwargs_i["title"] = title[i]
802
+
803
+ if "frameon" in kwargs_i:
804
+ pass
805
+ else:
806
+ kwargs_i["frameon"] = frameon[i]
807
+ if "na_color" not in kwargs_i:
808
+ kwargs_i["na_color"] = "black"
809
+
810
+ if sum(adata.obs[groupby] == grp) < 5:
811
+ logg.warning(f"Group {grp} has less than 5 points. Skipping KDE plot.")
812
+ sc.pl.embedding(
813
+ adata,
814
+ basis=basis[i],
815
+ ax=ax_i,
816
+ show=False,
817
+ **kwargs_i,
818
+ )
819
+ else:
820
+ kernel = gaussian_kde(
821
+ adata[adata.obs[groupby] == grp].obsm[basis[i]].T,
822
+ bw_method=bw_method[i],
823
+ )
824
+
825
+ xmin = min(adata.obsm[basis[i]].T[0])
826
+ xmax = max(adata.obsm[basis[i]].T[0])
827
+ ymin = min(adata.obsm[basis[i]].T[1])
828
+ ymax = max(adata.obsm[basis[i]].T[1])
829
+
830
+ xx, yy = np.mgrid[xmin:xmax:100j, ymin:ymax:100j]
831
+ positions = np.vstack([xx.ravel(), yy.ravel()])
832
+ f = np.reshape(kernel(positions).T, xx.shape)
833
+
834
+ cmap_i = cmap[i]
835
+ if not isinstance(cmap_i, ListedColormap):
836
+ try:
837
+ cmap_i = matplotlib.colormaps[cmap_i]
838
+ except Exception:
839
+ logg.warning(f"Invalid colormap name {cmap[i]}. Using default Reds.")
840
+ cmap_i = matplotlib.colormaps["Reds"]
841
+
842
+ my_cmap = cmap_i(np.arange(cmap_i.N))
843
+ alphas = np.linspace(0, 1, cmap_i.N)
844
+ BG = np.asarray([1., 1., 1.,])
845
+ for j in range(cmap_i.N):
846
+ my_cmap[j, :-1] = my_cmap[j, :-1] * alphas[j] + BG * (1. - alphas[j])
847
+ my_cmap = ListedColormap(my_cmap)
848
+
849
+ sc.pl.embedding(
850
+ adata,
851
+ basis=basis[i],
852
+ ax=ax_i,
853
+ show=False,
854
+ **kwargs_i,
855
+ )
856
+ ax_i.contour(xx, yy, f, colors="black", linewidths=1)
857
+ ax_i.contourf(xx, yy, f, cmap=my_cmap, alpha=0.8)
858
+ ax_i.set_title(title[i])
859
+
860
+ if square:
861
+ try:
862
+ ax_i.set_aspect("equal", "box")
863
+ except Exception:
864
+ ax_i.set_aspect("equal")
865
+
866
+ for i in range(len(groups), ncols * nrows):
867
+ axes_grid[i // ncols, i % ncols].axis("off")
868
+
869
+ if tight_layout:
870
+ fig.tight_layout()
871
+
872
+ if return_fig:
873
+ return fig
874
+ elif return_ax:
875
+ return axes_grid.flat[:len(groups)]
876
+ elif show:
877
+ plt.show()
878
+
879
+ def loss_history(
880
+ clones: sc.AnnData,
881
+ uns_key: str = "clone2vec",
882
+ return_fig: bool = False,
883
+ loss_key: str = "loss_history",
884
+ show: bool = True,
885
+ figsize: tuple[float, float] | None = None,
886
+ ax: list[matplotlib.axes.Axes] | None = None,
887
+ ) -> plt.Figure | list[matplotlib.axes.Axes] | None:
888
+ """
889
+ Plot the mean loss per epoch and its change across epochs during clone2vec training.
890
+
891
+ Parameters
892
+ ----------
893
+ clones : AnnData
894
+ Annotated data matrix containing training statistics in `clones.uns`.
895
+ uns_key : str, optional
896
+ Key in `clones.uns` that stores a list of mean losses per epoch.
897
+ Default is "c2v_loss_history".
898
+ loss_key : str, optional
899
+ Key in `clones.uns[uns_key]` that stores a list of mean losses per epoch.
900
+ Default is "loss_history".
901
+ return_fig : bool, optional
902
+ If True, returns the Matplotlib Figure object. Default is False.
903
+ show : bool, optional
904
+ If True, shows the plot. Default is True.
905
+ figsize : tuple[float, float] | None, optional
906
+ Figure size. Default is None.
907
+ ax : list[matplotlib.axes.Axes] | None, optional
908
+ List of axes to plot on. Default is None.
909
+
910
+ Returns
911
+ -------
912
+ None or matplotlib.figure.Figure or list[matplotlib.axes.Axes]
913
+ The plot figure if `return_fig` is True, or axes if `return_ax` is True, otherwise None.
914
+
915
+ Raises
916
+ -------
917
+ KeyError
918
+ If `uns_key` is not present in `clones.uns`.
919
+ """
920
+ if figsize is None:
921
+ figsize = (8, 3)
922
+
923
+ if ax:
924
+ show = False
925
+ return_ax = False
926
+ axes = ax
927
+ if isinstance(axes, (list, np.ndarray)):
928
+ if len(axes) < 2:
929
+ # Fallback or error? Assuming user knows what they are doing if passing axes
930
+ pass
931
+ fig = axes[0].figure
932
+ else:
933
+ # Should be a list
934
+ axes = [ax, ax] # This might be wrong, but better than crashing if user passes one ax
935
+ fig = ax.figure
936
+ else:
937
+ fig, axes = plt.subplots(ncols=2, figsize=figsize)
938
+ if show:
939
+ return_ax = False
940
+ else:
941
+ return_ax = True
942
+
943
+ try:
944
+ loss = np.array(clones.uns[uns_key][loss_key])
945
+ except KeyError:
946
+ try:
947
+ loss = np.array(clones.uns["clone2vec"][loss_key])
948
+ logg.warning(f"uns_key {uns_key} not found in clones.uns. Using clone2vec[{loss_key}] instead.")
949
+ except KeyError:
950
+ try:
951
+ loss = np.array(clones.uns["clone2vec_Poi"][loss_key])
952
+ logg.warning(f"Neither {uns_key} nor clone2vec[{loss_key}] found in clones.uns. Using clone2vec_Poi[{loss_key}] instead.")
953
+ except KeyError:
954
+ raise KeyError(f"uns_key {uns_key}, clone2vec[{loss_key}], and clone2vec_Poi[{loss_key}] not found in clones.uns.")
955
+
956
+ sns.lineplot(
957
+ x=range(len(loss)),
958
+ y=loss,
959
+ ax=axes[0],
960
+ )
961
+
962
+ axes[0].set_xlabel("Number of epoch")
963
+ axes[0].set_ylabel("Mean loss")
964
+ axes[0].grid(alpha=0.3)
965
+
966
+ sns.lineplot(
967
+ x=range(len(loss) - 1),
968
+ y=loss[:-1] - loss[1:],
969
+ ax=axes[1],
970
+ )
971
+
972
+ axes[1].set_xlabel("Number of epoch")
973
+ axes[1].set_ylabel("Δ(Mean loss)")
974
+ axes[1].grid(alpha=0.3)
975
+ axes[1].set_yscale("log")
976
+
977
+ fig.tight_layout()
978
+
979
+ if return_fig:
980
+ return fig
981
+ elif return_ax:
982
+ return axes
983
+ elif show:
984
+ plt.show()
985
+
986
+ def clone_size(
987
+ clones: sc.AnnData,
988
+ return_fig: bool = False,
989
+ title: str = "Clone size distribution",
990
+ bins: int = 30,
991
+ log: bool = True,
992
+ alpha: float = 1,
993
+ edgecolor: str = "black",
994
+ show: bool = True,
995
+ figsize: tuple[float, float] | None = None,
996
+ ax: list[matplotlib.axes.Axes] | None = None,
997
+ ) -> plt.Figure | list[matplotlib.axes.Axes] | None:
998
+ """
999
+ Plot basic statistics of clone size distribution.
1000
+
1001
+ Parameters
1002
+ ----------
1003
+ clones : AnnData
1004
+ Annotated data matrix containing clone size stat in clones.obs["n_cells"]
1005
+ return_fig : bool, optional
1006
+ If True, returns the Matplotlib Figure object. Default is False.
1007
+ title : str, optional
1008
+ Title of the plot. Default is "Clone size distribution".
1009
+ show : bool, optional
1010
+ Whether to show the plot. Default is True.
1011
+ figsize : tuple[float, float] | None, optional
1012
+ Figure size. Default is None.
1013
+ ax : list[matplotlib.axes.Axes] | None, optional
1014
+ List of axes to plot on. Default is None.
1015
+
1016
+ Returns
1017
+ -------
1018
+ None or matplotlib.figure.Figure or list[matplotlib.axes.Axes]
1019
+ The plot figure if `return_fig` is True, or axes if `return_ax` is True, otherwise None.
1020
+
1021
+ Notes
1022
+ -----
1023
+ Single-cell clone annotations with only one occurrence (clone size = 1) are excluded
1024
+ from both plots.
1025
+ """
1026
+ if figsize is None:
1027
+ figsize = (8, 4)
1028
+
1029
+ if ax:
1030
+ show = False
1031
+ return_ax = False
1032
+ axes = ax
1033
+ if isinstance(axes, (list, np.ndarray)):
1034
+ if len(axes) < 2:
1035
+ pass
1036
+ fig = axes[0].figure
1037
+ else:
1038
+ axes = [ax, ax]
1039
+ fig = ax.figure
1040
+ else:
1041
+ fig, axes = plt.subplots(ncols=2, figsize=figsize)
1042
+ if show:
1043
+ return_ax = False
1044
+ else:
1045
+ return_ax = True
1046
+
1047
+ sns.histplot(
1048
+ clones.obs["n_cells"],
1049
+ bins=bins,
1050
+ log=log,
1051
+ alpha=alpha,
1052
+ edgecolor=edgecolor,
1053
+ ax=axes[0],
1054
+ )
1055
+ axes[0].grid(alpha=0.3)
1056
+ axes[0].set_xlabel("Clone size")
1057
+ axes[0].set_ylabel("Number of clones")
1058
+
1059
+ size_dist = clones.obs["n_cells"].value_counts().sort_index()
1060
+
1061
+ sns.lineplot(np.cumsum(size_dist[::-1]), ax=axes[1])
1062
+ axes[1].grid(alpha=0.3)
1063
+ if log:
1064
+ axes[1].set_xscale("log")
1065
+ axes[1].set_xlabel("Clone size")
1066
+ axes[1].set_ylabel("Number of clones bigger than this")
1067
+
1068
+ plt.suptitle(title)
1069
+ fig.tight_layout()
1070
+
1071
+ if return_fig:
1072
+ return fig
1073
+ elif return_ax:
1074
+ return axes
1075
+ elif show:
1076
+ plt.show()
1077
+
1078
+ def nesting_clones(
1079
+ adata: sc.AnnData,
1080
+ early_injection: str,
1081
+ late_injection: str,
1082
+ min_clone_size: int = 5,
1083
+ non_clonal_str: str = "NA",
1084
+ show: bool = True,
1085
+ figsize: tuple[float, float] | None = None,
1086
+ ax: matplotlib.axes.Axes | None = None,
1087
+ return_fig: bool = False,
1088
+ ) -> plt.Figure | matplotlib.axes.Axes | None:
1089
+ """
1090
+ Plot ternary composition of clones labeled by two different injections.
1091
+
1092
+ In ideal clonal reconstructions, smaller clones from a later injection
1093
+ should nest within larger clones from an earlier injection — resembling
1094
+ a "Russian doll" pattern. This function visualizes the composition of
1095
+ shared and unique cells across early and late injections using a ternary plot.
1096
+
1097
+ Parameters
1098
+ ----------
1099
+ adata : AnnData
1100
+ Annotated data matrix with clonal labels in `.obs`.
1101
+ early_injection : str
1102
+ Column name in `.obs` containing clone IDs from the early injection.
1103
+ late_injection : str
1104
+ Column name in `.obs` containing clone IDs from the late injection.
1105
+ min_clone_size : int, optional
1106
+ Minimum number of cells required for a clone to be included in the plot.
1107
+ Default is 5.
1108
+ non_clonal_str : str, optional
1109
+ Value representing unlabelled or non-clonal cells. Default is "NA".
1110
+ show : bool, optional
1111
+ Whether to show the plot. Default is True.
1112
+ figsize : tuple[float, float] | None, optional
1113
+ Figure size. Default is None.
1114
+ return_fig : bool, optional
1115
+ Whether to return the figure. Default is False.
1116
+
1117
+ Returns
1118
+ -------
1119
+ None or matplotlib.figure.Figure or matplotlib.axes.Axes
1120
+ Returns Figure if `return_fig` is True, or ax if `return_ax` is True.
1121
+ """
1122
+ try:
1123
+ import mpltern
1124
+ except ImportError:
1125
+ raise ImportError("`mpltern` is required for nesting_clones. Please install it via pip: `pip install mpltern`.")
1126
+
1127
+ possible_combinations = adata.obs[[
1128
+ early_injection, late_injection,
1129
+ ]][(adata.obs[[early_injection, late_injection]] != non_clonal_str).sum(axis=1) == 2]
1130
+ possible_combinations = list(set([(i, j) for i, j in possible_combinations.values]))
1131
+
1132
+ early_clone_sizes = []
1133
+ late_clone_sizes = []
1134
+ di_clone_sizes = []
1135
+
1136
+ for early_clone, late_clone in possible_combinations:
1137
+ early = sum(adata.obs[early_injection] == early_clone)
1138
+ late = sum(adata.obs[late_injection] == late_clone)
1139
+ both = sum((adata.obs[late_injection] == late_clone) & (adata.obs[early_injection] == early_clone))
1140
+ if (early >= min_clone_size) and (late >= min_clone_size):
1141
+ early_clone_sizes.append(early - both)
1142
+ late_clone_sizes.append(late - both)
1143
+ di_clone_sizes.append(both)
1144
+
1145
+ if figsize is None:
1146
+ figsize = (4, 4)
1147
+
1148
+ fig, ax = plt.subplots(figsize=figsize, subplot_kw={'projection': 'ternary', 'ternary_sum': 100})
1149
+ if show:
1150
+ return_ax = False
1151
+ else:
1152
+ return_ax = True
1153
+
1154
+ ax.set_tlabel("Both barcodes (%)")
1155
+ ax.set_llabel("Early barcode (%)")
1156
+ ax.set_rlabel("Late barcode (%)")
1157
+
1158
+ # Order = top, left, right
1159
+ ax.scatter(
1160
+ di_clone_sizes,
1161
+ early_clone_sizes,
1162
+ late_clone_sizes,
1163
+ s=10,
1164
+ color="grey",
1165
+ edgecolor="k",
1166
+ linewidth=0.5,
1167
+ )
1168
+
1169
+ ax.grid(alpha=0.3)
1170
+
1171
+ ax.set_tlim(-3, 103)
1172
+ ax.set_llim(-3, 103)
1173
+ ax.set_rlim(-3, 103)
1174
+
1175
+ if return_fig:
1176
+ return fig
1177
+ elif return_ax:
1178
+ return ax
1179
+ elif show:
1180
+ plt.show()
1181
+
1182
+ def volcano(
1183
+ pvals: pd.Series | list = None,
1184
+ logfcs: pd.Series | list = None,
1185
+ names: pd.Series | list | None = None,
1186
+ adj_p: bool = False,
1187
+ lg_p: bool = True,
1188
+ ax: matplotlib.axes.Axes | None = None,
1189
+ return_fig: bool = False,
1190
+ draw_p_threshold: bool = True,
1191
+ pval_threshold: float | None = 0.05,
1192
+ draw_logfc_threshold: bool = True,
1193
+ logfc_threshold: float | None = 1.0,
1194
+ n_highlite: int = 5,
1195
+ highlite_names: list | None = None,
1196
+ background_scatter_kws: dict | None = None,
1197
+ lines_kws: dict | None = None,
1198
+ scatters_kws: dict | None = None,
1199
+ pval_line_kws: dict | None = None,
1200
+ pval_scatter_kws: dict | None = None,
1201
+ logfc_scatter_kws: dict | None = None,
1202
+ logfc_scatter_kws_left: dict | None = None,
1203
+ logfc_scatter_kws_right: dict | None = None,
1204
+ logfc_line_kws: dict | None = None,
1205
+ logfc_line_kws_left: dict | None = None,
1206
+ logfc_line_kws_right: dict | None = None,
1207
+ pval_logfc_scatter_kws: dict | None = None,
1208
+ pval_logfc_scatter_kws_left: dict | None = None,
1209
+ pval_logfc_scatter_kws_right: dict | None = None,
1210
+ highlite_scatter_kws: dict | None = None,
1211
+ highlite_scatter_kws_right: dict | None = None,
1212
+ highlite_scatter_kws_left: dict | None = None,
1213
+ text_kws: dict | None = None,
1214
+ text_kws_right: dict | None = None,
1215
+ text_kws_left: dict | None = None,
1216
+ xlim: tuple[float, float] | None = None,
1217
+ ylim: tuple[float, float] | None = None,
1218
+ title: str | None = "Volcano plot",
1219
+ xlabel: str | None = None,
1220
+ ylabel: str | None = None,
1221
+ grid: bool = True,
1222
+ rasterize: bool = True,
1223
+ show: bool = True,
1224
+ figsize: tuple[float, float] | None = None,
1225
+ ) -> plt.Figure | matplotlib.axes.Axes | None:
1226
+ """
1227
+ Draw a volcano using provided p-values and logFCs.
1228
+
1229
+ Parameters
1230
+ ----------
1231
+ pvals : pd.Series | list
1232
+ P-values for each gene.
1233
+ logfcs : pd.Series | list
1234
+ Log2 fold changes for each gene.
1235
+ names : pd.Series | list | None, optional
1236
+ Gene names corresponding to p-values and logFCs. If None, indices are used (if provided).
1237
+ If not provided, no gene names are shown. Default is None.
1238
+ adj_p : bool, optional
1239
+ Whether p-values are adjusted (used to label the Y-axis). Default is False.
1240
+ lg_p : bool, optional
1241
+ Whether to use -log10(p) scale. If False, the function expects -log10(p) in pvals.
1242
+ Default is True.
1243
+ ax : matplotlib.axes.Axes | None, optional
1244
+ Axes to draw the volcano on. Default is None.
1245
+ return_fig : bool, optional
1246
+ Whether to return the figure. Default is False.
1247
+ draw_p_threshold : bool, optional
1248
+ Whether to draw the p-value threshold line. Default is True.
1249
+ pval_threshold : float | None, optional
1250
+ P-value threshold for significance. Default is 0.05.
1251
+ draw_logfc_threshold : bool, optional
1252
+ Whether to draw the logFC threshold lines. Default is True.
1253
+ logfc_threshold : float | None, optional
1254
+ Log2 fold change threshold for significance. Default is 1.0.
1255
+ n_highlite : int, optional
1256
+ Number of top genes to highlight from each side. Default is 5.
1257
+ highlite_names : list | None, optional
1258
+ List of gene names to highlight in addition to top-DE genes. Default is None.
1259
+ background_scatter_kws : dict | None, optional
1260
+ Keyword arguments for background (p > pval_threshold and |logFC| < logfc_threshold) scatter plot. Default is None.
1261
+ lines_kws : dict | None, optional
1262
+ Keyword arguments for all lines. Default is None.
1263
+ scatters_kws : dict | None, optional
1264
+ Keyword arguments for all scatters. Default is None.
1265
+ pval_line_kws : dict | None, optional
1266
+ Keyword arguments for p-value threshold line. Default is None.
1267
+ pval_scatter_kws : dict | None, optional
1268
+ Keyword arguments for p-value threshold scatter. Default is None.
1269
+ logfc_scatter_kws : dict | None, optional
1270
+ Keyword arguments for logFC threshold scatter. Default is None.
1271
+ logfc_scatter_kws_left : dict | None, optional
1272
+ Keyword arguments for logFC threshold scatter on the left side. Default is None.
1273
+ logfc_scatter_kws_right : dict | None, optional
1274
+ Keyword arguments for logFC threshold scatter on the right side. Default is None.
1275
+ logfc_line_kws : dict | None, optional
1276
+ Keyword arguments for logFC threshold line. Default is None.
1277
+ logfc_line_kws_left : dict | None, optional
1278
+ Keyword arguments for logFC threshold line on the left side. Default is None.
1279
+ logfc_line_kws_right : dict | None, optional
1280
+ Keyword arguments for logFC threshold line on the right side. Default is None.
1281
+ pval_logfc_scatter_kws : dict | None, optional
1282
+ Keyword arguments for p-value and logFC threshold scatter. Default is None.
1283
+ pval_logfc_scatter_kws_left : dict | None, optional
1284
+ Keyword arguments for p-value and logFC threshold scatter on the left side. Default is None.
1285
+ pval_logfc_scatter_kws_right : dict | None, optional
1286
+ Keyword arguments for p-value and logFC threshold scatter on the right side. Default is None.
1287
+ highlite_scatter_kws : dict | None, optional
1288
+ Keyword arguments for highlite scatter plot. Default is None.
1289
+ highlite_scatter_kws_right : dict | None, optional
1290
+ Keyword arguments for highlite scatter plot on the right side. Default is None.
1291
+ highlite_scatter_kws_left : dict | None, optional
1292
+ Keyword arguments for highlite scatter plot on the left side. Default is None.
1293
+ text_kws : dict | None, optional
1294
+ Keyword arguments for text. Default is None.
1295
+ text_kws_right : dict | None, optional
1296
+ Keyword arguments for text on the right side. Default is None.
1297
+ text_kws_left : dict | None, optional
1298
+ Keyword arguments for text on the left side. Default is None.
1299
+ xlim : tuple[float, float] | None, optional
1300
+ x-axis limits. Default is None.
1301
+ ylim : tuple[float, float] | None, optional
1302
+ y-axis limits. Default is None.
1303
+ title : str | None, optional
1304
+ Title of the plot. Default is None.
1305
+ xlabel : str | None, optional
1306
+ x-axis label. Default is None.
1307
+ ylabel : str | None, optional
1308
+ y-axis label. Default is None.
1309
+ grid : bool, optional
1310
+ Whether to draw grid lines. Default is True.
1311
+ rasterize : bool, optional
1312
+ Whether to rasterize the plot. Default is True.
1313
+ show : bool, optional
1314
+ Whether to show the plot. Default is True.
1315
+ figsize : tuple[float, float] | None, optional
1316
+ Figure size. Default is None.
1317
+
1318
+ Returns
1319
+ -------
1320
+ fig : matplotlib.figure.Figure
1321
+ Figure object if return_fig is True.
1322
+ """
1323
+ try:
1324
+ import textalloc as ta
1325
+ except ImportError:
1326
+ raise ImportError("`textalloc` is required for volcano_plot. Please install it via pip: `pip install textalloc`.")
1327
+
1328
+ if lines_kws is None:
1329
+ lines_kws = {}
1330
+ if scatters_kws is None:
1331
+ scatters_kws = {}
1332
+
1333
+ def _fill_defaults(d, **defaults):
1334
+ if d is None:
1335
+ d = {}
1336
+ for key in defaults:
1337
+ if key not in d:
1338
+ d[key] = defaults[key]
1339
+ return d
1340
+
1341
+ if names is None and not (isinstance(pvals, pd.Series) or isinstance(logfcs, pd.Series)):
1342
+ logg.warning("If `names` is None, `pvals` and `logfcs` must be pd.Series. Gene names won't be displayed.")
1343
+ highlite_names = None
1344
+ n_highlite = 0
1345
+
1346
+ df = pd.DataFrame({"log2fc": logfcs, "p": pvals})
1347
+ elif names is None and (isinstance(pvals, pd.Series) or isinstance(logfcs, pd.Series)):
1348
+ df = pd.DataFrame({"log2fc": logfcs, "p": pvals})
1349
+ else:
1350
+ df = pd.DataFrame({"log2fc": logfcs, "p": pvals}, index=names)
1351
+
1352
+ df["p"] = np.where(df.p < 1e-300, 1e-300, df.p)
1353
+
1354
+ if figsize is None:
1355
+ figsize = (4, 4)
1356
+
1357
+ if ax:
1358
+ show = False
1359
+ return_ax = False
1360
+ fig = ax.figure
1361
+ else:
1362
+ fig, ax = plt.subplots(figsize=figsize)
1363
+ if show:
1364
+ return_ax = False
1365
+ else:
1366
+ return_ax = True
1367
+
1368
+ if lg_p:
1369
+ df["-log10p"] = -np.log10(df["p"])
1370
+ pval_threshold = -np.log10(pval_threshold)
1371
+ else:
1372
+ df["-log10p"] = df["p"]
1373
+ df.dropna(inplace=True)
1374
+
1375
+ # Drawing < logFC and >p-val
1376
+ background_scatter_kws = _fill_defaults(background_scatter_kws, **scatters_kws)
1377
+ background_scatter_kws = _fill_defaults(
1378
+ background_scatter_kws,
1379
+ s=3, alpha=1, color="#AAAAAA", edgecolor="none", rasterized=rasterize,
1380
+ )
1381
+ df_background = df[
1382
+ (df["-log10p"] < pval_threshold) &
1383
+ (df["log2fc"].abs() < logfc_threshold)
1384
+ ]
1385
+ sns.scatterplot(
1386
+ x="log2fc",
1387
+ y="-log10p",
1388
+ data=df_background,
1389
+ ax=ax,
1390
+ zorder=1,
1391
+ **background_scatter_kws,
1392
+ )
1393
+
1394
+ # Drawing < -logFC and >p-val
1395
+ logfc_scatter_kws = _fill_defaults(logfc_scatter_kws, **scatters_kws)
1396
+ logfc_scatter_kws = _fill_defaults(
1397
+ logfc_scatter_kws, s=3, alpha=1, edgecolor="none", rasterized=rasterize,
1398
+ )
1399
+ logfc_scatter_kws_left = _fill_defaults(
1400
+ logfc_scatter_kws_left, **logfc_scatter_kws,
1401
+ )
1402
+ logfc_scatter_kws_left = _fill_defaults(
1403
+ logfc_scatter_kws_left, color="#A7BACC",
1404
+ )
1405
+ df_nonsigni_left = df[
1406
+ (df["-log10p"] < pval_threshold) &
1407
+ (df["log2fc"] <= -logfc_threshold)
1408
+ ]
1409
+ sns.scatterplot(
1410
+ x="log2fc",
1411
+ y="-log10p",
1412
+ data=df_nonsigni_left,
1413
+ ax=ax,
1414
+ zorder=1,
1415
+ **logfc_scatter_kws_left,
1416
+ )
1417
+
1418
+ # Drawing > logFC and >p-val
1419
+ logfc_scatter_kws_right = _fill_defaults(
1420
+ logfc_scatter_kws_right, **logfc_scatter_kws,
1421
+ )
1422
+ logfc_scatter_kws_right = _fill_defaults(
1423
+ logfc_scatter_kws_right, color="#CFA7A7",
1424
+ )
1425
+
1426
+ df_nonsigni_right = df[
1427
+ (df["-log10p"] < pval_threshold) &
1428
+ (df["log2fc"] >= logfc_threshold)
1429
+ ]
1430
+ sns.scatterplot(
1431
+ x="log2fc",
1432
+ y="-log10p",
1433
+ data=df_nonsigni_right,
1434
+ ax=ax,
1435
+ zorder=1,
1436
+ **logfc_scatter_kws_right,
1437
+ )
1438
+
1439
+ # Drawing || < logFC and <p-val
1440
+ pval_scatter_kws = _fill_defaults(pval_scatter_kws, **scatters_kws)
1441
+ pval_scatter_kws = _fill_defaults(
1442
+ pval_scatter_kws, s=3, alpha=1, edgecolor="none", color="#afb598", rasterized=rasterize,
1443
+ )
1444
+ df_signi_center = df[
1445
+ (df["-log10p"] >= pval_threshold) &
1446
+ (df["log2fc"].abs() < logfc_threshold)
1447
+ ]
1448
+ sns.scatterplot(
1449
+ x="log2fc",
1450
+ y="-log10p",
1451
+ data=df_signi_center,
1452
+ ax=ax,
1453
+ zorder=1,
1454
+ **pval_scatter_kws,
1455
+ )
1456
+
1457
+ # Drawing > logFC and < p-val
1458
+ pval_logfc_scatter_kws = _fill_defaults(pval_logfc_scatter_kws, **scatters_kws)
1459
+ pval_logfc_scatter_kws_right = _fill_defaults(
1460
+ pval_logfc_scatter_kws_right,
1461
+ **pval_logfc_scatter_kws,
1462
+ )
1463
+ pval_logfc_scatter_kws_right = _fill_defaults(
1464
+ pval_logfc_scatter_kws_right, color="#D64545", s=7, rasterized=rasterize,
1465
+ edgecolor=None,
1466
+ )
1467
+ df_signi_right = df[
1468
+ (df["-log10p"] >= pval_threshold) &
1469
+ (df["log2fc"] >= logfc_threshold)
1470
+ ]
1471
+ sns.scatterplot(
1472
+ x="log2fc",
1473
+ y="-log10p",
1474
+ data=df_signi_right,
1475
+ ax=ax,
1476
+ zorder=1,
1477
+ **pval_logfc_scatter_kws_right,
1478
+ )
1479
+
1480
+ # Drawing < -logFC and < p-val
1481
+ pval_logfc_scatter_kws_left = _fill_defaults(
1482
+ pval_logfc_scatter_kws_left,
1483
+ **pval_logfc_scatter_kws,
1484
+ )
1485
+ pval_logfc_scatter_kws_left = _fill_defaults(
1486
+ pval_logfc_scatter_kws_left, color="#4A90E2", s=7, rasterized=rasterize,
1487
+ edgecolor=None,
1488
+ )
1489
+ df_signi_left = df[
1490
+ (df["-log10p"] >= pval_threshold) &
1491
+ (df["log2fc"] <= -logfc_threshold)
1492
+ ]
1493
+ sns.scatterplot(
1494
+ x="log2fc",
1495
+ y="-log10p",
1496
+ data=df_signi_left,
1497
+ ax=ax,
1498
+ zorder=1,
1499
+ **pval_logfc_scatter_kws_left,
1500
+ )
1501
+
1502
+ # Highliting genes
1503
+ if highlite_names:
1504
+ # Checking type
1505
+ if isinstance(highlite_names, str):
1506
+ highlite_names = [highlite_names]
1507
+ if not isinstance(highlite_names, (list, tuple, pd.Series)):
1508
+ logg.warning(
1509
+ "highlite_names must be a list, tuple, or pandas Series."
1510
+ )
1511
+ highlite_names = []
1512
+ else:
1513
+ highlite_names = []
1514
+ gene_not_found = []
1515
+ for gene in highlite_names:
1516
+ if gene not in df.index:
1517
+ gene_not_found.append(gene)
1518
+ if len(gene_not_found) > 0:
1519
+ logg.warning(
1520
+ f"Following genes were not found in the dataframe: {gene_not_found}"
1521
+ )
1522
+ highlite_names = pd.Series(highlite_names)
1523
+
1524
+ left_highlite_names = list(
1525
+ df_signi_left.sort_values("-log10p", ascending=False).index[:n_highlite]
1526
+ )
1527
+ left_highlite_names += list(
1528
+ highlite_names[highlite_names.isin(df[df.log2fc < 0].index)]
1529
+ )
1530
+
1531
+ left_highlite_names = np.array(left_highlite_names)
1532
+ dropped_genes = []
1533
+ if xlim:
1534
+ if xlim[0]:
1535
+ out_of_field = (df.loc[left_highlite_names, "log2fc"] < xlim[0]).values
1536
+ if sum(out_of_field) > 0:
1537
+ dropped_genes += list(left_highlite_names[out_of_field])
1538
+ left_highlite_names = left_highlite_names[~out_of_field]
1539
+
1540
+ if ylim:
1541
+ if ylim[0]:
1542
+ out_of_field = (df.loc[left_highlite_names, "-log10p"] < ylim[0]).values
1543
+ if sum(out_of_field) > 0:
1544
+ dropped_genes += list(left_highlite_names[out_of_field])
1545
+ left_highlite_names = left_highlite_names[~out_of_field]
1546
+ if ylim[1]:
1547
+ out_of_field = (df.loc[left_highlite_names, "-log10p"] > ylim[1]).values
1548
+ if sum(out_of_field) > 0:
1549
+ dropped_genes += list(left_highlite_names[out_of_field])
1550
+ left_highlite_names = left_highlite_names[~out_of_field]
1551
+
1552
+ right_highlite_names = list(
1553
+ df_signi_right.sort_values("-log10p", ascending=False).index[:n_highlite]
1554
+ )
1555
+ right_highlite_names += list(
1556
+ highlite_names[highlite_names.isin(df[df.log2fc > 0].index)]
1557
+ )
1558
+
1559
+ right_highlite_names = np.array(right_highlite_names)
1560
+ if xlim:
1561
+ if xlim[1]:
1562
+ out_of_field = (df.loc[right_highlite_names, "log2fc"] > xlim[1]).values
1563
+ if sum(out_of_field) > 0:
1564
+ dropped_genes += list(right_highlite_names[out_of_field])
1565
+ right_highlite_names = right_highlite_names[~out_of_field]
1566
+
1567
+ if ylim:
1568
+ if ylim[0]:
1569
+ out_of_field = (df.loc[right_highlite_names, "-log10p"] < ylim[0]).values
1570
+ if sum(out_of_field) > 0:
1571
+ dropped_genes += list(right_highlite_names[out_of_field])
1572
+ right_highlite_names = right_highlite_names[~out_of_field]
1573
+ if ylim[1]:
1574
+ out_of_field = (df.loc[right_highlite_names, "-log10p"] > ylim[1]).values
1575
+ if sum(out_of_field) > 0:
1576
+ dropped_genes += list(right_highlite_names[out_of_field])
1577
+ right_highlite_names = right_highlite_names[~out_of_field]
1578
+
1579
+ if len(dropped_genes) > 0:
1580
+ logg.warning(
1581
+ f"Following genes are out of the plot area: {dropped_genes}"
1582
+ )
1583
+
1584
+ highlite_scatter_kws = _fill_defaults(
1585
+ highlite_scatter_kws, **scatters_kws
1586
+ )
1587
+ highlite_scatter_kws_left = _fill_defaults(
1588
+ highlite_scatter_kws_left, **highlite_scatter_kws
1589
+ )
1590
+
1591
+ increase_s = False
1592
+ add_edgecolor = False
1593
+ add_linewidth = False
1594
+ if "s" not in highlite_scatter_kws_left:
1595
+ increase_s = True
1596
+ if "edgecolor" not in highlite_scatter_kws_left:
1597
+ add_edgecolor = True
1598
+ if "linewidth" not in highlite_scatter_kws_left:
1599
+ add_linewidth = True
1600
+
1601
+ highlite_scatter_kws_left = _fill_defaults(
1602
+ highlite_scatter_kws_left, **pval_logfc_scatter_kws_left
1603
+ )
1604
+ if increase_s:
1605
+ highlite_scatter_kws_left["s"] += 10
1606
+ if add_linewidth:
1607
+ highlite_scatter_kws_left["linewidth"] = 0.5
1608
+ if add_edgecolor:
1609
+ highlite_scatter_kws_left["edgecolor"] = "black"
1610
+
1611
+ left_highlite_names = list(set(left_highlite_names))
1612
+ sns.scatterplot(
1613
+ x="log2fc",
1614
+ y="-log10p",
1615
+ data=df.loc[left_highlite_names],
1616
+ ax=ax,
1617
+ zorder=1,
1618
+ **highlite_scatter_kws_left,
1619
+ )
1620
+
1621
+ highlite_scatter_kws_right = _fill_defaults(
1622
+ highlite_scatter_kws_right, **highlite_scatter_kws
1623
+ )
1624
+
1625
+ increase_s = False
1626
+ add_edgecolor = False
1627
+ add_linewidth = False
1628
+ if "s" not in highlite_scatter_kws_right:
1629
+ increase_s = True
1630
+ if "edgecolor" not in highlite_scatter_kws_right:
1631
+ add_edgecolor = True
1632
+ if "linewidth" not in highlite_scatter_kws_right:
1633
+ add_linewidth = True
1634
+
1635
+ highlite_scatter_kws_right = _fill_defaults(
1636
+ highlite_scatter_kws_right, **pval_logfc_scatter_kws_right
1637
+ )
1638
+ if increase_s:
1639
+ highlite_scatter_kws_right["s"] += 10
1640
+ if add_linewidth:
1641
+ highlite_scatter_kws_right["linewidth"] = 0.5
1642
+ if add_edgecolor:
1643
+ highlite_scatter_kws_right["edgecolor"] = "black"
1644
+
1645
+ right_highlite_names = list(set(right_highlite_names))
1646
+ sns.scatterplot(
1647
+ x="log2fc",
1648
+ y="-log10p",
1649
+ data=df.loc[right_highlite_names],
1650
+ ax=ax,
1651
+ zorder=1,
1652
+ **highlite_scatter_kws_right,
1653
+ )
1654
+
1655
+ if xlim is None:
1656
+ xlim = ax.get_xlim()
1657
+ ax.set_xlim(xlim)
1658
+ if ylim is None:
1659
+ ylim = ax.get_ylim()
1660
+ ax.set_ylim(ylim)
1661
+
1662
+ xlines = None
1663
+ ylines = None
1664
+
1665
+ pval_line_kws = _fill_defaults(pval_line_kws, **lines_kws)
1666
+ pval_line_kws = _fill_defaults(
1667
+ pval_line_kws,
1668
+ linestyle="--", color="black", linewidth=0.5,
1669
+ )
1670
+
1671
+ if draw_p_threshold and pval_threshold is not None and pval_line_kws["linewidth"] > 0:
1672
+ ax.axhline(pval_threshold, zorder=2, **pval_line_kws)
1673
+ xlines = [[xlim[0], xlim[1]]]
1674
+ ylines = [[pval_threshold, pval_threshold]]
1675
+
1676
+ logfc_line_kws = _fill_defaults(logfc_line_kws, **lines_kws)
1677
+ logfc_line_kws = _fill_defaults(
1678
+ logfc_line_kws,
1679
+ linestyle="--", color="black", linewidth=0.5,
1680
+ )
1681
+ logfc_line_kws_left = _fill_defaults(
1682
+ logfc_line_kws_left, **logfc_line_kws
1683
+ )
1684
+ logfc_line_kws_right = _fill_defaults(
1685
+ logfc_line_kws_right, **logfc_line_kws
1686
+ )
1687
+ if draw_logfc_threshold and logfc_threshold is not None and logfc_line_kws["linewidth"] > 0:
1688
+ ax.axvline(logfc_threshold, zorder=2, **logfc_line_kws_left)
1689
+ ax.axvline(-logfc_threshold, zorder=2, **logfc_line_kws_right)
1690
+
1691
+ if xlines is None:
1692
+ xlines = []
1693
+ xlines += [[logfc_threshold, logfc_threshold], [-logfc_threshold, -logfc_threshold]]
1694
+
1695
+ if ylines is None:
1696
+ ylines = []
1697
+ ylines += [[ylim[0], ylim[1]], [ylim[0], ylim[1]]]
1698
+
1699
+ # Parse text_kws consistently
1700
+ text_kws = _fill_defaults(text_kws)
1701
+ text_kws_left = _fill_defaults(text_kws_left, **text_kws)
1702
+ text_kws_right = _fill_defaults(text_kws_right, **text_kws)
1703
+
1704
+ text_kws_left = _fill_defaults(
1705
+ text_kws_left,
1706
+ textsize=10,
1707
+ linecolor="k",
1708
+ avoid_crossing_label_lines=True,
1709
+ avoid_label_lines_overlap=True,
1710
+ textcolor=highlite_scatter_kws_left.get("color", "black"),
1711
+ fontstyle="italic",
1712
+ max_distance=0.3,
1713
+ bbox=dict(
1714
+ pad=1.5,
1715
+ facecolor="white",
1716
+ edgecolor="black",
1717
+ alpha=0.5,
1718
+ ),
1719
+ )
1720
+
1721
+ text_kws_right = _fill_defaults(
1722
+ text_kws_right,
1723
+ textsize=10,
1724
+ linecolor="k",
1725
+ linewidth=0.5,
1726
+ avoid_crossing_label_lines=True,
1727
+ avoid_label_lines_overlap=True,
1728
+ textcolor=highlite_scatter_kws_right.get("color", "black"),
1729
+ fontstyle="italic",
1730
+ max_distance=0.3,
1731
+ bbox=dict(
1732
+ pad=1.5,
1733
+ facecolor="white",
1734
+ edgecolor="black",
1735
+ alpha=0.5,
1736
+ ),
1737
+ )
1738
+
1739
+ if len(left_highlite_names) > 0:
1740
+ import warnings
1741
+ with warnings.catch_warnings():
1742
+ warnings.filterwarnings(
1743
+ "ignore",
1744
+ message=r".*Series.__getitem__ treating keys as positions is deprecated.*",
1745
+ category=FutureWarning,
1746
+ )
1747
+ ta.allocate(
1748
+ ax,
1749
+ x=df.loc[left_highlite_names, "log2fc"],
1750
+ y=df.loc[left_highlite_names, "-log10p"],
1751
+ text_list=left_highlite_names,
1752
+ x_scatter=df.log2fc,
1753
+ y_scatter=df["-log10p"],
1754
+ x_lines=xlines,
1755
+ y_lines=ylines,
1756
+ **text_kws_left,
1757
+ )
1758
+
1759
+ if len(right_highlite_names) > 0:
1760
+ import warnings
1761
+ with warnings.catch_warnings():
1762
+ warnings.filterwarnings(
1763
+ "ignore",
1764
+ message=r".*Series.__getitem__ treating keys as positions is deprecated.*",
1765
+ category=FutureWarning,
1766
+ )
1767
+ ta.allocate(
1768
+ ax,
1769
+ x=df.loc[right_highlite_names, "log2fc"],
1770
+ y=df.loc[right_highlite_names, "-log10p"],
1771
+ text_list=right_highlite_names,
1772
+ x_scatter=df.log2fc,
1773
+ y_scatter=df["-log10p"],
1774
+ x_lines=xlines,
1775
+ y_lines=ylines,
1776
+ **text_kws_right,
1777
+ )
1778
+
1779
+ if grid:
1780
+ ax.grid(alpha=0.3, zorder=0)
1781
+ if xlabel is None:
1782
+ xlabel = "log2(Fold Change)"
1783
+ ax.set_xlabel(xlabel)
1784
+ if ylabel is None:
1785
+ if adj_p:
1786
+ ylabel = "–log10(adj. p-value)"
1787
+ else:
1788
+ ylabel = "–log10(p-value)"
1789
+ ax.set_ylabel(ylabel)
1790
+
1791
+ if title:
1792
+ ax.set_title(title)
1793
+
1794
+ if return_fig:
1795
+ return fig
1796
+ elif return_ax:
1797
+ return ax
1798
+ elif show:
1799
+ plt.show()
1800
+
1801
+ def shap_volcano(
1802
+ shapdata: AnnData,
1803
+ layer: str,
1804
+ min_corr: float = 0.5,
1805
+ xlabel: str = "corr(SHAP, Expr)",
1806
+ ylabel: str = "mean(|SHAP|)",
1807
+ title: str | None = None,
1808
+ return_fig: bool = False,
1809
+ show: bool = True,
1810
+ figsize: tuple[float, float] | None = None,
1811
+ ax: matplotlib.axes.Axes | None = None,
1812
+ **kwargs,
1813
+ ) -> plt.Figure | matplotlib.axes.Axes | None:
1814
+ """
1815
+ Draws volcano-like plot showing the result of the associations analysis with CatBoost and SHAP.
1816
+
1817
+ Parameters
1818
+ ----------
1819
+ shapdata : AnnData
1820
+ Annotated data matrix with SHAP values in `layers[layer]` and gene expression correlations in `varm["gex_r"][layer]`.
1821
+ layer : str
1822
+ Layer in `shapdata.layers` with SHAP values.
1823
+ min_corr : float, optional
1824
+ Minimum correlation threshold for plotting. Default is 0.5.
1825
+ xlabel : str, optional
1826
+ Label for the x-axis. Default is "corr(SHAP, Expr)".
1827
+ ylabel : str, optional
1828
+ Label for the y-axis. Default is "mean(|SHAP|)".
1829
+ title : str | None, optional
1830
+ Title for the plot. Default is None.
1831
+ return_fig : bool, optional
1832
+ Whether to return the figure object. Default is False.
1833
+ show : bool, optional
1834
+ Whether to show the plot. Default is True.
1835
+ figsize : tuple[float, float] | None, optional
1836
+ Figure size. Default is None.
1837
+ ax : matplotlib.axes.Axes | None, optional
1838
+ Axes object to draw on. Default is None.
1839
+ **kwargs
1840
+ Additional keyword arguments for `volcano()`.
1841
+ """
1842
+
1843
+ if title is None:
1844
+ title = f"{layer} proportion predictors"
1845
+
1846
+ return volcano(
1847
+ pvals=np.abs(shapdata.layers[layer]).mean(axis=0).A[0],
1848
+ logfcs=shapdata.varm["gex_r"][layer],
1849
+ lg_p=False,
1850
+ logfc_threshold=min_corr,
1851
+ ylabel=ylabel,
1852
+ xlabel=xlabel,
1853
+ title=title,
1854
+ return_fig=return_fig,
1855
+ show=show,
1856
+ figsize=figsize,
1857
+ ax=ax,
1858
+ **kwargs,
1859
+ )
1860
+
1861
+ def barplot(
1862
+ data: pd.Series,
1863
+ kind: Literal["h", "v"] = "v",
1864
+ ax: plt.Axes | None = None,
1865
+ cmap: str = "Reds",
1866
+ vmax: float | None = None,
1867
+ vmin: float | None = 0.,
1868
+ return_fig: bool = False,
1869
+ show: bool = True,
1870
+ title: str | None = None,
1871
+ right_spines: bool | None = None,
1872
+ left_spines: bool | None = None,
1873
+ top_spines: bool | None = None,
1874
+ bottom_spines: bool | None = None,
1875
+ width: float = 0.8,
1876
+ figsize: tuple[float, float] | None = None,
1877
+ edgecolor: str = "black",
1878
+ rotation: float | None = None,
1879
+ arrow: list[Literal["right-bottom", "top-left"]] | Literal["right-bottom", "top-left"] | None = None,
1880
+ **kwargs,
1881
+ ) -> plt.Figure | None:
1882
+ """
1883
+ Draws barplot colored by the value in each bar.
1884
+
1885
+ Parameters
1886
+ ----------
1887
+ data : pd.Series
1888
+ Data to plot.
1889
+ kind : Literal["h", "v"], optional
1890
+ Kind of plot. Default is "v".
1891
+ ax : plt.Axes | None, optional
1892
+ Axes object to draw on. Default is None.
1893
+ cmap : str, optional
1894
+ Colormap to use. Default is "Reds".
1895
+ vmax : float | None, optional
1896
+ Maximum value for colormap normalization. Default is None.
1897
+ vmin : float | None, optional
1898
+ Minimum value for colormap normalization. Default is 0.
1899
+ return_fig : bool, optional
1900
+ Whether to return the figure object. Default is False.
1901
+ title : str | None, optional
1902
+ Title for the plot. Default is None.
1903
+ right_spines : bool | None, optional
1904
+ Whether to show right spines. Default is None.
1905
+ left_spines : bool | None, optional
1906
+ Whether to show left spines. Default is None.
1907
+ top_spines : bool | None, optional
1908
+ Whether to show top spines. Default is None.
1909
+ bottom_spines : bool | None, optional
1910
+ Whether to show bottom spines. Default is None.
1911
+ width : float, optional
1912
+ Width of the bars. Default is 0.8.
1913
+ figsize : tuple[float, float] | None, optional
1914
+ Figure size. Default is None.
1915
+ edgecolor : str, optional
1916
+ Edge color of the bars. Default is "black".
1917
+ rotation : float | None, optional
1918
+ Rotation angle for labels, if None rotation depends on the . Default is None.
1919
+ arrow : list[Literal["right-bottom", "top-left"]] | Literal["right-bottom", "top-left"] | None, optional
1920
+ Whether to add arrow to the plot. Default is None.
1921
+ **kwargs
1922
+ Additional keyword arguments for `ax.bar()`.
1923
+
1924
+ Returns
1925
+ -------
1926
+ fig : plt.Figure | None
1927
+ Figure object if `return_fig` is True, otherwise None.
1928
+ """
1929
+
1930
+ import matplotlib.colors as mcolors
1931
+
1932
+ if kind == "v":
1933
+ if figsize is None:
1934
+ figsize = (3, 6)
1935
+ if right_spines is None:
1936
+ right_spines = False
1937
+ if left_spines is None:
1938
+ left_spines = False
1939
+ if top_spines is None:
1940
+ top_spines = False
1941
+ if bottom_spines is None:
1942
+ bottom_spines = True
1943
+ if arrow is None:
1944
+ arrow = ["right-bottom"]
1945
+ if rotation is None:
1946
+ rotation = 0
1947
+ else:
1948
+ if figsize is None:
1949
+ figsize = (6, 3)
1950
+ if right_spines is None:
1951
+ right_spines = False
1952
+ if left_spines is None:
1953
+ left_spines = True
1954
+ if top_spines is None:
1955
+ top_spines = False
1956
+ if bottom_spines is None:
1957
+ bottom_spines = False
1958
+ if arrow is None:
1959
+ arrow = ["top-left"]
1960
+ if rotation is None:
1961
+ rotation = 90
1962
+ if isinstance(arrow, str):
1963
+ arrow = [arrow]
1964
+ if vmax is None:
1965
+ vmax = data.max()
1966
+ if vmin is None:
1967
+ vmin = data.min()
1968
+
1969
+ if ax:
1970
+ show = False
1971
+ return_ax = False
1972
+ else:
1973
+ fig, ax = plt.subplots(figsize=figsize)
1974
+ if show:
1975
+ return_ax = False
1976
+ else:
1977
+ return_ax = True
1978
+
1979
+ if kind == "h":
1980
+ data.plot(ax=ax, kind="bar", width=width, edgecolor=edgecolor, **kwargs)
1981
+ ax.tick_params(axis="x", labelrotation=rotation)
1982
+ else:
1983
+ data = data[::-1]
1984
+ data.plot(ax=ax, kind="barh", width=width, edgecolor=edgecolor, **kwargs)
1985
+ ax.tick_params(axis="y", labelrotation=rotation)
1986
+
1987
+ ax.spines["right"].set_visible(right_spines)
1988
+ ax.spines["top"].set_visible(top_spines)
1989
+ ax.spines["left"].set_visible(left_spines)
1990
+ ax.spines["bottom"].set_visible(bottom_spines)
1991
+
1992
+ if "right-bottom" in arrow:
1993
+ ax.plot(
1994
+ 1, 0, ">k",
1995
+ transform=ax.transAxes,
1996
+ clip_on=False,
1997
+ )
1998
+
1999
+ if "top-left" in arrow:
2000
+ ax.plot(
2001
+ 0, 1, "^k",
2002
+ transform=ax.transAxes,
2003
+ clip_on=False,
2004
+ )
2005
+
2006
+ cmap = plt.get_cmap(cmap)
2007
+ vmin = vmin
2008
+ vmax = vmax
2009
+ norm = mcolors.Normalize(vmin=vmin, vmax=vmax)
2010
+
2011
+ for patch, value in zip(ax.patches, data.values):
2012
+ color = cmap(norm(value))
2013
+ patch.set_facecolor(color)
2014
+
2015
+ ax.grid(alpha=0.3)
2016
+ if title:
2017
+ ax.set_title(title)
2018
+
2019
+ if return_fig:
2020
+ return fig
2021
+ elif return_ax:
2022
+ return ax
2023
+ elif show:
2024
+ plt.show()
2025
+
2026
+ def predictors_comparison(
2027
+ shapdata: sc.AnnData,
2028
+ group1: str,
2029
+ group2: str,
2030
+ varm_key: str | None = None,
2031
+ n_genes: int = 10,
2032
+ cmap: str = "RdBu_r",
2033
+ title: str | None = None,
2034
+ show: bool = True,
2035
+ figsize: tuple[float, float] | None = None,
2036
+ ax: plt.Axes | None = None,
2037
+ return_fig: bool = False,
2038
+ **kwargs,
2039
+ ) -> plt.Figure | plt.Axes | None:
2040
+ """
2041
+ Draws barplot of SHAP values for two groups.
2042
+
2043
+ Parameters
2044
+ ----------
2045
+ shapdata : sc.AnnData
2046
+ Annotated data matrix with SHAP values in `varm`.
2047
+ group1 : str
2048
+ Name of the first group.
2049
+ group2 : str
2050
+ Name of the second group.
2051
+ varm_key : str | None, optional
2052
+ Key in `varm` to SHAP values. Default is None.
2053
+ n_genes : int, optional
2054
+ Number of top and bottom genes to plot. Default is 10.
2055
+ cmap : str, optional
2056
+ Colormap to use. Default is "RdBu_r".
2057
+ title: str | None, optional
2058
+ Title for the plot. Default is None.
2059
+ show : bool, optional
2060
+ Whether to show the plot. Default is True.
2061
+ figsize : tuple[float, float] | None, optional
2062
+ Figure size. Default is None.
2063
+ ax : plt.Axes | None, optional
2064
+ Axes object to draw on. Default is None.
2065
+ return_fig : bool, optional
2066
+ Whether to return the figure object. Default is False.
2067
+ **kwargs
2068
+ Additional keyword arguments for `ax.bar()`.
2069
+
2070
+ Returns
2071
+ -------
2072
+ fig : plt.Figure | plt.Axes | None
2073
+ Figure object if `return_fig` is True, Axes if `show` is False, otherwise None.
2074
+ """
2075
+ if varm_key is None:
2076
+ try:
2077
+ df = shapdata.varm["signed_mean_shap"]
2078
+ except KeyError:
2079
+ raise KeyError("varm['signed_mean_shap'] not found. Please run c2v.utils.correct_shap() first with flags `normalize=False` and `correct_sign=True`.")
2080
+ else:
2081
+ logg.warning(f"We expect sign-corrected and not normalized by maximum value SHAPs in varm['{varm_key}'].")
2082
+ df = shapdata.varm[varm_key]
2083
+
2084
+ diff = (df[group1] - df[group2]).sort_values(ascending=False)
2085
+ diff = pd.concat([diff[:n_genes], diff[-n_genes:]])
2086
+ vmax = np.abs(diff).max()
2087
+
2088
+ if title is None:
2089
+ title = f"{group1} [+] vs. {group2} [–]"
2090
+
2091
+ return barplot(
2092
+ diff[::-1],
2093
+ cmap=cmap,
2094
+ vmin=-vmax,
2095
+ vmax=vmax,
2096
+ left_spines=True,
2097
+ bottom_spines=True,
2098
+ title=title,
2099
+ show=show,
2100
+ figsize=figsize,
2101
+ ax=ax,
2102
+ return_fig=return_fig,
2103
+ **kwargs,
2104
+ )
2105
+
2106
+
2107
+ def heatmap(
2108
+ df: pd.DataFrame,
2109
+ cmap: str = "RdBu_r",
2110
+ linecolor: str = "black",
2111
+ linewidth: float = 0.5,
2112
+ borderwidth_hm: float = 2.,
2113
+ square: bool = True,
2114
+ cbar_scale: float = 0.6,
2115
+ cbar_aspect: float = 20.,
2116
+ cbar_pad: float = 0.025,
2117
+ cmap_border: float = 1.,
2118
+ cbar_title: str = "",
2119
+ ax: plt.Axes | None = None,
2120
+ x_rotation: float = 0.,
2121
+ y_rotation: float = 0.,
2122
+ xlabels: bool = True,
2123
+ ylabels: bool = True,
2124
+ sort_columns: bool = True,
2125
+ sort_rows: bool = False,
2126
+ linkage_method: str = "average",
2127
+ linkage_metric: str = "euclidean",
2128
+ return_fig: bool = False,
2129
+ title: str | None = None,
2130
+ show: bool = True,
2131
+ figsize: tuple[float, float] | None = None,
2132
+ **kwargs,
2133
+ ) -> plt.Figure | plt.Axes | None:
2134
+ """
2135
+ Draws pretty heatmap.
2136
+
2137
+ Parameters
2138
+ ----------
2139
+ df : pd.DataFrame
2140
+ DataFrame to be visualized.
2141
+ cmap : str, optional
2142
+ Colormap to be used. Default is "RdBu_r".
2143
+ linecolor : str, optional
2144
+ Color of the lines between cells. Default is "black".
2145
+ linewidth : float, optional
2146
+ Width of the lines between cells. Default is 0.5.
2147
+ borderwidth_hm : float, optional
2148
+ Width of the border around the heatmap. Default is 2.
2149
+ square : bool, optional
2150
+ Whether to make cells square. Default is True.
2151
+ cbar_scale : float, optional
2152
+ Scale of the colorbar. Default is 0.6.
2153
+ cbar_aspect : float, optional
2154
+ Aspect ratio of the colorbar. Default is 20.
2155
+ cbar_pad : float, optional
2156
+ Padding between the heatmap and the colorbar. Default is 0.025.
2157
+ cmap_border : float, optional
2158
+ Width of the border around the colormap. Default is 1.
2159
+ cbar_title : str, optional
2160
+ Title of the colorbar. Default is "".
2161
+ ax : plt.Axes | None, optional
2162
+ Axes object to draw the heatmap on. Default is None.
2163
+ x_rotation : float, optional
2164
+ Rotation angle for x-axis labels. Default is 0.
2165
+ y_rotation : float, optional
2166
+ Rotation angle for y-axis labels. Default is 0.
2167
+ xlabels : bool, optional
2168
+ Whether to show x-axis labels. Default is True.
2169
+ ylabels : bool, optional
2170
+ Whether to show y-axis labels. Default is True.
2171
+ sort_columns : bool, optional
2172
+ Whether to hierarchically sort columns for display. Default is False.
2173
+ sort_rows : bool, optional
2174
+ Whether to hierarchically sort rows for display. Default is False.
2175
+ linkage_method : str, optional
2176
+ Linkage method for hierarchical clustering. Default is "average".
2177
+ linkage_metric : str, optional
2178
+ Linkage metric for hierarchical clustering. Default is "euclidean".
2179
+ return_fig : bool, optional
2180
+ Whether to return the figure object. Default is False.
2181
+ title : str | None, optional
2182
+ Title for the plot. Default is None.
2183
+ show : bool, optional
2184
+ Whether to show the plot. Default is True.
2185
+ figsize : tuple[float, float] | None, optional
2186
+ Figure size. Default is None.
2187
+ **kwargs
2188
+ Additional keyword arguments for `sns.heatmap()`.
2189
+
2190
+ Returns
2191
+ -------
2192
+ fig : plt.Figure | plt.Axes | None
2193
+ Figure object if `return_fig` is True, Axes if `show` is False, otherwise None.
2194
+ """
2195
+
2196
+ import matplotlib.patches as patches
2197
+
2198
+ if figsize is None:
2199
+ figsize = (6, 6)
2200
+
2201
+ if ax:
2202
+ show = False
2203
+ return_ax = False
2204
+ fig = ax.figure
2205
+ else:
2206
+ fig, ax = plt.subplots(figsize=figsize)
2207
+ if show:
2208
+ return_ax = False
2209
+ else:
2210
+ return_ax = True
2211
+
2212
+ if sort_columns:
2213
+ from scipy.cluster.hierarchy import linkage, leaves_list
2214
+ Z = linkage(df.T.values, method=linkage_method, metric=linkage_metric)
2215
+ order = leaves_list(Z)
2216
+ data = df.iloc[:, order]
2217
+ else:
2218
+ data = df
2219
+
2220
+ if sort_rows:
2221
+ Z = linkage(data.values, method=linkage_method, metric=linkage_metric)
2222
+ order = leaves_list(Z)
2223
+ data = data.iloc[order, :]
2224
+
2225
+ hm = sns.heatmap(
2226
+ data,
2227
+ cmap=cmap,
2228
+ linecolor=linecolor,
2229
+ linewidth=linewidth,
2230
+ square=square,
2231
+ cbar_kws={
2232
+ "shrink": cbar_scale,
2233
+ "aspect": cbar_aspect,
2234
+ "pad": cbar_pad,
2235
+ "label": cbar_title,
2236
+ },
2237
+ ax=ax,
2238
+ **kwargs,
2239
+ )
2240
+ if xlabels:
2241
+ ax.tick_params(axis="x", labelrotation=90 - x_rotation)
2242
+ for label in ax.get_xticklabels():
2243
+ label.set_rotation_mode("anchor")
2244
+ label.set_ha("right")
2245
+ label.set_va("center")
2246
+ else:
2247
+ ax.set_xticks([])
2248
+ if ylabels:
2249
+ ax.tick_params(axis="y", labelrotation=y_rotation)
2250
+ for label in ax.get_yticklabels():
2251
+ label.set_rotation_mode("anchor")
2252
+ else:
2253
+ ax.set_yticks([])
2254
+
2255
+ if title:
2256
+ ax.set_title(title)
2257
+
2258
+ rect = patches.Rectangle(
2259
+ (0, 0), 1, 1,
2260
+ transform=ax.transAxes,
2261
+ fill=False,
2262
+ edgecolor="black",
2263
+ linewidth=borderwidth_hm,
2264
+ zorder=10,
2265
+ )
2266
+ ax.add_patch(rect)
2267
+
2268
+ cbar = hm.collections[0].colorbar
2269
+ cbar.outline.set_visible(True)
2270
+ cbar.outline.set_linewidth(cmap_border)
2271
+ cbar.outline.set_edgecolor("black")
2272
+
2273
+ if return_fig:
2274
+ return fig
2275
+ elif return_ax:
2276
+ return ax
2277
+ elif show:
2278
+ plt.show()
2279
+
2280
+ def _cmap(
2281
+ initial_cmap: str = "Reds",
2282
+ grey_intensity: float = 0.2,
2283
+ color_intencity: float = 0.1,
2284
+ ) -> ListedColormap:
2285
+ """
2286
+ Returns color map for visualization of gene expression on UMAPs. Color
2287
+ map will starts from grey, not from white.
2288
+
2289
+ Parameters
2290
+ ----------
2291
+ initial_cmap : str, optional
2292
+ What color map will be the base for novel color map.
2293
+ grey_intensity : float, optional
2294
+ What intensity of grey should be at the start of color map.
2295
+ color_intencity : float, optional
2296
+ What intensity of color should be after grey at color map
2297
+
2298
+ Returns
2299
+ ----------
2300
+ ListedColormap object.
2301
+ """
2302
+ from matplotlib.colors import ListedColormap
2303
+
2304
+ cm_color = plt.get_cmap(initial_cmap, 128)
2305
+ cm_grey = plt.get_cmap("Greys", 128)
2306
+
2307
+ return ListedColormap(np.vstack((
2308
+ cm_grey(np.linspace(grey_intensity, 0.2, 1)),
2309
+ cm_color(np.linspace(color_intencity, 1, 128)),
2310
+ )))
2311
+
2312
+ def _prepare_c2c(
2313
+ adata: sc.AnnData,
2314
+ obsm: str,
2315
+ clone_col: str | None = None,
2316
+ color: str | None = None,
2317
+ cmap: str | None = None,
2318
+ palette: str | None = None,
2319
+ ) -> tuple[pd.DataFrame, str]:
2320
+ """
2321
+ Prepares dataframes for visualization of cells or clones in clones2cells.
2322
+
2323
+ Parameters
2324
+ ----------
2325
+ adata : sc.AnnData
2326
+ Annotated data matrix.
2327
+ obsm : str
2328
+ Name of the obsm matrix to use for visualization.
2329
+ clone_col : str, optional
2330
+ Name of the column in adata.obs that contains clone information.
2331
+ If None, cells will be visualized.
2332
+ color : str, optional
2333
+ Name of the column in adata.obs or adata.raw.obs that contains
2334
+ color information. If None, cells will be visualized in grey.
2335
+ cmap : str, optional
2336
+ Name of the colormap to use for continuous coloring. If None,
2337
+ standard scanpy's procedure for categorical coloring is used.
2338
+ palette : str, optional
2339
+ Name of the palette to use for categorical coloring. If None,
2340
+ standard scanpy's procedure for categorical coloring is used.
2341
+
2342
+ Returns
2343
+ -------
2344
+ df : pd.DataFrame
2345
+ Dataframe with columns "x", "y", "clone" (if clone_col is None) or
2346
+ "cell", "clone" (if clone_col is not None).
2347
+ cmap : str | None
2348
+ Name of the colormap to use for visualization. If None, cells will be
2349
+ visualized in grey.
2350
+ """
2351
+
2352
+ df = pd.DataFrame({
2353
+ "x": adata.obsm[obsm][:, 0],
2354
+ "y": adata.obsm[obsm][:, 1],
2355
+ })
2356
+
2357
+ if clone_col is None:
2358
+ df["clone"] = adata.obs_names.values
2359
+ else:
2360
+ df["cell"] = adata.obs_names.values
2361
+ df["clone"] = adata.obs[clone_col].values
2362
+
2363
+ if color:
2364
+ if adata.raw and not (color in adata.obs.columns):
2365
+ c = adata.raw.obs_vector(color)
2366
+ else:
2367
+ c = adata.obs_vector(color)
2368
+
2369
+ if not pd.api.types.is_numeric_dtype(c):
2370
+ c = pd.core.arrays.categorical.Categorical(c)
2371
+ if palette is None:
2372
+ sc.pl._utils.add_colors_for_categorical_sample_annotation(adata, color)
2373
+ colors = adata.uns[f"{color}_colors"]
2374
+ else:
2375
+ if type(palette) == dict:
2376
+ colors = []
2377
+ for category in c.categories:
2378
+ colors.append(palette[category])
2379
+ else:
2380
+ colors = palette
2381
+ cmap = dict(zip(c.categories, colors))
2382
+ df["c"] = c
2383
+ else:
2384
+ if cmap is None:
2385
+ cmap = "viridis"
2386
+ df["c"] = c
2387
+ else:
2388
+ cmap = None
2389
+
2390
+ return df, cmap
2391
+
2392
+ def catboost_perfomance(
2393
+ shapdata: sc.AnnData,
2394
+ var_names: str | list[str] | None = None,
2395
+ set_type: Literal["train", "validation"] = "validation",
2396
+ ncols: int = 4,
2397
+ ax: matplotlib.axes.Axes | list[matplotlib.axes.Axes] | None = None,
2398
+ return_fig: bool = False,
2399
+ show: bool = True,
2400
+ figsize: tuple[float, float] | None = None,
2401
+ line_kws: dict | list[dict] | None = None,
2402
+ scatter_kws: dict | list[dict] | None = None,
2403
+ kwargs: dict | list[dict] | None = None,
2404
+ title: str | list[str] | None = None,
2405
+ ) -> matplotlib.figure.Figure | matplotlib.axes.Axes | np.ndarray | list[matplotlib.axes.Axes] | None:
2406
+ """
2407
+ Compares predicted by CatBoost and observed values. It might help to evaluate
2408
+ performance of CatBoost model.
2409
+
2410
+ Parameters
2411
+ ----------
2412
+ shapdata : sc.AnnData
2413
+ Annotated data matrix.
2414
+ var_names : str | list[str], optional
2415
+ Names of the variables to visualize. If None, all fates will be
2416
+ visualized.
2417
+ set_type : Literal["train", "validation"], optional
2418
+ Whether to visualize train or validation set.
2419
+ ncols : int, optional
2420
+ Number of columns in the plot.
2421
+ ax : matplotlib.axes.Axes | list[matplotlib.axes.Axes], optional
2422
+ Axes to plot on. If None, new figure will be created.
2423
+ return_fig : bool, optional
2424
+ Whether to return figure object.
2425
+ show : bool, optional
2426
+ Whether to show the plot. Default is True.
2427
+ figsize : tuple[float, float] | None, optional
2428
+ Figure size. Default is None.
2429
+ line_kws : dict | list[dict], optional
2430
+ Keyword arguments for line plot.
2431
+ scatter_kws : dict | list[dict], optional
2432
+ Keyword arguments for scatter plot.
2433
+ kwargs : dict | list[dict], optional
2434
+ Keyword arguments for sns.lineplot.
2435
+ title : str | list[str], optional
2436
+ Title of the plot.
2437
+
2438
+ Returns
2439
+ -------
2440
+ fig : matplotlib.figure.Figure | matplotlib.axes.Axes | np.ndarray | list[matplotlib.axes.Axes] | None
2441
+ Figure object if `return_fig` is True, Axes if `show` is False, otherwise None.
2442
+ """
2443
+
2444
+ import scipy.sparse as sp
2445
+ from .associations import _fast_corr
2446
+
2447
+ if "catboost_info" not in shapdata.uns.keys():
2448
+ raise ValueError("catboost_info not found in shapdata.uns. Please, run `c2v.tl.catboost()` first.")
2449
+
2450
+ obsm_key = shapdata.uns["catboost_info"]["obsm_key"]
2451
+ fates_used = shapdata.uns["catboost_info"]["fates_used"]
2452
+ if var_names is None:
2453
+ var_names = list(fates_used)
2454
+ elif isinstance(var_names, str):
2455
+ var_names = [var_names]
2456
+
2457
+ if set_type == "validation":
2458
+ mask = shapdata.obs["validation"].values
2459
+ else:
2460
+ mask = (~shapdata.obs["validation"]).values
2461
+
2462
+ if line_kws is None:
2463
+ line_kws = [{} for _ in range(len(var_names))]
2464
+ elif isinstance(line_kws, dict):
2465
+ line_kws = [line_kws.copy() for _ in range(len(var_names))]
2466
+ if scatter_kws is None:
2467
+ scatter_kws = [{} for _ in range(len(var_names))]
2468
+ elif isinstance(scatter_kws, dict):
2469
+ scatter_kws = [scatter_kws.copy() for _ in range(len(var_names))]
2470
+ if kwargs is None:
2471
+ kwargs = [{} for _ in range(len(var_names))]
2472
+ elif isinstance(kwargs, dict):
2473
+ kwargs = [kwargs.copy() for _ in range(len(var_names))]
2474
+ if title is None:
2475
+ title = [None for _ in range(len(var_names))]
2476
+ elif isinstance(title, str):
2477
+ title = [title for _ in range(len(var_names))]
2478
+
2479
+ if len(line_kws) != len(var_names):
2480
+ raise ValueError("line_kws must have the same length as var_names")
2481
+ if len(scatter_kws) != len(var_names):
2482
+ raise ValueError("scatter_kws must have the same length as var_names")
2483
+ if len(kwargs) != len(var_names):
2484
+ raise ValueError("kwargs must have the same length as var_names")
2485
+ if len(title) != len(var_names):
2486
+ raise ValueError("title must have the same length as var_names")
2487
+
2488
+ ncols = min(len(var_names), ncols)
2489
+ nrows = len(var_names) // ncols + (1 if len(var_names) % ncols != 0 else 0)
2490
+
2491
+ if figsize is None:
2492
+ figsize = (3.5 * ncols, 3.5 * nrows)
2493
+
2494
+ if ax:
2495
+ tight_layout = False
2496
+ show = False
2497
+ return_ax = False
2498
+ fig = None
2499
+ axes = ax
2500
+ else:
2501
+ fig, axes = plt.subplots(nrows=nrows, ncols=ncols, figsize=figsize)
2502
+ tight_layout = True
2503
+ if show:
2504
+ return_ax = False
2505
+ else:
2506
+ return_ax = True
2507
+
2508
+
2509
+ if isinstance(axes, matplotlib.axes.Axes):
2510
+ axes_grid = np.array([[axes]])
2511
+ else:
2512
+ axes_arr = np.array(axes, dtype=object)
2513
+ if axes_arr.ndim == 0:
2514
+ axes_grid = np.array([[axes_arr.item()]])
2515
+ elif axes_arr.ndim == 1:
2516
+ total = nrows * ncols
2517
+ if axes_arr.size < total:
2518
+ raise ValueError("Provided axes contain fewer panels than required for the number of groups")
2519
+ axes_grid = axes_arr.flat[:total].reshape(nrows, ncols)
2520
+ elif axes_arr.ndim >= 2:
2521
+ total = nrows * ncols
2522
+ if axes_arr.size < total:
2523
+ raise ValueError("Provided axes contain fewer panels than required for the number of groups")
2524
+ axes_grid = axes_arr.flat[:total].reshape(nrows, ncols)
2525
+ else:
2526
+ raise TypeError("ax must be an Axes, a list/array of Axes, or None")
2527
+
2528
+ subset = shapdata[mask]
2529
+
2530
+ for i, v in enumerate(var_names):
2531
+ col = i % ncols
2532
+ row = i // ncols
2533
+ ax_i = axes_grid[row, col]
2534
+
2535
+ if isinstance(subset.obsm[obsm_key], pd.DataFrame):
2536
+ x = subset.obsm[obsm_key][v].values
2537
+ elif sp.issparse(subset.obsm[obsm_key]):
2538
+ idx = fates_used.index(v)
2539
+ x = subset.obsm[obsm_key][:, idx].toarray().ravel()
2540
+ else:
2541
+ idx = fates_used.index(v)
2542
+ x = subset.obsm[obsm_key][:, idx]
2543
+
2544
+ pred_key = f"{obsm_key}:predicted"
2545
+ if isinstance(subset.obsm[pred_key], pd.DataFrame):
2546
+ y = subset.obsm[pred_key][v].values
2547
+ elif sp.issparse(subset.obsm[pred_key]):
2548
+ idx = fates_used.index(v)
2549
+ y = subset.obsm[pred_key][:, idx].toarray().ravel()
2550
+ else:
2551
+ idx = fates_used.index(v)
2552
+ y = subset.obsm[pred_key][:, idx]
2553
+
2554
+ corr = _fast_corr(x, y, slope=True, significance=False, progress_bar=False)["r"][0][0]
2555
+
2556
+ current_line_kws = line_kws[i]
2557
+ current_scatter_kws = scatter_kws[i]
2558
+
2559
+ if "color" not in current_line_kws.keys():
2560
+ current_line_kws["color"] = sns.color_palette()[3]
2561
+ if "color" not in current_scatter_kws.keys():
2562
+ current_scatter_kws["color"] = "black"
2563
+ if "alpha" not in current_scatter_kws.keys():
2564
+ current_scatter_kws["alpha"] = 0.8
2565
+ if "s" not in current_scatter_kws.keys():
2566
+ current_scatter_kws["s"] = 15
2567
+
2568
+ sns.regplot(
2569
+ x=x,
2570
+ y=y,
2571
+ ax=ax_i,
2572
+ scatter_kws=current_scatter_kws,
2573
+ line_kws=current_line_kws,
2574
+ **kwargs[i],
2575
+ )
2576
+ line = ax_i.get_lines()[-1]
2577
+ line.set_label(f"r = {corr:.3f}")
2578
+ ax_i.legend(loc="best")
2579
+ if title[i] is None:
2580
+ ax_i.set_title(v)
2581
+ else:
2582
+ ax_i.set_title(title[i])
2583
+ ax_i.grid(alpha=0.3)
2584
+ ax_i.set_xlabel("Observed")
2585
+ ax_i.set_ylabel("Predicted")
2586
+
2587
+ for i in range(len(var_names), ncols * nrows):
2588
+ axes_grid[i // ncols, i % ncols].axis("off")
2589
+
2590
+ if tight_layout:
2591
+ fig.tight_layout()
2592
+
2593
+ if return_fig:
2594
+ return fig
2595
+ elif return_ax:
2596
+ return axes_grid.flat[:len(var_names)]
2597
+ elif show:
2598
+ plt.show()
2599
+
2600
+
2601
+ def clones2cells(
2602
+ adata: sc.AnnData,
2603
+ clones: sc.AnnData,
2604
+ obs_name: str | None = None,
2605
+ cells_color: str | None = None,
2606
+ clones_color: str | None = None,
2607
+ mode: Literal["highlite", "filter"] = "highlite",
2608
+ cells_basis: str = "X_umap",
2609
+ clones_basis: str = "X_umap",
2610
+ keep_color: bool = False,
2611
+ bg_color: str = "lightgrey",
2612
+ selected_color: str = "red",
2613
+ cells_cmap: str | None = None,
2614
+ clones_cmap: str | None = None,
2615
+ cells_palette: str | None = None,
2616
+ clones_palette: str | None = None,
2617
+ s_cells_bg: int = 1,
2618
+ s_cells_selected: int = 2,
2619
+ s_clones: int = 6,
2620
+ width: float = "auto",
2621
+ height: float = 400,
2622
+ axes: bool = False,
2623
+ norm_clones: tuple[float, float] | None = None,
2624
+ norm_cells: tuple[float, float] | None = None,
2625
+ ) -> None:
2626
+ """
2627
+ Draws two interactive sctterplots with gene expression (left) and clonal (right) embeddings.
2628
+ Selection on the right plot leads to the highliting (`mode='highlite'`) or filtering (`mode='filter'`)
2629
+ of cells from the corresponding clones. Selection on the left plot leads to coloring the right plot
2630
+ by the proportion of selected cells in clones.
2631
+
2632
+ Parameters
2633
+ ----------
2634
+ adata : sc.AnnData
2635
+ Annotated data matrix with gene expression.
2636
+ clones : sc.AnnData
2637
+ Annotated data matrix with clonal embeddings.
2638
+ obs_name : str, optional
2639
+ Name of column in `clones.obs` with clone labels in gene expression AnnData.
2640
+ If not provided, will be taken from `clones.uns["obs_name"]`.
2641
+ cells_color : str, optional
2642
+ Name of column in `adata.obs` with cells colors. If not provided,
2643
+ cells will be colored in `bg_color`.
2644
+ clones_color : str, optional
2645
+ Name of column in `clones.obs` with clones colors. If not provided,
2646
+ clones will be colored in `bg_color`.
2647
+ mode : {"highlite", "filter"}, optional
2648
+ Whether to highlite (`mode='highlite'`) or filter (`mode='filter'`) cells
2649
+ from the selected clones.
2650
+ cells_basis : str, optional
2651
+ Name of key in `adata.obsm` with cells embeddings.
2652
+ clones_basis : str, optional
2653
+ Name of key in `clones.obsm` with clonal embeddings.
2654
+ keep_color : bool, optional
2655
+ Whether to keep color of cells in `cells_color` for `mode='highlite'`.
2656
+ bg_color : str, optional
2657
+ Color of unselected cells or clones.
2658
+ selected_color : str, optional
2659
+ Color of selected cells if `mode='highlite'` and `keep_color=False`.
2660
+ cells_cmap : str, optional
2661
+ Continuous color map for cells.
2662
+ clones_cmap : str, optional
2663
+ Continuous color map for clones.
2664
+ cells_palette : str, optional
2665
+ Palette (discrete colormap) for cells. If None, standard scanpy's procedure
2666
+ for categorical coloring is used.
2667
+ clones_palette : str, optional
2668
+ Palette (discrete colormap) for clones. If None, standard scanpy's procedure
2669
+ for categorical coloring is used.
2670
+ s_cells_bg : int, optional
2671
+ Size of unselected cells.
2672
+ s_cells_selected : int, optional
2673
+ Size of selected cells.
2674
+ s_clones : int, optional
2675
+ Size of clones.
2676
+ width : float, optional
2677
+ Width of widget.
2678
+ height : float, optional
2679
+ Height of widget.
2680
+ axes : bool, optional
2681
+ Whether to show axes.
2682
+ norm_clones : tuple[float, float], optional
2683
+ Range of values for clonal embeddings normalization.
2684
+ norm_cells : tuple[float, float], optional
2685
+ Range of values for gene expression embeddings normalization.
2686
+
2687
+ Returns
2688
+ -------
2689
+ None
2690
+ """
2691
+ try:
2692
+ import ipywidgets as widgets
2693
+ import jscatter as js
2694
+ except ImportError:
2695
+ raise ImportError("`ipywidgets` and `jscatter` are required for clones2cells. Please install them via pip: `pip install ipywidgets jscatter`.")
2696
+
2697
+ logg.warning("Widget might be displayed incorrectly in Safari browser")
2698
+
2699
+ if obs_name is None:
2700
+ obs_name = clones.uns["obs_name"]
2701
+
2702
+ df_gex, cmap_gex = _prepare_c2c(
2703
+ adata=adata,
2704
+ obsm=cells_basis,
2705
+ clone_col=obs_name,
2706
+ color=cells_color,
2707
+ cmap=cells_cmap,
2708
+ palette=cells_palette,
2709
+ )
2710
+
2711
+ if cmap_gex:
2712
+ df_gex = df_gex.sort_values("c")
2713
+
2714
+ df_clones, cmap_clones = _prepare_c2c(
2715
+ adata=clones,
2716
+ obsm=clones_basis,
2717
+ color=clones_color,
2718
+ cmap=clones_cmap,
2719
+ palette=clones_palette,
2720
+ )
2721
+ if cmap_clones:
2722
+ df_clones = df_clones.sort_values("c")
2723
+
2724
+ if cmap_gex and (type(cmap_gex) != dict) and (mode == "highlite"):
2725
+ if keep_color:
2726
+ logg.warning("`keep_color=True` isn't supported in `mode='highlite'`. Switching to `keep_color=False`")
2727
+ keep_color = False
2728
+ cat_gex = False
2729
+ else:
2730
+ cat_gex = True
2731
+
2732
+ if (mode == "highlite") and (cmap_gex is None):
2733
+ keep_color = False
2734
+
2735
+ clones_whitelist = df_clones["clone"].values
2736
+ clone_sizes = df_gex["clone"].value_counts()[clones_whitelist]
2737
+
2738
+ if mode == "highlite":
2739
+ in_clones = df_gex.clone.isin(clones_whitelist).values
2740
+
2741
+ bg_mask = np.array([True] * len(df_gex) + [False] * sum(in_clones))
2742
+ bg_idx = np.argwhere(bg_mask).T[0]
2743
+
2744
+ clone_mask = ~bg_mask
2745
+ clone_idx = np.argwhere(clone_mask).T[0]
2746
+
2747
+ df_gex = pd.concat([df_gex, df_gex[in_clones]]).reset_index(drop=True)
2748
+
2749
+ if keep_color:
2750
+ df_gex["c_select"] = df_gex["c"].astype(str).copy()
2751
+ df_gex.loc[bg_mask, "c_select"] = "Unselected cells"
2752
+ df_gex["c_select"] = df_gex["c_select"].astype("category")
2753
+ df_gex["c_select"] = df_gex["c_select"].cat.reorder_categories(
2754
+ list(df_gex["c"].cat.categories) + ["Unselected cells"]
2755
+ )
2756
+
2757
+ cmap_select = cmap_gex.copy()
2758
+ cmap_select["Unselected cells"] = bg_color
2759
+
2760
+ df_gex["s_select"] = "Cells in clones"
2761
+ df_gex.loc[bg_mask, "s_select"] = "Unselected cells"
2762
+ df_gex["s_select"] = df_gex["s_select"].astype("category")
2763
+
2764
+ size_select = {
2765
+ "Unselected cells": s_cells_bg,
2766
+ "Cells in clones": s_cells_selected,
2767
+ }
2768
+ else:
2769
+ df_gex["c_select"] = "Cells in clones"
2770
+ df_gex.loc[bg_mask, "c_select"] = "Unselected cells"
2771
+ df_gex["c_select"] = df_gex["c_select"].astype("category")
2772
+
2773
+ cmap_select = {
2774
+ "Unselected cells": bg_color,
2775
+ "Cells in clones": selected_color,
2776
+ }
2777
+
2778
+ df_gex["s_select"] = "Cells in clones"
2779
+ df_gex.loc[bg_mask, "s_select"] = "Unselected cells"
2780
+ df_gex["s_select"] = df_gex["s_select"].astype("category")
2781
+
2782
+ size_select = {
2783
+ "Unselected cells": s_cells_bg,
2784
+ "Cells in clones": s_cells_selected,
2785
+ }
2786
+ else:
2787
+ bg_idx = None
2788
+
2789
+ if cmap_gex is None:
2790
+ df_gex["c"] = "Unselected cells"
2791
+ cmap_gex = {"Unselected cells": bg_color}
2792
+ gex_legend = False
2793
+ else:
2794
+ gex_legend = True
2795
+
2796
+ scatter_gex = js.Scatter(x="x", y="y", width=width, height=height, opacity=1,
2797
+ size=s_cells_bg, data=df_gex, axes=axes)
2798
+
2799
+ scatter_gex.color(by="c", map=cmap_gex, labeling={"variable": None}, norm=norm_cells)
2800
+ scatter_gex.filter(bg_idx)
2801
+ scatter_gex.size(s_cells_bg)
2802
+ scatter_gex.legend(legend=gex_legend)
2803
+
2804
+ if cmap_clones is None:
2805
+ df_clones["c"] = "Unselected"
2806
+ cmap_clones = {"Unselected": bg_color}
2807
+ clones_legend = False
2808
+ else:
2809
+ clones_legend = True
2810
+
2811
+ if pd.api.types.is_numeric_dtype(df_clones["c"]):
2812
+ if norm_clones is None:
2813
+ norm_clones = (df_clones["c"].min(), df_clones["c"].max())
2814
+
2815
+ scatter_c2v = js.Scatter(x="x", y="y", width=width, height=height, opacity=1,
2816
+ size=s_clones, data=df_clones, axes=axes)
2817
+
2818
+ scatter_c2v.color(by="c", map=cmap_clones, labeling={"variable": None}, norm=norm_clones)
2819
+ scatter_c2v.legend(clones_legend)
2820
+
2821
+ def c2v_selection(change):
2822
+ if len(change.new) == 0:
2823
+ scatter_gex.color(by="c", map=cmap_gex, labeling={"variable": None}, norm=norm_cells)
2824
+ scatter_gex.filter(bg_idx)
2825
+ scatter_gex.size(s_cells_bg)
2826
+ scatter_gex.legend(gex_legend)
2827
+ else:
2828
+ clones.uns["clones2cells"] = {"last_selection": df_clones.clone.values[change.new]}
2829
+ if mode == "filter":
2830
+ selected_clones = df_clones.clone.values[change.new]
2831
+ selected_cells = np.argwhere(df_gex.clone.isin(selected_clones)).T[0]
2832
+ scatter_gex.filter(selected_cells)
2833
+ scatter_gex.size(s_cells_selected)
2834
+ else:
2835
+ scatter_gex.legend(False)
2836
+ selected_clones = df_clones.clone.values[change.new]
2837
+ selected_cells = np.argwhere(
2838
+ df_gex.clone.isin(selected_clones) | bg_mask
2839
+ ).T[0]
2840
+
2841
+ scatter_gex.color(by="c_select", map=cmap_select, norm=norm_cells)
2842
+ scatter_gex.size(by="s_select", map=size_select)
2843
+ scatter_gex.filter(selected_cells)
2844
+
2845
+ scatter_c2v.widget.observe(c2v_selection, names=["selection"])
2846
+
2847
+ if clones_cmap is None:
2848
+ clones_cmap = "viridis"
2849
+
2850
+ def gex_selection(change):
2851
+ if len(change.new) == 0:
2852
+ scatter_c2v.color(by="c", map=cmap_clones, labeling={"variable": None}, norm=norm_clones)
2853
+ scatter_c2v.legend(clones_legend)
2854
+ else:
2855
+ selected_cell_bcs = df_gex.cell.values[change.new]
2856
+ selected_cell_bcs = np.array(list(set(selected_cell_bcs)))
2857
+ adata.uns["clones2cells"] = {"last_selection": selected_cell_bcs}
2858
+ if mode == "filter":
2859
+ df_clones["proportions_selected"] = (
2860
+ df_gex.iloc[change.new].clone.value_counts()[clones_whitelist] /
2861
+ clone_sizes
2862
+ )[df_clones.clone.values] * 100
2863
+ scatter_c2v.color(
2864
+ by="proportions_selected",
2865
+ map=clones_cmap,
2866
+ norm=(0, df_clones["proportions_selected"].max()),
2867
+ labeling={"variable": "% of selected"}
2868
+ )
2869
+ scatter_c2v.legend(legend=True)
2870
+ else:
2871
+ selected_mask = np.array([False] * len(df_gex))
2872
+ selected_mask[change.new] = True
2873
+
2874
+ df_clones["proportions_selected"] = (
2875
+ df_gex
2876
+ .iloc[selected_mask]
2877
+ .clone.value_counts()[clones_whitelist] /
2878
+ clone_sizes
2879
+ )[df_clones.clone].values.astype(float) * 100
2880
+
2881
+ scatter_c2v.color(
2882
+ by="proportions_selected",
2883
+ map=clones_cmap,
2884
+ norm=(0, df_clones["proportions_selected"].max()),
2885
+ labeling={"variable": "% of selected"}
2886
+ )
2887
+ scatter_c2v.legend(legend=True)
2888
+
2889
+ scatter_gex.widget.observe(gex_selection, names=["selection"])
2890
+
2891
+ display(js.compose([
2892
+ (scatter_gex, "Gene expression embedding"),
2893
+ (scatter_c2v, "Clonal embedding"),
2894
+ ], row_height=height))
2895
+
2896
+ def small_cbar(
2897
+ axes: matplotlib.axes.Axes | list[matplotlib.axes.Axes],
2898
+ width: float = 0.03,
2899
+ height: float = 0.20,
2900
+ fontsize: int = 10,
2901
+ ticks_round: int = 2,
2902
+ x_pad: float = 0.02,
2903
+ y_pad: float = 0,
2904
+ show_numbers: bool = True,
2905
+ ):
2906
+ """
2907
+ Adds small colorbars to the right of the specified axes.
2908
+
2909
+ Parameters:
2910
+ -----------
2911
+ axes : matplotlib.axes.Axes | list[matplotlib.axes.Axes]
2912
+ The axes object(s) to draw on (e.g., fig.axes[0]).
2913
+ width : float, optional
2914
+ Width of the colorbar. Default 3%.
2915
+ height : float, optional
2916
+ Height of each colorbar. Default 20%.
2917
+ fontsize : int, optional
2918
+ Font size for tick labels. Default 10.
2919
+ ticks_round : int, optional
2920
+ Number of decimal places to round tick labels. Default 2.
2921
+ x_pad : float, optional
2922
+ Padding from the right edge (0.0 to 1.0). Default 2%.
2923
+ y_pad : float, optional
2924
+ Padding from the top edge (0.0 to 1.0). Default 0%.
2925
+ show_numbers : bool, optional
2926
+ Whether to show numeric tick labels. Default True.
2927
+ """
2928
+ if not isinstance(axes, Iterable):
2929
+ axes = [axes]
2930
+
2931
+ for ax in axes:
2932
+ mappables = [m for m in ax.collections if m.colorbar is not None]
2933
+ if not mappables:
2934
+ continue
2935
+
2936
+ for i, m in enumerate(mappables):
2937
+ m.colorbar.remove()
2938
+
2939
+ x_pos = 1.0 - width + x_pad
2940
+ y_pos = y_pad + (i * (height + 0.05))
2941
+
2942
+ cax = ax.inset_axes([x_pos, y_pos, width, height], transform=ax.transAxes)
2943
+ cbar = plt.colorbar(m, cax=cax, orientation="vertical")
2944
+
2945
+ vmin, vmax = m.get_clim()
2946
+
2947
+ ticks = [vmin, vmax]
2948
+ cbar.set_ticks(ticks)
2949
+
2950
+ if not show_numbers:
2951
+ cbar.ax.set_yticklabels(["Min", "Max"])
2952
+ elif ticks_round is not None:
2953
+ cbar.ax.set_yticklabels(
2954
+ [f"{np.round(x, ticks_round)}" for x in ticks],
2955
+ fontsize=fontsize
2956
+ )
2957
+
2958
+ cbar.outline.set_edgecolor("black")
2959
+ cbar.outline.set_linewidth(1)
2960
+
2961
+ def embedding_axis(
2962
+ axes: matplotlib.axes.Axes | list[matplotlib.axes.Axes],
2963
+ x_offset: float = 0.,
2964
+ y_offset: float = 0.,
2965
+ length: float = 0.15,
2966
+ arrow_width: float = 0.0001,
2967
+ head_width: float = 0.02,
2968
+ color: str = "black",
2969
+ label: str = "UMAP",
2970
+ label1: str | None = None,
2971
+ label2: str | None = None,
2972
+ font_size: int = 10.
2973
+ ):
2974
+ """
2975
+ Adds two perpendicular arrows (L-shape) to the bottom-left corner of the plot
2976
+ to mimic standard single-cell embedding visualizations (Seurat/Scanpy).
2977
+
2978
+ Parameters:
2979
+ -----------
2980
+ axes : matplotlib.axes.Axes | list[matplotlib.axes.Axes]
2981
+ The axes object to draw on (e.g., fig.axes[0]).
2982
+ x_offset : float, optional
2983
+ Distance from left edge (0.0 to 1.0). Default 5%.
2984
+ y_offset : float, optional
2985
+ Distance from bottom edge (0.0 to 1.0). Default 5%.
2986
+ length : float, optional
2987
+ Length of the arrows as a fraction of the axes size. Default 15%.
2988
+ arrow_width : float, optional
2989
+ Width of the arrow shaft. Default 0.0001.
2990
+ head_width : float, optional
2991
+ Width of the arrow head. Default 0.02.
2992
+ color : str, optional
2993
+ Color of arrows and text. Default "black".
2994
+ label : str, optional
2995
+ Label for the horizontal and vertical arrows. Default "UMAP".
2996
+ label1 : str, optional
2997
+ Label for the horizontal arrow. If None, label + " 1" is used. Default None.
2998
+ label2 : str, optional
2999
+ Label for the vertical arrow. If None, label + " 2" is used. Default None.
3000
+ font_size : int, optional
3001
+ Size of the text labels. Default 10.
3002
+ """
3003
+ if not isinstance(axes, Iterable):
3004
+ axes = [axes]
3005
+
3006
+ for ax in axes:
3007
+ ax.set_axis_off()
3008
+
3009
+ arrow_props = {
3010
+ "fc": color,
3011
+ "ec": color,
3012
+ "width": arrow_width,
3013
+ "head_width": head_width,
3014
+ "head_length": head_width,
3015
+ "transform": ax.transAxes,
3016
+ "length_includes_head": True,
3017
+ "overhang": 0.2,
3018
+ "clip_on": False,
3019
+ }
3020
+
3021
+ ax.arrow(x_offset, y_offset, length, 0, **arrow_props)
3022
+ ax.arrow(x_offset, y_offset, 0, length, **arrow_props)
3023
+
3024
+ text_offset = 0.02
3025
+ if label1 is None:
3026
+ label1 = label + " 1"
3027
+ ax.text(
3028
+ x_offset,
3029
+ y_offset - (text_offset * 1.5),
3030
+ label1,
3031
+ transform=ax.transAxes,
3032
+ ha="left",
3033
+ va="top",
3034
+ fontsize=font_size,
3035
+ color=color,
3036
+ )
3037
+
3038
+ if label2 is None:
3039
+ label2 = label + " 2"
3040
+ ax.text(
3041
+ x_offset - (text_offset * 1.5),
3042
+ y_offset,
3043
+ label2,
3044
+ transform=ax.transAxes,
3045
+ ha="right",
3046
+ va="bottom",
3047
+ rotation=90,
3048
+ fontsize=font_size,
3049
+ color=color,
3050
+ )
3051
+
3052
+ def fancy_legend(
3053
+ axes,
3054
+ textsize: int = 10,
3055
+ fontweight: str = "normal",
3056
+ center_loc: bool = False,
3057
+ line: bool = False,
3058
+ max_distance: float = 0.2,
3059
+ **kwargs,
3060
+ ):
3061
+ """
3062
+ Adds a legend to the plot with cluster labels aligned to the cluster centers.
3063
+
3064
+ Parameters:
3065
+ -----------
3066
+ axes : matplotlib.axes.Axes | list[matplotlib.axes.Axes]
3067
+ The axes object to draw on (e.g., fig.axes[0]).
3068
+ textsize : int, optional
3069
+ Size of the text labels. Default 10.
3070
+ fontweight : str, optional
3071
+ Font weight of the text labels. Default "normal".
3072
+ **kwargs : dict, optional
3073
+ Additional keyword arguments passed to textalloc.alloc().
3074
+ """
3075
+
3076
+ import textalloc as ta
3077
+ import matplotlib.colors as mcolors
3078
+
3079
+ if not isinstance(axes, Iterable):
3080
+ axes = [axes]
3081
+
3082
+ for ax in axes:
3083
+ legend = ax.get_legend()
3084
+ handles = legend.legend_handles
3085
+ texts = legend.get_texts()
3086
+
3087
+ legend_map = {}
3088
+ for handle, text in zip(handles, texts):
3089
+ c = handle.get_facecolor()[0]
3090
+ c_hex = mcolors.to_hex(c)
3091
+ legend_map[c_hex] = text.get_text()
3092
+
3093
+ cluster_points = {label: [] for label in legend_map.values()}
3094
+ cluster_colors = {label: color for color, label in legend_map.items()}
3095
+
3096
+ all_x_points = []
3097
+ all_y_points = []
3098
+
3099
+ for collection in ax.collections:
3100
+ offsets = collection.get_offsets()
3101
+ facecolors = collection.get_facecolors()
3102
+
3103
+ if len(offsets) > 0:
3104
+ all_x_points.extend(offsets[:, 0])
3105
+ all_y_points.extend(offsets[:, 1])
3106
+
3107
+ if len(facecolors) == 1:
3108
+ c_hex = mcolors.to_hex(facecolors[0])
3109
+ if c_hex in legend_map:
3110
+ label = legend_map[c_hex]
3111
+ cluster_points[label].extend(offsets)
3112
+ elif len(facecolors) == len(offsets):
3113
+ for i, point in enumerate(offsets):
3114
+ c_hex = mcolors.to_hex(facecolors[i])
3115
+ if c_hex in legend_map:
3116
+ label = legend_map[c_hex]
3117
+ cluster_points[label].append(point)
3118
+
3119
+ cluster_centers = {}
3120
+ for label, points in cluster_points.items():
3121
+ if len(points) > 0:
3122
+ pts = np.array(points)
3123
+ cluster_centers[label] = np.median(pts, axis=0)
3124
+
3125
+ legend.remove()
3126
+
3127
+ labels = []
3128
+ x_pos = []
3129
+ y_pos = []
3130
+ colors = []
3131
+
3132
+ for label, center in cluster_centers.items():
3133
+ labels.append(label)
3134
+ x_pos.append(center[0])
3135
+ y_pos.append(center[1])
3136
+ colors.append(cluster_colors[label])
3137
+
3138
+ if not center_loc:
3139
+ _, _, texts, _ = ta.allocate(
3140
+ ax=ax,
3141
+ textsize=textsize,
3142
+ fontweight=fontweight,
3143
+ x=np.array(x_pos),
3144
+ y=np.array(y_pos),
3145
+ text_list=labels,
3146
+ x_scatter=np.array(all_x_points),
3147
+ y_scatter=np.array(all_y_points),
3148
+ draw_lines=line,
3149
+ linewidth=0.5,
3150
+ linecolor=colors,
3151
+ draw_all=True,
3152
+ max_distance=max_distance,
3153
+ textcolor=colors,
3154
+ bbox={
3155
+ "boxstyle": "round,pad=0.2",
3156
+ "pad": 3,
3157
+ "facecolor": "white",
3158
+ "edgecolor": "black",
3159
+ "alpha": 0.85,
3160
+ "lw": 0.5,
3161
+ },
3162
+ **kwargs,
3163
+ )
3164
+ else:
3165
+ texts = []
3166
+ for lbl, x, y, c in zip(labels, x_pos, y_pos, colors):
3167
+ t = ax.text(
3168
+ x,
3169
+ y,
3170
+ lbl,
3171
+ fontsize=textsize,
3172
+ fontweight=fontweight,
3173
+ color=c,
3174
+ ha="center",
3175
+ va="center_baseline",
3176
+ bbox={
3177
+ "boxstyle": "round,pad=0.2",
3178
+ "pad": 3,
3179
+ "facecolor": "white",
3180
+ "edgecolor": "black",
3181
+ "alpha": 0.85,
3182
+ "lw": 0.5,
3183
+ },
3184
+ )
3185
+ texts.append(t)
3186
+
3187
+ for text_artist, color in zip(texts, colors):
3188
+ bbox = text_artist.get_bbox_patch()
3189
+ bbox.set_edgecolor(color)
3190
+ text_artist.set_verticalalignment("center_baseline")
3191
+
3192
+ def scaled_dotplot(
3193
+ adata: sc.AnnData,
3194
+ groupby: str,
3195
+ var_names: list[str],
3196
+ cmap: str = "RdBu_r",
3197
+ vmin: float = -2.5,
3198
+ vmax: float = 2.5,
3199
+ colorbar_title: str = "Mean Z-score",
3200
+ max_value: float = 5.,
3201
+ **kwargs
3202
+ ):
3203
+ """
3204
+ Function plots dotplot colored by scaled expression values. The problem with
3205
+ sc.pl.dotplot is that dot_size is defined by amount of the expression values
3206
+ more or equal than 0, and for scaled expressions it's not the correct case.
3207
+
3208
+ Parameters
3209
+ ----------
3210
+ adata : sc.AnnData
3211
+ Annotated data matrix.
3212
+ groupby : str
3213
+ Key for observations grouping.
3214
+ var_names : list[str]
3215
+ List of genes to plot.
3216
+ cmap : str
3217
+ Colormap to use. Default is "RdBu_r".
3218
+ vmin : float
3219
+ Minimum value for color scaling. Default is -2.5.
3220
+ vmax : float
3221
+ Maximum value for color scaling. Default is 2.5.
3222
+ colorbar_title : str
3223
+ Title for the colorbar. Default is "Mean Z-score".
3224
+ max_value : float
3225
+ Maximum value for scaling expression values. Default is 5.
3226
+ **kwargs
3227
+ Additional keyword arguments to pass to sc.pl.dotplot.
3228
+
3229
+ Returns
3230
+ -------
3231
+ matplotlib.axes.Axes
3232
+ Axes object with the dotplot.
3233
+ """
3234
+
3235
+ if adata.raw:
3236
+ adata_scaled = adata.raw[:, var_names].to_adata().copy()
3237
+ else:
3238
+ adata_scaled = adata[:, var_names].copy()
3239
+
3240
+ sc.pp.scale(adata_scaled, max_value=max_value)
3241
+ color_df = sc.pl.DotPlot(
3242
+ adata_scaled,
3243
+ var_names=var_names,
3244
+ groupby=groupby,
3245
+ ).dot_color_df
3246
+
3247
+ return sc.pl.dotplot(
3248
+ adata,
3249
+ groupby=groupby,
3250
+ var_names=var_names,
3251
+ dot_color_df=color_df,
3252
+ cmap=cmap,
3253
+ vmax=vmax,
3254
+ vmin=vmin,
3255
+ colorbar_title=colorbar_title,
3256
+ show=False,
3257
+ **kwargs,
3258
+ )
3259
+
3260
+ def scatter2vars(
3261
+ adata: sc.AnnData,
3262
+ var1: str,
3263
+ var2: str,
3264
+ clip1: tuple[float, float] | None = None,
3265
+ clip2: tuple[float, float] | None = None,
3266
+ c1: Literal["red", "green", "blue"] = "red",
3267
+ c2: Literal["red", "green", "blue"] = "blue",
3268
+ basis: str = "X_umap",
3269
+ use_raw: bool | None = None,
3270
+ components: str | None = None,
3271
+ s: float | None = None,
3272
+ alpha: float = 1.,
3273
+ frameon: bool = True,
3274
+ title: str | None = None,
3275
+ ax: matplotlib.axes.Axes | None = None,
3276
+ rasterize: bool = False,
3277
+ ticks: bool = False,
3278
+ round_ticks: int = 2,
3279
+ bright_level: float = 0.8,
3280
+ grey_level: float = 0.9,
3281
+ show: bool = True,
3282
+ return_fig: bool = False,
3283
+ cbar: bool = True,
3284
+ figsize: tuple[float, float] | None = None,
3285
+ ) -> matplotlib.axes.Axes | matplotlib.figure.Figure | None:
3286
+ """
3287
+ Plots embedding colored by two continious variables.
3288
+
3289
+ Parameters
3290
+ ----------
3291
+ adata : sc.AnnData
3292
+ Annotated data matrix.
3293
+ var1 : str
3294
+ Key for variable 1.
3295
+ var2 : str
3296
+ Key for variable 2.
3297
+ clip1 : tuple[float, float] | None
3298
+ Clip values for variable 1. Default is None.
3299
+ clip2 : tuple[float, float] | None
3300
+ Clip values for variable 2. Default is None.
3301
+ c1 : Literal["red", "green", "blue"]
3302
+ Color for variable 1. Default is "red".
3303
+ c2 : Literal["red", "green", "blue"]
3304
+ Color for variable 2. Default is "blue".
3305
+ basis : str
3306
+ Key for embedding. Default is "X_umap".
3307
+ use_raw : bool | None
3308
+ Whether to use raw data. Default is None.
3309
+ components : str | None
3310
+ Components to use. Default is None.
3311
+ s : float | None
3312
+ Size of points. Default is None.
3313
+ alpha : float
3314
+ Transparency of points. Default is 1.
3315
+ frameon : bool
3316
+ Whether to draw frame. Default is True.
3317
+ title : str | None
3318
+ Title for the plot. Default is None.
3319
+ ax : matplotlib.axes.Axes | None
3320
+ Axes object to draw on. Default is None.
3321
+ rasterize : bool
3322
+ Whether to rasterize points. Default is False.
3323
+ ticks : bool
3324
+ Whether to draw ticks. Default is False.
3325
+ round_ticks : int
3326
+ Number of decimal places to round ticks. Default is 2.
3327
+ bright_level : float
3328
+ Brightness level for points. Default is 0.8.
3329
+ grey_level : float
3330
+ Grey level for points. Default is 0.9.
3331
+ show : bool
3332
+ Whether to show the plot. Default is True.
3333
+ return_fig : bool
3334
+ Whether to return figure object. Default is False.
3335
+ cbar : bool
3336
+ Whether to draw colorbar. Default is True.
3337
+ figsize : tuple[float, float] | None
3338
+ Figure size. Default is None.
3339
+
3340
+ Returns
3341
+ -------
3342
+ matplotlib.axes.Axes | matplotlib.figure.Figure | None
3343
+ Axes object with the plot or figure if return_fig is True. None if show is False.
3344
+ """
3345
+
3346
+ from mpl_toolkits.axes_grid1.inset_locator import inset_axes
3347
+
3348
+ if components is None:
3349
+ components = "0,1"
3350
+ components = np.array(components.split(",")).astype(int)
3351
+
3352
+ if s is None:
3353
+ s = 60000 / len(adata)
3354
+
3355
+ if use_raw is None:
3356
+ if adata.raw:
3357
+ use_raw = True
3358
+ else:
3359
+ use_raw = False
3360
+
3361
+ expressions = sc.get.obs_df(adata, keys=[var1, var2], use_raw=use_raw)
3362
+
3363
+ if clip1 is None:
3364
+ clip1 = (expressions[var1].min(), expressions[var1].max())
3365
+ else:
3366
+ clip1 = np.array(clip1)
3367
+ if clip1[0] is None:
3368
+ clip1[0] = expressions[var1].min()
3369
+ if clip1[1] is None:
3370
+ clip1[1] = expressions[var1].max()
3371
+ clip1 = tuple(clip1)
3372
+
3373
+ if clip2 is None:
3374
+ clip2 = (expressions[var2].min(), expressions[var2].max())
3375
+ else:
3376
+ clip2 = np.array(clip2)
3377
+ if clip2[0] is None:
3378
+ clip2[0] = expressions[var2].min()
3379
+ if clip2[1] is None:
3380
+ clip2[1] = expressions[var2].max()
3381
+ clip2 = tuple(clip2)
3382
+
3383
+ expressions[var1] = np.clip(expressions[var1], *clip1)
3384
+ expressions[var2] = np.clip(expressions[var2], *clip2)
3385
+ expressions[var1] = (expressions[var1] - clip1[0]) / (clip1[1] - clip1[0])
3386
+ expressions[var2] = (expressions[var2] - clip2[0]) / (clip2[1] - clip2[0])
3387
+
3388
+ order = expressions.sum(axis=1).sort_values().index
3389
+ expressions = expressions.loc[order]
3390
+ emb = adata[order].obsm[basis][:, components]
3391
+
3392
+ if c1 not in ["red", "blue", "green"]:
3393
+ logg.warning(f"Color {c1} is not supported. Backing up to red.")
3394
+ c1 = "red"
3395
+ if c2 not in ["red", "blue", "green"]:
3396
+ logg.warning(f"Color {c2} is not supported. Backing up to blue.")
3397
+ c2 = "blue"
3398
+ if c1 == c2:
3399
+ logg.warning("Colors for var1 and var2 are the same. Backing up to red and blue.")
3400
+ c1 = "red"
3401
+ c2 = "blue"
3402
+
3403
+ color_basis = {
3404
+ "red": np.array([1, 0, 0]),
3405
+ "green": np.array([0, 0.8, 0]),
3406
+ "blue": np.array([0, 0, 1]),
3407
+ }
3408
+
3409
+ c_00 = np.array([grey_level, grey_level, grey_level])
3410
+ c_10 = bright_level * color_basis[c1]
3411
+ c_01 = bright_level * color_basis[c2]
3412
+ c_11 = bright_level / 2 * (color_basis[c1] + color_basis[c2])
3413
+
3414
+ a = np.asarray(expressions[[var1]])
3415
+ b = np.asarray(expressions[[var2]])
3416
+
3417
+ cell_colors = (
3418
+ (1 - a) * (1 - b) * c_00 +
3419
+ a * (1 - b) * c_10 +
3420
+ (1 - a) * b * c_01 +
3421
+ a * b * c_11
3422
+ )
3423
+ cell_colors = np.clip(cell_colors, 0, 1)
3424
+
3425
+ if figsize is None:
3426
+ figsize = (4, 4)
3427
+
3428
+ if ax:
3429
+ show = False
3430
+ return_ax = False
3431
+ fig = ax.figure
3432
+ else:
3433
+ fig, ax = plt.subplots(figsize=figsize)
3434
+ if show:
3435
+ return_ax = False
3436
+ else:
3437
+ return_ax = True
3438
+
3439
+ ax.scatter(
3440
+ emb[:, 0],
3441
+ emb[:, 1],
3442
+ c=cell_colors,
3443
+ s=s,
3444
+ alpha=alpha,
3445
+ edgecolor="None",
3446
+ rasterized=rasterize,
3447
+ )
3448
+
3449
+ if basis == "X_umap":
3450
+ label = "UMAP"
3451
+ elif basis == "X_tsne":
3452
+ label = "t-SNE"
3453
+ elif basis == "X_pca":
3454
+ label = "PCA"
3455
+ elif basis == "X_draw_graph_fa":
3456
+ label = "ForceAtlas"
3457
+ elif basis == "X_pca_harmony":
3458
+ label = "Harmony"
3459
+ else:
3460
+ label = basis
3461
+
3462
+ if frameon:
3463
+ ax.set_xlabel(f"{label} {components[0]}")
3464
+ ax.set_ylabel(f"{label} {components[1]}")
3465
+ else:
3466
+ for spine in ax.spines.values():
3467
+ spine.set_visible(False)
3468
+ ticks = False
3469
+
3470
+ if not ticks:
3471
+ ax.set_xticks([])
3472
+ ax.set_yticks([])
3473
+
3474
+ if title is None:
3475
+ title = f"{var1} vs. {var2}"
3476
+
3477
+ ax.set_title(title)
3478
+
3479
+ # Inserting a legend
3480
+ if cbar:
3481
+ res = 100
3482
+
3483
+ l_a = np.linspace(0, 1, res)
3484
+ l_b = np.linspace(0, 1, res)
3485
+ L_A, L_B = np.meshgrid(l_a, l_b)
3486
+
3487
+ L_A_flat = L_A.flatten()[:, None]
3488
+ L_B_flat = L_B.flatten()[:, None]
3489
+
3490
+ legend_colors = (
3491
+ (1 - L_A_flat) * (1 - L_B_flat) * c_00 +
3492
+ L_A_flat * (1 - L_B_flat) * c_10 +
3493
+ (1 - L_A_flat) * L_B_flat * c_01 +
3494
+ L_A_flat * L_B_flat * c_11
3495
+ ).reshape(res, res, 3)
3496
+
3497
+ axins = inset_axes(
3498
+ ax,
3499
+ width="20%",
3500
+ height="20%",
3501
+ loc="upper left",
3502
+ bbox_to_anchor=(1.08, 0, 1, 1),
3503
+ bbox_transform=ax.transAxes,
3504
+ borderpad=0
3505
+ )
3506
+
3507
+ axins.imshow(legend_colors, origin="lower", extent=[0, 1, 0, 1])
3508
+
3509
+ axins.set_xlabel(var1, fontsize=9)
3510
+ axins.set_ylabel(var2, fontsize=9)
3511
+
3512
+ axins.xaxis.tick_top()
3513
+ axins.yaxis.tick_right()
3514
+
3515
+ axins.set_xticks([0, 0.5, 1])
3516
+ axins.set_yticks([0, 0.5, 1])
3517
+
3518
+ ticks1 = []
3519
+ for _ in [clip1[0], (clip1[1] - clip1[0]) / 2, clip1[1]]:
3520
+ ticks1.append(np.round(_, round_ticks))
3521
+ axins.set_xticklabels(ticks1, fontsize=7)
3522
+
3523
+ ticks2 = []
3524
+ for _ in [clip2[0], (clip2[1] - clip2[0]) / 2, clip2[1]]:
3525
+ ticks2.append(np.round(_, round_ticks))
3526
+ axins.set_yticklabels(ticks2, fontsize=7)
3527
+
3528
+ if return_fig:
3529
+ return fig
3530
+ elif return_ax:
3531
+ return ax
3532
+ elif show:
3533
+ plt.show()
3534
+
3535
+
3536
+ Reds = _cmap("Reds")
3537
+ Blues = _cmap("Blues")
3538
+ Greens = _cmap("Greens")
3539
+ Purples = _cmap("Purples")
3540
+ Oranges = _cmap("Oranges")