-
Notifications
You must be signed in to change notification settings - Fork 52
/
plot.py
2086 lines (1850 loc) · 72.4 KB
/
plot.py
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
from typing import Union, Optional, List, Tuple, Dict, Literal, Sequence
import collections.abc as cabc
import warnings
from copy import copy
from cycler import Cycler
import numpy as np
import pandas as pd
from sklearn.preprocessing import StandardScaler
from scipy.stats import gaussian_kde
import scanpy as sc
import mellon
import matplotlib
import matplotlib.pyplot as plt
import matplotlib.patheffects as PathEffects
from matplotlib.colors import Normalize, Colormap
from mpl_toolkits.axes_grid1 import make_axes_locatable
from scanpy.plotting._tools.scatterplots import (
_get_color_source_vector,
_color_vector,
_get_vboundnorm,
_get_palette,
_FontSize,
_FontWeight,
VBound,
)
from scanpy.plotting._utils import check_colornorm
from .presults import PResults
from .validation import (
_validate_obsm_key,
_validate_varm_key,
_validate_gene_trend_input,
)
from . import config
class FigureGrid:
"""
Generates a grid of axes for plotting
axes can be iterated over or selected by number. e.g.:
>>> # iterate over axes and plot some nonsense
>>> fig = FigureGrid(4, max_cols=2)
>>> for i, ax in enumerate(fig):
>>> plt.plot(np.arange(10) * i)
>>> # select axis using indexing
>>> ax3 = fig[3]
>>> ax3.set_title("I'm axis 3")
"""
# Figure Grid is favorable for displaying multiple graphs side by side.
def __init__(self, n: int, max_cols=3, scale=3):
"""
:param n: number of axes to generate
:param max_cols: maximum number of axes in a given row
"""
self.n = n
self.nrows = int(np.ceil(n / max_cols))
self.ncols = int(min((max_cols, n)))
figsize = self.ncols * scale, self.nrows * scale
# create figure
self.gs = plt.GridSpec(nrows=self.nrows, ncols=self.ncols)
self.figure = plt.figure(figsize=figsize)
# create axes
self.axes = {}
for i in range(n):
row = int(i // self.ncols)
col = int(i % self.ncols)
self.axes[i] = plt.subplot(self.gs[row, col])
def __getitem__(self, item):
return self.axes[item]
def __iter__(self):
for i in range(self.n):
yield self[i]
def get_fig(fig=None, ax=None):
"""
Fills in any missing axis or figure with the currently active one.
Parameters
----------
ax : matplotlib Axis object
fig : matplotlib Figure object
"""
if not fig:
fig = plt.figure()
if not ax:
ax = plt.gca()
return fig, ax
def density_2d(x, y):
"""
Return x and y and their density z, sorted by their density (smallest to largest).
Parameters
----------
x : array
y : array
"""
xy = np.vstack([np.ravel(x), np.ravel(y)])
z = gaussian_kde(xy)(xy)
i = np.argsort(z)
return np.ravel(x)[i], np.ravel(y)[i], np.arcsinh(z[i])
def plot_molecules_per_cell_and_gene(data, fig=None, ax=None):
height = 4
width = 12
fig = plt.figure(figsize=[width, height])
gs = plt.GridSpec(1, 3)
colsum = np.log10(data.sum(axis=0))
rowsum = np.log10(data.sum(axis=1))
for i in range(3):
ax = plt.subplot(gs[0, i])
if i == 0:
n, bins, patches = ax.hist(rowsum, bins="auto")
plt.xlabel("Molecules per cell (log10 scale)")
elif i == 1:
temp = np.log10(data.astype(bool).sum(axis=0))
n, bins, patches = ax.hist(temp, bins="auto")
plt.xlabel("Nonzero cells per gene (log10 scale)")
else:
n, bins, patches = ax.hist(colsum, bins="auto")
plt.xlabel("Molecules per gene (log10 scale)")
plt.ylabel("Frequency")
plt.tight_layout()
ax.tick_params(axis="x", labelsize=8)
return fig, ax
def cell_types(tsne, clusters, cluster_colors=None, n_cols=5):
"""
Plot cell clusters on the tSNE map.
Parameters
----------
tsne : DataFrame
tSNE map or UMAP
clusters
Results of the determine_cell_clusters function
"""
# Cluster colors
if cluster_colors is None:
set2_colors = matplotlib.colormaps["hsv"](np.linspace(0, 1, len(set(clusters))))
cluster_colors = pd.Series(
[matplotlib.colors.rgb2hex(rgba) for rgba in set2_colors],
index=set(clusters),
)
n_clusters = len(cluster_colors)
# Cell types
fig = FigureGrid(n_clusters, n_cols)
for ax, cluster in zip(fig, cluster_colors.index):
ax.scatter(tsne.loc[:, "x"], tsne.loc[:, "y"], s=3, color="lightgrey")
cells = clusters.index[clusters == cluster]
ax.scatter(
tsne.loc[cells, "x"],
tsne.loc[cells, "y"],
s=5,
color=cluster_colors[cluster],
)
ax.set_axis_off()
ax.set_title(cluster, fontsize=10)
return fig.figure, fig.axes
def highlight_cells_on_umap(
data: Union[sc.AnnData, pd.DataFrame],
cells: Union[List[str], Dict[str, str], pd.Series, pd.Index, np.ndarray, str],
annotation_offset: float = 0.03,
s: float = 1,
s_highlighted: float = 10,
fig: Optional[plt.Figure] = None,
ax: Optional[plt.Axes] = None,
embedding_basis: str = "X_umap",
) -> Tuple[plt.Figure, plt.Axes]:
"""
Highlights and annotates specific cells on a UMAP plot.
Parameters
----------
data : Union[sc.AnnData, pd.DataFrame]
Either a Scanpy AnnData object or a DataFrame of UMAP coordinates.
cells : Union[List[str], Dict[str, str], pd.Series, pd.Index, np.ndarray, str]
Cells to highlight on the UMAP. Can be provided as:
- a list, dict, or pd.Series: used as cell names (values in dict/Series used as annotations).
- a pd.Index: cell identifiers matching those in the data's index will be highlighted.
- a boolean array-like: used as a mask to select cells from the data's index.
- a string: used to retrieve a boolean mask from the AnnData's .obs attribute.
annotation_offset : float, optional
Offset for the annotations in proportion to the data range. Default is 0.03.
s : float, optional
Size of the points in the scatter plot. Default is 1.
s_highlighted : float, optional
Size of the points in the highlighted cells. Default is 10.
fig : Optional[plt.Figure], optional
Matplotlib Figure object. If None, a new figure is created. Default is None.
ax : Optional[plt.Axes], optional
Matplotlib Axes object. If None, a new Axes object is created. Default is None.
embedding_basis : str, optional
The key to retrieve UMAP results from the AnnData object. Default is 'X_umap'.
Returns
-------
fig : plt.Figure
A matplotlib Figure object containing the UMAP plot.
ax : plt.Axes
The corresponding Axes object.
Raises
------
KeyError
If 'embedding_basis' is not found in 'data.obsm'.
TypeError
If 'cells' is neither list, dict nor pd.Series.
"""
if isinstance(data, sc.AnnData):
if embedding_basis not in data.obsm:
raise KeyError(f"'{embedding_basis}' not found in .obsm.")
umap = pd.DataFrame(
data.obsm[embedding_basis], index=data.obs_names, columns=["x", "y"]
)
elif isinstance(data, pd.DataFrame):
umap = data.copy()
else:
raise TypeError("'data' should be either sc.AnnData or pd.DataFrame.")
if not isinstance(cells, (pd.Series, np.ndarray, pd.Index, list)):
if isinstance(cells, str):
if cells not in data.obs.columns:
raise KeyError(f"The column '{cells}' was not found in .obs.")
mask = data.obs[cells].astype(bool).values
cells = {cell: "" for cell in data.obs[mask].index}
elif not isinstance(cells, dict):
raise TypeError(
"'cells' should be either list, dict, pd.Series, pd.Index, string "
"(as column in .obs), or a boolean array-like."
)
elif isinstance(data, sc.AnnData) and len(cells) == data.n_obs:
try:
cells = data.obs_names[cells]
except IndexError:
raise ValueError(
"Using 'cells' as boolean index since len(cells) == ad.n_obs but failed."
)
cells = {cell: "" for cell in cells}
elif isinstance(cells, (list, np.ndarray, pd.Index)):
cells = {cell: "" for cell in cells}
elif isinstance(cells, pd.Series):
cells = dict(cells)
elif isinstance(cells, pd.Index):
cells = {cell: "" for cell in cells}
else:
raise TypeError(
"'cells' should be either list, dict, pd.Series, pd.Index, string "
"(as column in .obs), or a boolean array-like."
)
xpad, ypad = (umap.max() - umap.min()) * annotation_offset
fig, ax = get_fig(fig=fig, ax=ax)
ax.scatter(umap["x"], umap["y"], s=s, color=config.DESELECTED_COLOR)
for cell, annotation in cells.items():
if cell in umap.index:
x, y = umap.loc[cell, ["x", "y"]]
ax.scatter(x, y, c=config.SELECTED_COLOR, s=s_highlighted)
if annotation:
ax.annotate(annotation, (x, y), (x + xpad, y + ypad), "data")
ax.set_axis_off()
return fig, ax
def plot_tsne_by_cell_sizes(data, tsne, fig=None, ax=None, vmin=None, vmax=None):
"""Plot tSNE projections of the data with cells colored by molecule counts
:param data: Expression data, DataFrame-like
:param tsne: tSNE coordinates, DataFrame-like
:param fig: matplotlib Figure object, optional
:param ax: matplotlib Axis object, optional
:param vmin: Minimum molecule count for plotting, optional
:param vmax: Maximum molecule count for plotting, optional
"""
sizes = data.sum(axis=1)
fig, ax = get_fig(fig, ax)
scatter = ax.scatter(tsne["x"], tsne["y"], s=3, c=sizes, vmin=vmin, vmax=vmax)
ax.set_axis_off()
plt.colorbar(scatter, ax=ax)
return fig, ax
def plot_gene_expression(
data: pd.DataFrame,
tsne: pd.DataFrame,
genes: List[str],
plot_scale: bool = False,
n_cols: int = 5,
percentile: int = 0,
**kwargs,
) -> plt.Figure:
"""
Plot gene expression overlaid on tSNE maps.
Parameters
----------
data : pd.DataFrame
A DataFrame where each column represents a gene and each row a cell.
tsne : pd.DataFrame
A DataFrame containing tSNE coordinates for each cell.
genes : List[str]
List of gene symbols to plot on tSNE.
plot_scale : bool, optional
If True, include a color scale bar in the plot. Defaults to False.
n_cols : int, optional
Number of columns in the subplot grid. Defaults to 5.
percentile : int, optional
Percentile to cut off extreme values in gene expression for plotting.
Defaults to 0, meaning no cutoff.
kwargs : dict, optional
Additional keyword arguments to pass to the scatter plot function.
Returns
-------
matplotlib.pyplot.Figure
A matplotlib Figure object representing the plot of the gene expression.
Raises
------
ValueError
If none of the genes in the list are found in the data.
"""
not_in_dataframe = set(genes).difference(data.columns)
if not_in_dataframe:
if len(not_in_dataframe) < len(genes):
print(
"The following genes were either not observed in the experiment, "
"or the wrong gene symbol was used: {!r}".format(not_in_dataframe)
)
else:
raise ValueError(
"None of the listed genes were observed in the experiment, or the "
"wrong symbols were used."
)
# remove genes missing from experiment
genes = pd.Series(genes)[pd.Series(genes).isin(data.columns)]
# Plot
cells = data.index.intersection(tsne.index)
fig = FigureGrid(len(genes), n_cols)
for g, ax in zip(genes, fig):
# Data
c = data.loc[cells, g]
vmin = np.percentile(c[~np.isnan(c)], percentile)
vmax = np.percentile(c[~np.isnan(c)], 100 - percentile)
default_args = {
"vmin": vmin,
"vmax": vmax,
"s": 3,
}
default_args.update(kwargs)
ax.scatter(tsne["x"], tsne["y"], s=3, color="lightgrey")
ax.scatter(
tsne.loc[cells, "x"],
tsne.loc[cells, "y"],
c=c,
**default_args,
)
ax.set_axis_off()
ax.set_title(g)
if plot_scale:
normalize = matplotlib.colors.Normalize(vmin=vmin, vmax=vmax)
cax, _ = matplotlib.colorbar.make_axes(ax)
kaw = dict()
if "cmap" in kwargs.keys():
kaw["cmap"] = kwargs["cmap"]
matplotlib.colorbar.ColorbarBase(cax, norm=normalize, **kaw)
return fig.figure, fig.axes
def plot_diffusion_components(
data: Union[sc.AnnData, pd.DataFrame],
dm_res: Optional[Union[pd.DataFrame, str]] = "DM_EigenVectors",
embedding_basis: str = "X_umap",
**kwargs,
) -> Tuple[plt.Figure, plt.Axes]:
"""
Visualize diffusion components on tSNE or UMAP plots.
Parameters
----------
data : Union[sc.AnnData, pd.DataFrame]
An AnnData object from Scanpy or a DataFrame that contains tSNE or UMAP results.
dm_res : Optional[Union[pd.DataFrame, str]], optional
A DataFrame that contains the diffusion map results or a string key to access diffusion map
results from the obsm of the AnnData object. Default is 'DM_Eigenvectors'.
embedding_basis : str, optional
Key to access UMAP results from the obsm of the AnnData object. Defaults to 'X_umap'.
kwargs : dict, optional
Additional keyword arguments to pass to the scatter plot function.
Returns
-------
Tuple[matplotlib.pyplot.Figure, matplotlib.pyplot.Axes]
A tuple containing the matplotlib Figure and Axes objects representing the diffusion component plot.
Raises
------
KeyError
If `embedding_basis` or `dm_res` is not found in .obsm when `data` is an AnnData object.
"""
# Retrieve the embedding data
if isinstance(data, sc.AnnData):
if embedding_basis not in data.obsm:
raise KeyError(f"'{embedding_basis}' not found in .obsm.")
embedding_data = pd.DataFrame(data.obsm[embedding_basis], index=data.obs_names)
if isinstance(dm_res, str):
if dm_res not in data.obsm:
raise KeyError(f"'{dm_res}' not found in .obsm.")
dm_res = {
"EigenVectors": pd.DataFrame(data.obsm[dm_res], index=data.obs_names)
}
else:
embedding_data = data
default_args = {
"edgecolors": "none",
"s": 3,
}
default_args.update(kwargs)
fig = FigureGrid(dm_res["EigenVectors"].shape[1], 5)
for i, ax in enumerate(fig):
ax.scatter(
embedding_data.iloc[:, 0],
embedding_data.iloc[:, 1],
c=dm_res["EigenVectors"].loc[embedding_data.index, i],
**default_args,
)
ax.xaxis.set_major_locator(plt.NullLocator())
ax.yaxis.set_major_locator(plt.NullLocator())
ax.set_aspect("equal")
ax.set_title(f"Component {i}", fontsize=10)
ax.set_axis_off()
return fig.figure, fig.axes
def plot_palantir_results(
data: Union[sc.AnnData, pd.DataFrame],
pr_res: Optional[PResults] = None,
embedding_basis: str = "X_umap",
pseudo_time_key: str = "palantir_pseudotime",
entropy_key: str = "palantir_entropy",
fate_prob_key: str = "palantir_fate_probabilities",
**kwargs,
):
"""
Plot Palantir results on t-SNE or UMAP plots.
Parameters
----------
data : Union[sc.AnnData, pd.DataFrame]
Either a Scanpy AnnData object or a DataFrame of tSNE or UMAP results.
pr_res : Optional[PResults]
Optional PResults object containing Palantir results. If None, results are expected to be found in the provided AnnData object.
embedding_basis : str, optional
The key to retrieve UMAP results from the AnnData object. Defaults to 'X_umap'.
pseudo_time_key : str, optional
Key to access the pseudotime from obs of the AnnData object. Default is 'palantir_pseudotime'.
entropy_key : str, optional
Key to access the entropy from obs of the AnnData object. Default is 'palantir_entropy'.
fate_prob_key : str, optional
Key to access the fate probabilities from obsm of the AnnData object. Default is 'palantir_fate_probabilities'.
**kwargs
Additional keyword arguments passed to `ax.scatter`.
Returns
-------
matplotlib.pyplot.Figure
A matplotlib Figure object representing the plot of the Palantir results.
"""
if isinstance(data, sc.AnnData):
if embedding_basis not in data.obsm:
raise KeyError(f"'{embedding_basis}' not found in .obsm.")
embedding_data = pd.DataFrame(data.obsm[embedding_basis], index=data.obs_names)
if pr_res is None:
if (
pseudo_time_key not in data.obs
or entropy_key not in data.obs
or fate_prob_key not in data.obsm
):
raise KeyError("Required Palantir results not found in .obs or .obsm.")
obsm_pobs, _ = _validate_obsm_key(data, fate_prob_key)
obsm_pobs = data.obsm[fate_prob_key]
pr_res = PResults(
data.obs[pseudo_time_key],
data.obs[entropy_key],
obsm_pobs,
None,
)
else:
embedding_data = data
n_branches = pr_res.branch_probs.shape[1]
n_cols = 6
n_rows = int(np.ceil(n_branches / n_cols))
plt.figure(figsize=[2 * n_cols, 2 * (n_rows + 2)])
gs = plt.GridSpec(
n_rows + 2, n_cols, height_ratios=np.append([0.75, 0.75], np.repeat(1, n_rows))
)
def scatter_with_colorbar(ax, x, y, c, **kwargs):
sc = ax.scatter(x, y, c=c, **kwargs)
divider = make_axes_locatable(ax)
cax = divider.append_axes("right", size="5%", pad=0.05)
plt.colorbar(sc, cax=cax, orientation="vertical")
# Pseudotime
ax = plt.subplot(gs[0:2, 1:3])
scatter_with_colorbar(
ax,
embedding_data.iloc[:, 0],
embedding_data.iloc[:, 1],
pr_res.pseudotime[embedding_data.index],
**kwargs,
)
ax.set_axis_off()
ax.set_title("Pseudotime")
# Entropy
ax = plt.subplot(gs[0:2, 3:5])
scatter_with_colorbar(
ax,
embedding_data.iloc[:, 0],
embedding_data.iloc[:, 1],
pr_res.entropy[embedding_data.index],
**kwargs,
)
ax.set_axis_off()
ax.set_title("Entropy")
# Branch probabilities
for i, branch in enumerate(pr_res.branch_probs.columns):
ax = plt.subplot(gs[i // n_cols + 2, i % n_cols])
scatter_with_colorbar(
ax,
embedding_data.iloc[:, 0],
embedding_data.iloc[:, 1],
pr_res.branch_probs[branch][embedding_data.index],
**kwargs,
)
ax.set_axis_off()
ax.set_title(branch, fontsize=10)
plt.tight_layout()
return plt.gcf()
def plot_terminal_state_probs(
data: Union[sc.AnnData, pd.DataFrame],
cells: List[str],
pr_res: Optional[PResults] = None,
fate_prob_key: str = "palantir_fate_probabilities",
**kwargs,
):
"""Function to plot barplot for probabilities for each cell in the list
Parameters
----------
data : Union[sc.AnnData, pd.DataFrame]
Either a Scanpy AnnData object or a DataFrame of fate probabilities.
cells : List[str]
List of cell for which the barplots need to be plotted.
pr_res : Optional[PResults]
Optional PResults object containing Palantir results. If None, results are expected to be found in the provided AnnData object.
fate_prob_key : str, optional
Key to access the fate probabilities from obsm of the AnnData object. Default is 'palantir_fate_probabilities'.
kwargs : dict, optional
Additional keyword arguments to pass to the matplotlib.pyplot.bar function.
Returns
-------
matplotlib.pyplot.Figure
A matplotlib Figure object representing the plot of the cell fate probabilities.
"""
if isinstance(data, sc.AnnData):
if pr_res is None:
branch_probs, _ = _validate_obsm_key(data, fate_prob_key)
else:
if pr_res is None:
raise ValueError("pr_res must be provided when data is a DataFrame.")
branch_probs = pr_res.branch_probs
n_cols = 5
n_rows = int(np.ceil(len(cells) / n_cols))
if len(cells) < n_cols:
n_cols = len(cells)
fig = plt.figure(figsize=[3 * n_cols, 3 * n_rows])
# Branch colors
set1_colors = matplotlib.colormaps["Set1"](range(branch_probs.shape[1]))
cluster_colors = [matplotlib.colors.rgb2hex(rgba) for rgba in set1_colors]
branch_colors = pd.Series(
cluster_colors,
index=branch_probs.columns,
)
for i, cell in enumerate(cells):
ax = fig.add_subplot(n_rows, n_cols, i + 1)
# Probs
x = branch_probs.columns.values
height = branch_probs.loc[cell, :].values
# Plot
ax.bar(x, height, color=branch_colors, **kwargs)
ax.set_xlabel("")
ax.set_ylabel("")
ax.set_ylim([0, 1])
ax.set_yticks([0, 1])
ax.set_yticklabels([0, 1], fontsize=8)
ax.set_title(cell, fontsize=10)
return fig
def plot_branch_selection(
ad: sc.AnnData,
pseudo_time_key: str = "palantir_pseudotime",
fate_prob_key: str = "palantir_fate_probabilities",
masks_key: str = "branch_masks",
fates: Optional[Union[List[str], str]] = None,
embedding_basis: str = "X_umap",
figsize: Tuple[float, float] = (15, 5),
**kwargs,
):
"""
Plot cells along specific fates of pseudotime ordering and the UMAP embedding.
Parameters
----------
ad : sc.AnnData
Annotated data matrix. The pseudotime and fate probabilities should be stored under the keys provided.
pseudo_time_key : str, optional
Key to access the pseudotime from obs of the AnnData object. Default is 'palantir_pseudotime'.
fate_prob_key : str, optional
Key to access the fate probabilities from obsm of the AnnData object.
Default is 'palantir_fate_probabilities'.
masks_key : str, optional
Key to access the branch cell selection masks from obsm of the AnnData object.
Default is 'branch_masks'.
fates : Union[List[str], str]
The fates to be plotted. If not specified, all fates will be plotted.
embedding_basis : str, optional
Key to access the UMAP embedding from obsm of the AnnData object. Default is 'X_umap'.
figsize : Tuple[float, float], optional
Width and height of each subplot in inches. The total height of the figure is determined by
multiplying the height by the number of fates. Default is (15, 5).
**kwargs
Additional arguments passed to `matplotlib.pyplot.scatter`.
Returns
-------
matplotlib.pyplot.Figure
A matplotlib Figure object representing the plot of the branch selections.
"""
if pseudo_time_key not in ad.obs:
raise KeyError(f"{pseudo_time_key} not found in ad.obs")
fate_probs, fate_probs_names = _validate_obsm_key(ad, fate_prob_key)
fate_mask, fate_mask_names = _validate_obsm_key(ad, masks_key)
if embedding_basis not in ad.obsm:
raise KeyError(f"{embedding_basis} not found in ad.obsm")
fate_names = set(fate_probs_names).intersection(fate_mask_names)
if len(fate_names) == 0:
raise ValueError(
f"No agreeing fate names found for .obsm['{fate_prob_key}'] and .obsm['{masks_key}']."
)
n_fates = len(fate_names)
if n_fates < len(fate_probs_names) or n_fates < len(fate_probs_names):
warnings.warn(
f"Found only {n_fates} fates in the intersection of "
f"{len(fate_probs_names)} fate-probability fates in .obsm['{fate_prob_key}'] fates) "
f"and {len(fate_mask_names)} fate-mask fates in .obsm['{masks_key}']."
)
if isinstance(fates, str):
fates = [fates]
elif fates is None:
fates = fate_names
else:
for b in fates:
if b not in fate_names:
raise (
f"Specified fate name '{b}' is not in the available set of "
+ ", ".join(fate_names)
)
pt = ad.obs[pseudo_time_key]
umap = ad.obsm[embedding_basis]
figsize = figsize[0], figsize[1] * len(fates)
fig, axes = plt.subplots(len(fates), 2, figsize=figsize, width_ratios=[2, 1])
for i, fate in enumerate(fates):
if axes.ndim == 1:
ax1, ax2 = axes
else:
ax1 = axes[i, 0]
ax2 = axes[i, 1]
mask = fate_mask[fate].astype(bool)
# plot cells along pseudotime
ax1.scatter(
pt[~mask],
fate_probs.loc[~mask, fate],
c=config.DESELECTED_COLOR,
label="Other Cells",
**kwargs,
)
ax1.scatter(
pt[mask],
fate_probs.loc[mask, fate],
c=config.SELECTED_COLOR,
label="Selected Cells",
**kwargs,
)
ax1.set_title(f"Branch: {fate}")
ax1.set_xlabel("Pseudotime")
ax1.set_ylabel(f"{fate}-Fate Probability")
ax1.legend()
# plot UMAP
ax2.scatter(
umap[~mask, 0],
umap[~mask, 1],
c=config.DESELECTED_COLOR,
label="Other Cells",
**kwargs,
)
ax2.scatter(
umap[mask, 0],
umap[mask, 1],
c=config.SELECTED_COLOR,
label="Selected Cells",
**kwargs,
)
ax2.set_title(f"Branch: {fate}")
ax2.axis("off")
plt.tight_layout()
return fig
def plot_gene_trends_legacy(gene_trends, genes=None):
"""Plot the gene trends: each gene is plotted in a different panel
:param: gene_trends: Results of the compute_marker_trends function
"""
# Branches and genes
branches = list(gene_trends.keys())
set2_colors = matplotlib.colormaps["Set2"](range(len(branches)))
colors = pd.Series(
[matplotlib.colors.rgb2hex(rgba) for rgba in set2_colors],
index=branches,
)
if genes is None:
genes = gene_trends[branches[0]]["trends"].index
# Set up figure
fig = plt.figure(figsize=[7, 3 * len(genes)])
for i, gene in enumerate(genes):
ax = fig.add_subplot(len(genes), 1, i + 1)
for branch in branches:
trends = gene_trends[branch]["trends"]
def_stds = pd.DataFrame(0, index=trends.index, columns=trends.columns)
stds = gene_trends[branch].get("std", def_stds)
ax.plot(
trends.columns.astype(float),
trends.loc[gene, :],
color=colors[branch],
label=branch,
)
ax.set_xticks([0, 1])
ax.fill_between(
trends.columns.astype(float),
trends.loc[gene, :] - stds.loc[gene, :],
trends.loc[gene, :] + stds.loc[gene, :],
alpha=0.1,
color=colors[branch],
)
ax.set_title(gene)
# Add legend
if i == 0:
ax.legend()
return fig
def plot_gene_trends(
data: Union[Dict, sc.AnnData],
genes: Optional[List[str]] = None,
gene_trend_key: str = "gene_trends",
branch_names: Union[str, List] = "branch_masks",
) -> plt.Figure:
"""
Plot the gene trends for each gene across different panels.
Parameters
----------
data : Union[Dict, sc.AnnData]
An AnnData object or a dictionary that contains the gene trends.
genes : Optional[List[str]], optional
A list of genes to plot. If not provided, all genes will be plotted. Default is None.
gene_trend_key : str, optional
The key to access gene trends in the varm of the AnnData object. Default is 'gene_trends'.
branch_names : Union[str, List[str]], optional
Key to retrieve branch names from the AnnData object, or a list of branch names. If a string is provided,
it will be treated as a key in either AnnData.uns or AnnData.obsm. For AnnData.obsm, the column names will
be treated as branch names. If it cannot be found in AnnData.obsm and AnnData.uns then branch_names + "_columns"
will be looked up in AnnData.uns.
Default is 'branch_masks'.
Returns
-------
fig : matplotlib.figure.Figure
The matplotlib figure object containing the plot.
Raises
------
KeyError
If 'branch_names' as a string is not found in either .uns or .obsm, or if 'gene_trend_key + "_" + branch_name'
is not found in .varm.
ValueError
If 'data' is not an AnnData object and not a dictionary.
"""
gene_trends = _validate_gene_trend_input(data, gene_trend_key, branch_names)
# Branches and genes
branches = list(gene_trends.keys())
set2_colors = matplotlib.colormaps["Set2"](range(len(branches)))
colors = pd.Series(
[matplotlib.colors.rgb2hex(rgba) for rgba in set2_colors],
index=branches,
)
if genes is None:
genes = gene_trends[branches[0]]["trends"].index
# Set up figure
fig = plt.figure(figsize=[7, 3 * len(genes)])
for i, gene in enumerate(genes):
ax = fig.add_subplot(len(genes), 1, i + 1)
for branch in branches:
trends = gene_trends[branch]["trends"]
ax.plot(
trends.columns.astype(float),
trends.loc[gene, :],
color=colors[branch],
label=branch,
)
ax.set_xticks([0, 1])
ax.set_title(gene)
# Add legend
if i == 0:
ax.legend()
return fig
def _process_mask(ad: sc.AnnData, masks_key: str, branch_name: str):
"""
Processes the mask string to obtain mask indices.
Parameters
----------
ad : sc.AnnData
The annotated data matrix
masks_key : str
The mask string
Returns
-------
np.ndarray
Boolean array for masking
"""
if masks_key in ad.obs:
return ad.obs_vector(masks_key).astype(bool)
fate_mask, fate_mask_names = _validate_obsm_key(ad, masks_key)
try:
mask = fate_mask[branch_name]
except KeyError:
raise ValueError(
f"Fate '{branch_name}' not found in {branch_name} "
f"in ad.osbm or {branch_name}_columns in ad.uns"
)
return mask.astype(bool).values
def prepare_color_vector(
ad: sc.AnnData,
color: str,
mask: Optional[np.ndarray] = None,
layer: Optional[str] = None,
palette: Optional[Union[str, Sequence[str]]] = None,
na_color: str = "lightgray",
):
"""
Prepare the color vector for plotting.
Parameters
----------
ad : sc.AnnData
The annotated data matrix
color : str
The color parameter
mask : np.ndarray, optional
Boolean mask array
layer : str, optional
The data layer to use
palette : str or Sequence[str], optional
The color palette to use
na_color : str, optional
The color for NA values
Returns
-------
Tuple
Color vector and a flag indicating whether it's categorical
"""
color_source_vector = _get_color_source_vector(ad, color, layer=layer)
color_vector, categorical = _color_vector(
ad, color, values=color_source_vector, palette=palette, na_color=na_color
)
if mask is not None:
color_vector = color_vector[mask]
return color_source_vector, color_vector, categorical
def _add_categorical_legend(
ax,
color_source_vector,
palette: dict,
legend_anchor: Tuple[float, float],
legend_fontweight,
legend_fontsize,
legend_fontoutline,
na_color,
na_in_legend: bool,
):
"""Add a legend to the passed Axes."""
if na_in_legend and pd.isnull(color_source_vector).any():
if "NA" in color_source_vector:
raise NotImplementedError(
"No fallback for null labels has been defined if NA already in categories."
)
color_source_vector = color_source_vector.add_categories("NA").fillna("NA")
palette = palette.copy()
palette["NA"] = na_color
if color_source_vector.dtype == bool:
cats = pd.Categorical(color_source_vector.astype(str)).categories
else:
cats = color_source_vector.categories
for label in cats:
ax.scatter([], [], c=palette[label], label=label)
ax.legend(