-
Notifications
You must be signed in to change notification settings - Fork 741
Expand file tree
/
Copy path__init__.py
More file actions
1818 lines (1583 loc) · 50.9 KB
/
__init__.py
File metadata and controls
1818 lines (1583 loc) · 50.9 KB
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 __future__ import annotations
import functools
import operator
from collections.abc import Mapping, Sequence
from copy import copy
from typing import TYPE_CHECKING
import numpy as np
import pandas as pd
from matplotlib import colormaps, rcParams
from matplotlib import pyplot as plt
from scanpy.get import obs_df
from ... import logging as logg
from ..._compat import old_positionals
from ..._settings import settings
from ..._utils import _doc_params, _empty, sanitize_anndata, with_cat_dtype
from ...get import rank_genes_groups_df
from .._anndata import ranking
from .._docs import (
doc_cm_palette,
doc_panels,
doc_rank_genes_groups_plot_args,
doc_rank_genes_groups_values_to_plot,
doc_scatter_embedding,
doc_show_save,
doc_show_save_ax,
doc_vbound_percentile,
)
from .._utils import (
_deprecated_scale,
savefig_or_show,
timeseries,
timeseries_as_heatmap,
timeseries_subplot,
)
from .scatterplots import _panel_grid, embedding, pca
if TYPE_CHECKING:
from collections.abc import Iterable
from typing import Literal
from anndata import AnnData
from cycler import Cycler
from matplotlib.axes import Axes
from matplotlib.colors import Colormap, Normalize
from matplotlib.figure import Figure
from ..._utils import Empty
from .._baseplot_class import BasePlot
from .._utils import DensityNorm
# ------------------------------------------------------------------------------
# PCA
# ------------------------------------------------------------------------------
@_doc_params(scatter_bulk=doc_scatter_embedding, show_save_ax=doc_show_save_ax)
def pca_overview(adata: AnnData, **params):
"""Plot PCA results.
The parameters are the ones of the scatter plot. Call pca_ranking separately
if you want to change the default settings.
Parameters
----------
adata
Annotated data matrix.
color
Keys for observation/cell annotation either as list `["ann1", "ann2"]` or
string `"ann1,ann2,..."`.
use_raw
Use `raw` attribute of `adata` if present.
{scatter_bulk}
show
Show the plot, do not return axis.
save
If `True` or a `str`, save the figure.
A string is appended to the default filename.
Infer the filetype if ending on {{`'.pdf'`, `'.png'`, `'.svg'`}}.
Examples
--------
.. plot::
:context: close-figs
import scanpy as sc
adata = sc.datasets.pbmc3k_processed()
sc.pl.pca_overview(adata, color="louvain")
.. currentmodule:: scanpy
See Also
--------
pp.pca
"""
show = params.pop("show", None)
pca(adata, **params, show=False)
pca_loadings(adata, show=False)
pca_variance_ratio(adata, show=show)
# backwards compat
pca_scatter = pca
@old_positionals("include_lowest", "n_points", "show", "save")
def pca_loadings(
adata: AnnData,
components: str | Sequence[int] | None = None,
*,
include_lowest: bool = True,
n_points: int | None = None,
show: bool | None = None,
save: str | bool | None = None,
):
"""Rank genes according to contributions to PCs.
Parameters
----------
adata
Annotated data matrix.
components
For example, ``'1,2,3'`` means ``[1, 2, 3]``, first, second, third
principal component.
include_lowest
Whether to show the variables with both highest and lowest loadings.
show
Show the plot, do not return axis.
n_points
Number of variables to plot for each component.
save
If `True` or a `str`, save the figure.
A string is appended to the default filename.
Infer the filetype if ending on {`'.pdf'`, `'.png'`, `'.svg'`}.
Examples
--------
.. plot::
:context: close-figs
import scanpy as sc
adata = sc.datasets.pbmc3k_processed()
Show first 3 components loadings
.. plot::
:context: close-figs
sc.pl.pca_loadings(adata, components = '1,2,3')
"""
if components is None:
components = [1, 2, 3]
elif isinstance(components, str):
components = [int(x) for x in components.split(",")]
components = np.array(components) - 1
if np.any(components < 0):
msg = "Component indices must be greater than zero."
raise ValueError(msg)
if n_points is None:
n_points = min(30, adata.n_vars)
elif adata.n_vars < n_points:
msg = f"Tried to plot {n_points} variables, but passed anndata only has {adata.n_vars}."
raise ValueError(msg)
ranking(
adata,
"varm",
"PCs",
n_points=n_points,
indices=components,
include_lowest=include_lowest,
)
savefig_or_show("pca_loadings", show=show, save=save)
@old_positionals("log", "show", "save")
def pca_variance_ratio(
adata: AnnData,
n_pcs: int = 30,
*,
log: bool = False,
show: bool | None = None,
# deprecated
save: bool | str | None = None,
):
"""Plot the variance ratio.
Parameters
----------
n_pcs
Number of PCs to show.
log
Plot on logarithmic scale..
show
Show the plot, do not return axis.
save
If `True` or a `str`, save the figure.
A string is appended to the default filename.
Infer the filetype if ending on {`'.pdf'`, `'.png'`, `'.svg'`}.
"""
ranking(
adata,
"uns",
"variance_ratio",
n_points=n_pcs,
dictionary="pca",
labels="PC",
log=log,
)
savefig_or_show("pca_variance_ratio", show=show, save=save)
# ------------------------------------------------------------------------------
# Subgroup identification and ordering – clustering, pseudotime, branching
# and tree inference tools
# ------------------------------------------------------------------------------
@old_positionals("color_map", "show", "save", "as_heatmap", "marker")
def dpt_timeseries(
adata: AnnData,
*,
color_map: str | Colormap | None = None,
show: bool | None = None,
as_heatmap: bool = True,
marker: str | Sequence[str] = ".",
# deprecated
save: bool | None = None,
):
"""Heatmap of pseudotime series.
Parameters
----------
as_heatmap
Plot the timeseries as heatmap.
"""
if adata.n_vars > 100:
logg.warning(
"Plotting more than 100 genes might take some while, "
"consider selecting only highly variable genes, for example."
)
# only if number of genes is not too high
if as_heatmap:
# plot time series as heatmap, as in Haghverdi et al. (2016), Fig. 1d
timeseries_as_heatmap(
adata.X[adata.obs["dpt_order_indices"].values],
var_names=adata.var_names,
highlights_x=adata.uns["dpt_changepoints"],
color_map=color_map,
)
else:
# plot time series as gene expression vs time
timeseries(
adata.X[adata.obs["dpt_order_indices"].values],
var_names=adata.var_names,
highlights_x=adata.uns["dpt_changepoints"],
xlim=[0, 1.3 * adata.X.shape[0]],
marker=marker,
)
plt.xlabel("dpt order")
savefig_or_show("dpt_timeseries", save=save, show=show)
@old_positionals("color_map", "palette", "show", "save", "marker")
@_doc_params(cm_palette=doc_cm_palette, show_save=doc_show_save)
def dpt_groups_pseudotime(
adata: AnnData,
*,
color_map: str | Colormap | None = None,
palette: Sequence[str] | Cycler | None = None,
show: bool | None = None,
marker: str | Sequence[str] = ".",
return_fig: bool = False,
# deprecated
save: bool | str | None = None,
) -> Figure | None:
"""Plot groups and pseudotime.
Parameters
----------
adata
Annotated data matrix.
{cm_palette}
{show_save}
marker
Marker style. See :mod:`~matplotlib.markers` for details.
"""
fig, (ax_grp, ax_ord) = plt.subplots(2, 1)
timeseries_subplot(
adata.obs["dpt_groups"].cat.codes.to_numpy(),
time=adata.obs["dpt_order"].values,
color=np.asarray(adata.obs["dpt_groups"]),
highlights_x=adata.uns["dpt_changepoints"],
ylabel="dpt groups",
yticks=(
np.arange(len(adata.obs["dpt_groups"].cat.categories), dtype=int)
if len(adata.obs["dpt_groups"].cat.categories) < 5
else None
),
palette=palette,
ax=ax_grp,
marker=marker,
)
timeseries_subplot(
adata.obs["dpt_pseudotime"].values,
time=adata.obs["dpt_order"].values,
color=adata.obs["dpt_pseudotime"].values,
xlabel="dpt order",
highlights_x=adata.uns["dpt_changepoints"],
ylabel="pseudotime",
yticks=[0, 1],
color_map=color_map,
ax=ax_ord,
marker=marker,
)
savefig_or_show("dpt_groups_pseudotime", save=save, show=show)
if return_fig:
return fig
@old_positionals(
"n_genes",
"gene_symbols",
"key",
"fontsize",
"ncols",
"sharey",
"show",
"save",
"ax",
)
@_doc_params(show_save_ax=doc_show_save_ax)
def rank_genes_groups( # noqa: PLR0912, PLR0913, PLR0915
adata: AnnData,
groups: str | Sequence[str] | None = None,
*,
n_genes: int = 20,
gene_symbols: str | None = None,
key: str | None = "rank_genes_groups",
fontsize: int = 8,
ncols: int = 4,
sharey: bool = True,
show: bool | None = None,
ax: Axes | None = None,
save: bool | None = None, # deprecated
**kwds,
) -> list[Axes] | None:
"""Plot ranking of genes.
Parameters
----------
adata
Annotated data matrix.
groups
The groups for which to show the gene ranking.
gene_symbols
Key for field in `.var` that stores gene symbols if you do not want to
use `.var_names`.
n_genes
Number of genes to show.
fontsize
Fontsize for gene names.
ncols
Number of panels shown per row.
sharey
Controls if the y-axis of each panels should be shared. But passing
`sharey=False`, each panel has its own y-axis range.
{show_save_ax}
Returns
-------
List of each group’s matplotlib axis or `None` if `show=True`.
Examples
--------
.. plot::
:context: close-figs
import scanpy as sc
adata = sc.datasets.pbmc68k_reduced()
sc.pl.rank_genes_groups(adata)
Plot top 10 genes (default 20 genes)
.. plot::
:context: close-figs
sc.pl.rank_genes_groups(adata, n_genes=10)
.. currentmodule:: scanpy
See Also
--------
tl.rank_genes_groups
"""
n_panels_per_row = kwds.get("n_panels_per_row", ncols)
if n_genes < 1:
msg = (
"Specifying a negative number for n_genes has not been implemented for "
f"this plot. Received {n_genes=!r}."
)
raise NotImplementedError(msg)
reference = str(adata.uns[key]["params"]["reference"])
group_names = adata.uns[key]["names"].dtype.names if groups is None else groups
# one panel for each group
# set up the figure
n_panels_x = min(n_panels_per_row, len(group_names))
n_panels_y = np.ceil(len(group_names) / n_panels_x).astype(int)
from matplotlib import gridspec
if ax is None or (sps := ax.get_subplotspec()) is None:
fig = (
plt.figure(
figsize=(
n_panels_x * rcParams["figure.figsize"][0],
n_panels_y * rcParams["figure.figsize"][1],
)
)
if ax is None
else ax.get_figure()
)
gs = gridspec.GridSpec(n_panels_y, n_panels_x, fig, wspace=0.22, hspace=0.3)
else:
fig = ax.get_figure()
gs = sps.subgridspec(n_panels_y, n_panels_x)
if fig is None:
msg = "passed ax has no associated figure"
raise RuntimeError(msg)
axs: list[Axes] = []
ymin = np.inf
ymax = -np.inf
for count, group_name in enumerate(group_names):
gene_names = adata.uns[key]["names"][group_name][:n_genes]
scores = adata.uns[key]["scores"][group_name][:n_genes]
# Setting up axis, calculating y bounds
if sharey:
ymin = min(ymin, np.min(scores))
ymax = max(ymax, np.max(scores))
axs.append(fig.add_subplot(gs[count], sharey=axs[0] if axs else None))
else:
ymin = np.min(scores)
ymax = np.max(scores)
ymax += 0.3 * (ymax - ymin)
axs.append(fig.add_subplot(gs[count]))
axs[-1].set_ylim(ymin, ymax)
axs[-1].set_xlim(-0.9, n_genes - 0.1)
# Mapping to gene_symbols
if gene_symbols is not None:
if adata.raw is not None and adata.uns[key]["params"]["use_raw"]:
gene_names = adata.raw.var[gene_symbols][gene_names]
else:
gene_names = adata.var[gene_symbols][gene_names]
# Making labels
for ig, gene_name in enumerate(gene_names):
axs[-1].text(
ig,
scores[ig],
gene_name,
rotation="vertical",
verticalalignment="bottom",
horizontalalignment="center",
fontsize=fontsize,
)
axs[-1].set_title(f"{group_name} vs. {reference}")
if count >= n_panels_x * (n_panels_y - 1):
axs[-1].set_xlabel("ranking")
# print the 'score' label only on the first panel per row.
if count % n_panels_x == 0:
axs[-1].set_ylabel("score")
if sharey is True and axs:
ymax += 0.3 * (ymax - ymin)
axs[0].set_ylim(ymin, ymax)
writekey = f"rank_genes_groups_{adata.uns[key]['params']['groupby']}"
savefig_or_show(writekey, show=show, save=save)
show = settings.autoshow if show is None else show
if show:
return None
return axs
def _fig_show_save_or_axes(
plot_obj: BasePlot,
*,
return_fig: bool,
show: bool | None,
# deprecated
save: bool | None,
):
"""Decides what to return."""
if return_fig:
return plot_obj
plot_obj.make_figure()
savefig_or_show(plot_obj.DEFAULT_SAVE_PREFIX, show=show, save=save)
show = settings.autoshow if show is None else show
if show:
return None
return plot_obj.get_axes()
def _rank_genes_groups_plot( # noqa: PLR0912, PLR0913, PLR0915
adata: AnnData,
plot_type: str = "heatmap",
*,
groups: str | Sequence[str] | None = None,
n_genes: int | None = None,
groupby: str | None = None,
values_to_plot: str | None = None,
var_names: Sequence[str] | Mapping[str, Sequence[str]] | None = None,
min_logfoldchange: float | None = None,
key: str | None = None,
show: bool | None = None,
return_fig: bool = False,
gene_symbols: str | None = None,
save: bool | None = None, # deprecated
**kwds,
):
"""Call the different `rank_genes_groups_*` plots."""
if var_names is not None and n_genes is not None:
msg = (
"The arguments n_genes and var_names are mutually exclusive. Please "
"select only one."
)
raise ValueError(msg)
if key is None:
key = "rank_genes_groups"
if groupby is None:
groupby = str(adata.uns[key]["params"]["groupby"])
group_names = adata.uns[key]["names"].dtype.names if groups is None else groups
if var_names is not None:
if isinstance(var_names, Mapping):
# get a single list of all gene names in the dictionary
var_names_list = functools.reduce(
operator.iadd, [list(x) for x in var_names.values()], []
)
elif isinstance(var_names, str):
var_names_list = [var_names]
else:
var_names_list = var_names
else:
# set n_genes = 10 as default when none of the options is given
if n_genes is None:
n_genes = 10
# dict in which each group is the key and the n_genes are the values
var_names = {}
var_names_list = []
for group in group_names:
df = rank_genes_groups_df(
adata,
group,
key=key,
gene_symbols=gene_symbols,
log2fc_min=min_logfoldchange,
)
if gene_symbols is not None:
df["names"] = df[gene_symbols]
genes_list = df.names[df.names.notnull()].tolist()
if len(genes_list) == 0:
logg.warning(f"No genes found for group {group}")
continue
genes_list = genes_list[n_genes:] if n_genes < 0 else genes_list[:n_genes]
var_names[group] = genes_list
var_names_list.extend(genes_list)
# by default add dendrogram to plots
kwds.setdefault("dendrogram", True)
if plot_type in ["dotplot", "matrixplot"]:
# these two types of plots can also
# show score, logfoldchange and pvalues, in general any value from rank
# genes groups
title = None
values_df = None
if values_to_plot is not None:
values_df = _get_values_to_plot(
adata,
values_to_plot,
var_names_list,
key=key,
gene_symbols=gene_symbols,
)
title = values_to_plot
if values_to_plot == "logfoldchanges":
title = "log fold change"
else:
title = values_to_plot.replace("_", " ").replace("pvals", "p-value")
if plot_type == "dotplot":
from .._dotplot import dotplot
_pl = dotplot(
adata,
var_names,
groupby,
dot_color_df=values_df,
return_fig=True,
gene_symbols=gene_symbols,
**kwds,
)
if title is not None and "colorbar_title" not in kwds:
_pl.legend(colorbar_title=title)
elif plot_type == "matrixplot":
from .._matrixplot import matrixplot
_pl = matrixplot(
adata,
var_names,
groupby,
values_df=values_df,
return_fig=True,
gene_symbols=gene_symbols,
**kwds,
)
if title is not None and "colorbar_title" not in kwds:
_pl.legend(title=title)
return _fig_show_save_or_axes(_pl, return_fig=return_fig, show=show, save=save)
elif plot_type == "stacked_violin":
from .._stacked_violin import stacked_violin
_pl = stacked_violin(
adata,
var_names,
groupby,
return_fig=True,
gene_symbols=gene_symbols,
**kwds,
)
return _fig_show_save_or_axes(_pl, return_fig=return_fig, show=show, save=save)
elif plot_type == "heatmap":
from .._anndata import heatmap
return heatmap(
adata,
var_names,
groupby,
show=show,
save=save,
gene_symbols=gene_symbols,
**kwds,
)
elif plot_type == "tracksplot":
from .._anndata import tracksplot
return tracksplot(
adata,
var_names,
groupby,
show=show,
save=save,
gene_symbols=gene_symbols,
**kwds,
)
@old_positionals(
"n_genes",
"groupby",
"gene_symbols",
"var_names",
"min_logfoldchange",
"key",
"show",
"save",
)
@_doc_params(params=doc_rank_genes_groups_plot_args, show_save_ax=doc_show_save_ax)
def rank_genes_groups_heatmap(
adata: AnnData,
groups: str | Sequence[str] | None = None,
*,
n_genes: int | None = None,
groupby: str | None = None,
gene_symbols: str | None = None,
var_names: Sequence[str] | Mapping[str, Sequence[str]] | None = None,
min_logfoldchange: float | None = None,
key: str | None = None,
show: bool | None = None,
save: bool | None = None, # deprecated
**kwds,
):
"""Plot ranking of genes using heatmap plot (see :func:`~scanpy.pl.heatmap`).
Parameters
----------
{params}
{show_save_ax}
**kwds
Are passed to :func:`~scanpy.pl.heatmap`.
Examples
--------
.. plot::
:context: close-figs
import scanpy as sc
adata = sc.datasets.pbmc68k_reduced()
sc.tl.rank_genes_groups(adata, 'bulk_labels')
sc.pl.rank_genes_groups_heatmap(adata)
Show gene names per group on the heatmap
.. plot::
:context: close-figs
sc.pl.rank_genes_groups_heatmap(adata, show_gene_labels=True)
Plot top 5 genes per group (default 10 genes)
.. plot::
:context: close-figs
sc.pl.rank_genes_groups_heatmap(adata, n_genes=5, show_gene_labels=True)
.. currentmodule:: scanpy
See Also
--------
tl.rank_genes_groups
tl.dendrogram
"""
return _rank_genes_groups_plot(
adata,
plot_type="heatmap",
groups=groups,
n_genes=n_genes,
gene_symbols=gene_symbols,
groupby=groupby,
var_names=var_names,
key=key,
min_logfoldchange=min_logfoldchange,
show=show,
save=save,
**kwds,
)
@old_positionals(
"n_genes",
"groupby",
"var_names",
"gene_symbols",
"min_logfoldchange",
"key",
"show",
"save",
)
@_doc_params(params=doc_rank_genes_groups_plot_args, show_save_ax=doc_show_save_ax)
def rank_genes_groups_tracksplot(
adata: AnnData,
groups: str | Sequence[str] | None = None,
*,
n_genes: int | None = None,
groupby: str | None = None,
var_names: Sequence[str] | Mapping[str, Sequence[str]] | None = None,
gene_symbols: str | None = None,
min_logfoldchange: float | None = None,
key: str | None = None,
show: bool | None = None,
save: bool | None = None, # deprecated
**kwds,
):
"""Plot ranking of genes using heatmap plot (see :func:`~scanpy.pl.heatmap`).
Parameters
----------
{params}
{show_save_ax}
**kwds
Are passed to :func:`~scanpy.pl.tracksplot`.
Examples
--------
.. plot::
:context: close-figs
import scanpy as sc
adata = sc.datasets.pbmc68k_reduced()
sc.tl.rank_genes_groups(adata, 'bulk_labels')
sc.pl.rank_genes_groups_tracksplot(adata)
"""
return _rank_genes_groups_plot(
adata,
plot_type="tracksplot",
groups=groups,
n_genes=n_genes,
var_names=var_names,
gene_symbols=gene_symbols,
groupby=groupby,
key=key,
min_logfoldchange=min_logfoldchange,
show=show,
save=save,
**kwds,
)
@old_positionals(
"n_genes",
"groupby",
"values_to_plot",
"var_names",
"gene_symbols",
"min_logfoldchange",
"key",
"show",
"save",
"return_fig",
)
@_doc_params(
params=doc_rank_genes_groups_plot_args,
vals_to_plot=doc_rank_genes_groups_values_to_plot,
show_save_ax=doc_show_save_ax,
)
def rank_genes_groups_dotplot( # noqa: PLR0913
adata: AnnData,
groups: str | Sequence[str] | None = None,
*,
n_genes: int | None = None,
groupby: str | None = None,
values_to_plot: Literal[
"scores",
"logfoldchanges",
"pvals",
"pvals_adj",
"log10_pvals",
"log10_pvals_adj",
]
| None = None,
var_names: Sequence[str] | Mapping[str, Sequence[str]] | None = None,
gene_symbols: str | None = None,
min_logfoldchange: float | None = None,
key: str | None = None,
show: bool | None = None,
return_fig: bool = False,
save: bool | None = None, # deprecated
**kwds,
):
"""Plot ranking of genes using dotplot plot (see :func:`~scanpy.pl.dotplot`).
Parameters
----------
{params}
{vals_to_plot}
{show_save_ax}
return_fig
Returns :class:`DotPlot` object. Useful for fine-tuning
the plot. Takes precedence over `show=False`.
**kwds
Are passed to :func:`~scanpy.pl.dotplot`.
Returns
-------
If `return_fig` is `True`, returns a :class:`DotPlot` object,
else if `show` is false, return axes dict
Examples
--------
.. plot::
:context: close-figs
import scanpy as sc
adata = sc.datasets.pbmc68k_reduced()
sc.tl.rank_genes_groups(adata, 'bulk_labels', n_genes=adata.raw.shape[1])
Plot top 2 genes per group.
.. plot::
:context: close-figs
sc.pl.rank_genes_groups_dotplot(adata,n_genes=2)
Plot with scaled expressions for easier identification of differences.
.. plot::
:context: close-figs
sc.pl.rank_genes_groups_dotplot(adata, n_genes=2, standard_scale='var')
Plot `logfoldchanges` instead of gene expression. In this case a diverging colormap
like `bwr` or `seismic` works better. To center the colormap in zero, the minimum
and maximum values to plot are set to -4 and 4 respectively.
Also, only genes with a log fold change of 3 or more are shown.
.. plot::
:context: close-figs
sc.pl.rank_genes_groups_dotplot(
adata,
n_genes=4,
values_to_plot="logfoldchanges", cmap='bwr',
vmin=-4,
vmax=4,
min_logfoldchange=3,
colorbar_title='log fold change'
)
Also, the last genes can be plotted. This can be useful to identify genes
that are lowly expressed in a group. For this `n_genes=-4` is used
.. plot::
:context: close-figs
sc.pl.rank_genes_groups_dotplot(
adata,
n_genes=-4,
values_to_plot="logfoldchanges",
cmap='bwr',
vmin=-4,
vmax=4,
min_logfoldchange=3,
colorbar_title='log fold change',
)
A list specific genes can be given to check their log fold change. If a
dictionary, the dictionary keys will be added as labels in the plot.
.. plot::
:context: close-figs
var_names = {{'T-cell': ['CD3D', 'CD3E', 'IL32'],
'B-cell': ['CD79A', 'CD79B', 'MS4A1'],
'myeloid': ['CST3', 'LYZ'] }}
sc.pl.rank_genes_groups_dotplot(
adata,
var_names=var_names,
values_to_plot="logfoldchanges",
cmap='bwr',
vmin=-4,
vmax=4,
min_logfoldchange=3,
colorbar_title='log fold change',
)
.. currentmodule:: scanpy
See Also
--------
tl.rank_genes_groups
"""
return _rank_genes_groups_plot(
adata,
plot_type="dotplot",
groups=groups,
n_genes=n_genes,
groupby=groupby,
values_to_plot=values_to_plot,
var_names=var_names,
gene_symbols=gene_symbols,
key=key,
min_logfoldchange=min_logfoldchange,
show=show,
save=save,
return_fig=return_fig,
**kwds,
)
@old_positionals("n_genes", "groupby", "gene_symbols")