-
Notifications
You must be signed in to change notification settings - Fork 742
Expand file tree
/
Copy pathscatterplots.py
More file actions
1422 lines (1224 loc) · 45.8 KB
/
scatterplots.py
File metadata and controls
1422 lines (1224 loc) · 45.8 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 inspect
import re
import textwrap
from collections.abc import Sequence
from copy import copy
from functools import cache, partial
from itertools import combinations, product
from numbers import Integral
from typing import TYPE_CHECKING
import numpy as np
import pandas as pd
from matplotlib import colormaps, colors, patheffects, rcParams
from matplotlib import pyplot as plt
from matplotlib.colors import Normalize
from matplotlib.markers import MarkerStyle
from ... import logging as logg
from ..._compat import deprecated
from ..._settings import settings
from ..._utils import _doc_params, _empty, sanitize_anndata
from ..._utils._doctests import doctest_internet
from ...get import _check_mask
from .. import _utils
from .._docs import (
doc_adata_color_etc,
doc_edges_arrows,
doc_scatter_embedding,
doc_scatter_spatial,
doc_show_save_ax,
)
from .._utils import _obs_vector_compat, check_colornorm, check_projection, circles
if TYPE_CHECKING:
from collections.abc import Callable, Collection, Mapping
from types import FunctionType
from typing import Any, Literal
from anndata import AnnData
from cycler import Cycler
from matplotlib.axes import Axes
from matplotlib.colors import Colormap
from matplotlib.figure import Figure
from numpy.typing import NDArray
from ..._utils import Empty
from ...tools._draw_graph import _Layout
from .._utils import ColorLike, VBound, _FontSize, _FontWeight, _LegendLoc
@_doc_params(
adata_color_etc=doc_adata_color_etc,
edges_arrows=doc_edges_arrows,
scatter_bulk=doc_scatter_embedding,
show_save_ax=doc_show_save_ax,
)
def embedding( # noqa: PLR0912, PLR0913, PLR0915
adata: AnnData,
basis: str,
*,
color: str | Sequence[str] | None = None,
mask_obs: NDArray[np.bool] | str | None = None,
gene_symbols: str | None = None,
use_raw: bool | None = None,
sort_order: bool = True,
edges: bool = False,
edges_width: float = 0.1,
edges_color: str | Sequence[float] | Sequence[str] = "grey",
neighbors_key: str | None = None,
arrows: bool = False,
arrows_kwds: Mapping[str, Any] | None = None,
groups: str | Sequence[str] | None = None,
components: str | Sequence[str] | None = None,
dimensions: tuple[int, int] | Sequence[tuple[int, int]] | None = None,
layer: str | None = None,
projection: Literal["2d", "3d"] = "2d",
scale_factor: float | None = None,
color_map: Colormap | str | None = None,
cmap: Colormap | str | None = None,
palette: str | Sequence[str] | Cycler | None = None,
na_color: ColorLike = "lightgray",
na_in_legend: bool = True,
size: float | Sequence[float] | None = None,
frameon: bool | None = None,
legend_fontsize: float | _FontSize | None = None,
legend_fontweight: int | _FontWeight = "bold",
legend_loc: _LegendLoc | None = "right margin",
legend_fontoutline: int | None = None,
colorbar_loc: Literal["right", "left", "top", "bottom"] | None = "right",
vmax: VBound | Sequence[VBound] | None = None,
vmin: VBound | Sequence[VBound] | None = None,
vcenter: VBound | Sequence[VBound] | None = None,
norm: Normalize | Sequence[Normalize] | None = None,
add_outline: bool | None = False,
outline_width: tuple[float, float] = (0.3, 0.05),
outline_color: tuple[str, str] = ("black", "white"),
ncols: int = 4,
hspace: float = 0.25,
wspace: float | None = None,
title: str | Sequence[str] | None = None,
show: bool | None = None,
ax: Axes | None = None,
return_fig: bool | None = None,
marker: str | Sequence[str] = ".",
save: bool | str | None = None, # deprecated
**kwargs,
) -> Figure | Axes | list[Axes] | None:
"""Scatter plot for user specified embedding basis (e.g. umap, pca, etc).
Parameters
----------
basis
Name of the `obsm` basis to use.
{adata_color_etc}
{edges_arrows}
{scatter_bulk}
{show_save_ax}
Returns
-------
If `show==False` a :class:`~matplotlib.axes.Axes` or a list of it.
"""
#####################
# Argument handling #
#####################
check_projection(projection)
sanitize_anndata(adata)
basis_values = _get_basis(adata, basis)
dimensions = _components_to_dimensions(
components, dimensions, projection=projection, total_dims=basis_values.shape[1]
)
args_3d = dict(projection="3d") if projection == "3d" else {}
# Checking the mask format and if used together with groups
if groups is not None and mask_obs is not None:
msg = "Groups and mask arguments are incompatible."
raise ValueError(msg)
mask_obs = _check_mask(adata, mask_obs, "obs")
# Figure out if we're using raw
if use_raw is None:
# check if adata.raw is set
use_raw = layer is None and adata.raw is not None
if use_raw and layer is not None:
msg = (
"Cannot use both a layer and the raw representation. "
f"Was passed: {use_raw=!r}, {layer=!r}."
)
raise ValueError(msg)
if use_raw and adata.raw is None:
msg = (
"`use_raw` is set to True but AnnData object does not have raw. "
"Please check."
)
raise ValueError(msg)
if isinstance(groups, str):
groups = [groups]
# Color map
if color_map is not None:
if cmap is not None:
msg = "Cannot specify both `color_map` and `cmap`."
raise ValueError(msg)
else:
cmap = color_map
cmap = copy(colormaps.get_cmap(cmap))
cmap.set_bad(na_color)
# Prevents warnings during legend creation
na_color = colors.to_hex(na_color, keep_alpha=True)
# by default turn off edge color. Otherwise, for
# very small sizes the edge will not reduce its size
# (https://github.com/scverse/scanpy/issues/293)
kwargs.setdefault("edgecolor", "none")
# Vectorized arguments
# turn color into a python list
color = [color] if isinstance(color, str) or color is None else list(color)
# turn marker into a python list
marker = [marker] if isinstance(marker, str) else list(marker)
if title is not None:
# turn title into a python list if not None
title = [title] if isinstance(title, str) else list(title)
# turn vmax and vmin into a sequence
if isinstance(vmax, str) or not isinstance(vmax, Sequence):
vmax = [vmax]
if isinstance(vmin, str) or not isinstance(vmin, Sequence):
vmin = [vmin]
if isinstance(vcenter, str) or not isinstance(vcenter, Sequence):
vcenter = [vcenter]
if isinstance(norm, Normalize) or not isinstance(norm, Sequence):
norm = [norm]
# Size
if "s" in kwargs and size is None:
size = kwargs.pop("s")
if size is not None:
# check if size is any type of sequence, and if so
# set as ndarray
if (
size is not None
and isinstance(size, Sequence | pd.Series | np.ndarray)
and len(size) == adata.shape[0]
):
size = np.array(size, dtype=float)
else:
# if the basis has NaNs, ignore the corresponding cells for size calcluation
size = 120000 / (~np.isnan(basis_values).any(axis=1)).sum()
##########
# Layout #
##########
# Most of the code is for the case when multiple plots are required
if wspace is None:
# try to set a wspace that is not too large or too small given the
# current figure size
wspace = 0.75 / rcParams["figure.figsize"][0] + 0.02
if components is not None:
color, dimensions = list(zip(*product(color, dimensions), strict=True))
color, dimensions, marker = _broadcast_args(color, dimensions, marker)
# 'color' is a list of names that want to be plotted.
# Eg. ['Gene1', 'louvain', 'Gene2'].
# component_list is a list of components [[0,1], [1,2]]
if (
not isinstance(color, str) and isinstance(color, Sequence) and len(color) > 1
) or len(dimensions) > 1:
if ax is not None:
msg = (
"Cannot specify `ax` when plotting multiple panels "
"(each for a given value of 'color')."
)
raise ValueError(msg)
# each plot needs to be its own panel
fig, grid = _panel_grid(hspace, wspace, ncols, len(color))
else:
grid = None
if ax is None:
fig = plt.figure()
ax = fig.add_subplot(111, **args_3d)
############
# Plotting #
############
axs = []
# use itertools.product to make a plot for each color and for each component
# For example if color=[gene1, gene2] and components=['1,2, '2,3'].
# The plots are: [
# color=gene1, components=[1,2], color=gene1, components=[2,3],
# color=gene2, components = [1, 2], color=gene2, components=[2,3],
# ]
for count, (value_to_plot, dims) in enumerate(zip(color, dimensions, strict=True)):
kwargs_scatter = kwargs.copy() # is potentially mutated for each plot
# TODO: It might be worth not returning `NumpyExtensionArray` objects out of the dataframes via accessors because we have a lot of np.ndarray checks.
# Setting np.array here prevents the `NumpyExtensionArray` from propagating.
color_source_vector = _get_color_source_vector(
adata,
value_to_plot,
layer=layer,
mask_obs=mask_obs,
use_raw=use_raw,
gene_symbols=gene_symbols,
groups=groups,
)
if isinstance(color_source_vector, pd.arrays.NumpyExtensionArray):
color_source_vector = color_source_vector.to_numpy()
color_vector, color_type = _color_vector(
adata,
value_to_plot,
values=color_source_vector,
palette=palette,
na_color=na_color,
)
# Order points
order = slice(None)
if sort_order and value_to_plot is not None and color_type == "cont":
# Higher values plotted on top, null values on bottom
order = np.argsort(-color_vector, kind="stable")[::-1]
elif sort_order and color_type == "cat":
# Null points go on bottom
order = np.argsort(~pd.isnull(color_source_vector), kind="stable")
# Set orders
if isinstance(size, np.ndarray):
size = np.array(size)[order]
color_source_vector = color_source_vector[order]
color_vector = color_vector[order]
coords = basis_values[:, dims][order, :]
# if plotting multiple panels, get the ax from the grid spec
# else use the ax value (either user given or created previously)
if grid:
ax = plt.subplot(grid[count], **args_3d)
axs.append(ax)
if not (settings._frameon if frameon is None else frameon):
ax.axis("off")
if title is None:
if value_to_plot is not None:
ax.set_title(value_to_plot)
else:
ax.set_title("")
else:
try:
ax.set_title(title[count])
except IndexError:
logg.warning(
"The title list is shorter than the number of panels. "
"Using 'color' value instead for some plots."
)
ax.set_title(value_to_plot)
if color_type == "cont":
vmin_float, vmax_float, vcenter_float, norm_obj = _get_vboundnorm(
vmin, vmax, vcenter, norm=norm, index=count, colors=color_vector
)
kwargs_scatter["norm"] = check_colornorm(
vmin_float,
vmax_float,
vcenter_float,
norm_obj,
)
kwargs_scatter["cmap"] = cmap
# make the scatter plot
if projection == "3d":
cax = ax.scatter(
coords[:, 0],
coords[:, 1],
coords[:, 2],
c=color_vector,
rasterized=settings._vector_friendly,
marker=marker[count],
**kwargs_scatter,
)
else:
scatter = (
partial(ax.scatter, s=size, plotnonfinite=True)
if scale_factor is None
else partial(
circles, s=size, ax=ax, scale_factor=scale_factor
) # size in circles is radius
)
if add_outline:
# the default outline is a black edge followed by a
# thin white edged added around connected clusters.
# To add an outline
# three overlapping scatter plots are drawn:
# First black dots with slightly larger size,
# then, white dots a bit smaller, but still larger
# than the final dots. Then the final dots are drawn
# with some transparency.
bg_width, gap_width = outline_width
point = np.sqrt(size)
gap_size = (point + (point * gap_width) * 2) ** 2
bg_size = (np.sqrt(gap_size) + (point * bg_width) * 2) ** 2
# the default black and white colors can be changes using
# the contour_config parameter
bg_color, gap_color = outline_color
# remove edge from kwargs if present
# because edge needs to be set to None
kwargs_scatter["edgecolor"] = "none"
# For points, if user did not set alpha, set alpha to 0.7
kwargs_scatter.setdefault("alpha", 0.7)
# remove alpha and color mapping for outline
kwargs_outline = {
k: v
for k, v in kwargs.items()
if k not in {"alpha", "cmap", "norm"}
}
for s, c in [(bg_size, bg_color), (gap_size, gap_color)]:
ax.scatter(
coords[:, 0],
coords[:, 1],
s=s,
c=c,
rasterized=settings._vector_friendly,
marker=marker[count],
**kwargs_outline,
)
edgecolor = kwargs_scatter.pop("edgecolor", None)
if not MarkerStyle(marker[count]).is_filled():
edgecolor = None
cax = scatter(
coords[:, 0],
coords[:, 1],
c=color_vector,
rasterized=settings._vector_friendly,
marker=marker[count],
edgecolor=edgecolor,
**kwargs_scatter,
)
# remove y and x ticks
ax.set_yticks([])
ax.set_xticks([])
if projection == "3d":
ax.set_zticks([])
# set default axis_labels
name = _basis2name(basis)
axis_labels = [name + str(d + 1) for d in dims]
ax.set_xlabel(axis_labels[0])
ax.set_ylabel(axis_labels[1])
if projection == "3d":
# shift the label closer to the axis
ax.set_zlabel(axis_labels[2], labelpad=-7)
ax.autoscale_view()
if edges:
_utils.plot_edges(
ax, adata, basis, edges_width, edges_color, neighbors_key=neighbors_key
)
if arrows:
_utils.plot_arrows(ax, adata, basis, arrows_kwds)
if value_to_plot is None:
# if only dots were plotted without an associated value
# there is not need to plot a legend or a colorbar
continue
if legend_fontoutline is not None:
path_effect = [
patheffects.withStroke(linewidth=legend_fontoutline, foreground="w")
]
else:
path_effect = None
# Adding legends
if color_type == "cat":
_add_categorical_legend(
ax,
color_source_vector,
palette=_get_palette(adata, value_to_plot),
scatter_array=coords,
legend_loc=legend_loc,
legend_fontweight=legend_fontweight,
legend_fontsize=legend_fontsize,
legend_fontoutline=path_effect,
na_color=na_color,
na_in_legend=na_in_legend,
multi_panel=bool(grid),
)
elif colorbar_loc is not None:
plt.colorbar(
cax, ax=ax, pad=0.01, fraction=0.08, aspect=30, location=colorbar_loc
)
if return_fig is True:
return fig
axs = axs if grid else ax
_utils.savefig_or_show(basis, show=show, save=save)
show = settings.autoshow if show is None else show
if show:
return None
return axs
def _panel_grid(hspace, wspace, ncols, num_panels):
from matplotlib import gridspec
n_panels_x = min(ncols, num_panels)
n_panels_y = np.ceil(num_panels / n_panels_x).astype(int)
# each panel will have the size of rcParams['figure.figsize']
fig = plt.figure(
figsize=(
n_panels_x * rcParams["figure.figsize"][0] * (1 + wspace),
n_panels_y * rcParams["figure.figsize"][1],
),
)
left = 0.2 / n_panels_x
bottom = 0.13 / n_panels_y
gs = gridspec.GridSpec(
nrows=n_panels_y,
ncols=n_panels_x,
left=left,
right=1 - (n_panels_x - 1) * left - 0.01 / n_panels_x,
bottom=bottom,
top=1 - (n_panels_y - 1) * bottom - 0.1 / n_panels_y,
hspace=hspace,
wspace=wspace,
)
return fig, gs
def _get_vboundnorm(
vmin: Sequence[VBound],
vmax: Sequence[VBound],
vcenter: Sequence[VBound],
*,
norm: Sequence[Normalize],
index: int,
colors: Sequence[float],
) -> tuple[float | None, float | None]:
"""Evaluate the value of `vmin`, `vmax` and `vcenter`.
Each could be a str in which case is interpreted as a percentile and should
be specified in the form `pN` where `N` is the percentile.
Eg. for a percentile of 85 the format would be `p85`.
Floats are accepted as `p99.9`.
Alternatively, `vmin`/`vmax` could be a function that is applied to
the list of color values (`colors`). E.g.
>>> def my_vmax(colors):
... return np.percentile(colors, p=80)
Parameters
----------
index
This index of the plot
colors
Values for the plot
Returns
-------
(vmin, vmax, vcenter, norm) containing None or float values for
vmin, vmax, vcenter and matplotlib.colors.Normalize or None for norm.
"""
out = []
for v_name, v in [("vmin", vmin), ("vmax", vmax), ("vcenter", vcenter)]:
if len(v) == 1:
# this case usually happens when the user sets eg vmax=0.9, which
# is internally converted into list of len=1, but is expected that this
# value applies to all plots.
v_value = v[0]
else:
try:
v_value = v[index]
except IndexError:
logg.error(
f"The parameter {v_name} is not valid. If setting multiple {v_name} values,"
f"check that the length of the {v_name} list is equal to the number "
"of plots. "
)
v_value = None
if v_value is not None:
if isinstance(v_value, str) and v_value.startswith("p"):
try:
float(v_value[1:])
except ValueError:
logg.error(
f"The parameter {v_name}={v_value} for plot number {index + 1} is not valid. "
f"Please check the correct format for percentiles."
)
# interpret value of vmin/vmax as quantile with the following syntax 'p99.9'
v_value = np.nanpercentile(colors, q=float(v_value[1:]))
elif callable(v_value):
# interpret vmin/vmax as function
v_value = v_value(colors)
if not isinstance(v_value, float):
logg.error(
f"The return of the function given for {v_name} is not valid. "
"Please check that the function returns a number."
)
v_value = None
else:
try:
float(v_value)
except ValueError:
logg.error(
f"The given {v_name}={v_value} for plot number {index + 1} is not valid. "
f"Please check that the value given is a valid number, a string "
f"starting with 'p' for percentiles or a valid function."
)
v_value = None
out.append(v_value)
out.append(norm[0] if len(norm) == 1 else norm[index])
return tuple(out)
_TYPE_GUARD_IMPORT_RE = re.compile(r"\nif TYPE_CHECKING:[^\n]*([\s\S]*?)(?=\n\S)")
@cache
def _get_guarded_imports(obj: FunctionType) -> Mapping[str, Any]:
"""Simplified version from `sphinx-autodoc-typehints`."""
module = inspect.getmodule(obj)
assert module
code = inspect.getsource(module)
rv: dict[str, Any] = {}
for m in _TYPE_GUARD_IMPORT_RE.finditer(code):
guarded_code = textwrap.dedent(m.group(1))
rv.update(obj.__globals__)
exec(guarded_code, rv)
for k in obj.__globals__:
del rv[k]
return rv
def _wraps_plot_scatter[**P, R](wrapper: Callable[P, R]) -> Callable[P, R]:
"""Update the wrapper function to use the correct signature."""
params = inspect.signature(embedding).parameters.copy()
wrapper_sig = inspect.signature(wrapper)
wrapper_params = wrapper_sig.parameters.copy()
params.pop("basis")
params.pop("kwargs")
wrapper_params.pop("adata")
params.update(wrapper_params)
annotations = {
k: v.annotation
for k, v in params.items()
if v.annotation != inspect.Parameter.empty
}
if wrapper_sig.return_annotation is not inspect.Signature.empty:
annotations["return"] = wrapper_sig.return_annotation
# `sphinx-autodoc-typehints` can execute `if TYPECHECKING` blocks,
# but all all users of `_wraps_plot_scatter` that aren’t in this module
# won’t have any imports. So we execute and inject the imports here.
wrapper.__globals__.update({
k: v
for k, v in {**embedding.__globals__, **_get_guarded_imports(embedding)}.items()
if k not in wrapper.__globals__
})
wrapper.__signature__ = inspect.Signature(
list(params.values()), return_annotation=wrapper_sig.return_annotation
)
wrapper.__annotations__ = annotations
return wrapper
# API
@_wraps_plot_scatter
@_doc_params(
adata_color_etc=doc_adata_color_etc,
edges_arrows=doc_edges_arrows,
scatter_bulk=doc_scatter_embedding,
show_save_ax=doc_show_save_ax,
)
def umap(adata: AnnData, **kwargs) -> Figure | Axes | list[Axes] | None:
"""Scatter plot in UMAP basis.
Parameters
----------
{adata_color_etc}
{edges_arrows}
{scatter_bulk}
{show_save_ax}
Returns
-------
If `show==False` a :class:`~matplotlib.axes.Axes` or a list of it.
Examples
--------
.. plot::
:context: close-figs
import scanpy as sc
adata = sc.datasets.pbmc68k_reduced()
sc.pl.umap(adata)
Colour points by discrete variable (Louvain clusters).
.. plot::
:context: close-figs
sc.pl.umap(adata, color="louvain")
Colour points by gene expression.
.. plot::
:context: close-figs
sc.pl.umap(adata, color="HES4")
Plot muliple umaps for different gene expressions.
.. plot::
:context: close-figs
sc.pl.umap(adata, color=["HES4", "TNFRSF4"])
.. currentmodule:: scanpy
See Also
--------
tl.umap
"""
return embedding(adata, "umap", **kwargs)
@_wraps_plot_scatter
@_doc_params(
adata_color_etc=doc_adata_color_etc,
edges_arrows=doc_edges_arrows,
scatter_bulk=doc_scatter_embedding,
show_save_ax=doc_show_save_ax,
)
def tsne(adata: AnnData, **kwargs) -> Figure | Axes | list[Axes] | None:
"""Scatter plot in tSNE basis.
Parameters
----------
{adata_color_etc}
{edges_arrows}
{scatter_bulk}
{show_save_ax}
Returns
-------
If `show==False` a :class:`~matplotlib.axes.Axes` or a list of it.
Examples
--------
.. plot::
:context: close-figs
import scanpy as sc
adata = sc.datasets.pbmc68k_reduced()
sc.tl.tsne(adata)
sc.pl.tsne(adata, color='bulk_labels')
.. currentmodule:: scanpy
See Also
--------
tl.tsne
"""
return embedding(adata, "tsne", **kwargs)
@_wraps_plot_scatter
@_doc_params(
adata_color_etc=doc_adata_color_etc,
scatter_bulk=doc_scatter_embedding,
show_save_ax=doc_show_save_ax,
)
def diffmap(adata: AnnData, **kwargs) -> Figure | Axes | list[Axes] | None:
"""Scatter plot in Diffusion Map basis.
Parameters
----------
{adata_color_etc}
{scatter_bulk}
{show_save_ax}
Returns
-------
If `show==False` a :class:`~matplotlib.axes.Axes` or a list of it.
Examples
--------
.. plot::
:context: close-figs
import scanpy as sc
adata = sc.datasets.pbmc68k_reduced()
sc.tl.diffmap(adata)
sc.pl.diffmap(adata, color='bulk_labels')
.. currentmodule:: scanpy
See Also
--------
tl.diffmap
"""
return embedding(adata, "diffmap", **kwargs)
@_wraps_plot_scatter
@_doc_params(
adata_color_etc=doc_adata_color_etc,
edges_arrows=doc_edges_arrows,
scatter_bulk=doc_scatter_embedding,
show_save_ax=doc_show_save_ax,
)
def draw_graph(
adata: AnnData, *, layout: _Layout | None = None, **kwargs
) -> Figure | Axes | list[Axes] | None:
"""Scatter plot in graph-drawing basis.
Parameters
----------
{adata_color_etc}
layout
One of the :func:`~scanpy.tl.draw_graph` layouts.
By default, the last computed layout is used.
{edges_arrows}
{scatter_bulk}
{show_save_ax}
Returns
-------
If `show==False` a :class:`~matplotlib.axes.Axes` or a list of it.
Examples
--------
.. plot::
:context: close-figs
import scanpy as sc
adata = sc.datasets.pbmc68k_reduced()
sc.tl.draw_graph(adata)
sc.pl.draw_graph(adata, color=['phase', 'bulk_labels'])
.. currentmodule:: scanpy
See Also
--------
tl.draw_graph
"""
if layout is None:
layout = str(adata.uns["draw_graph"]["params"]["layout"])
basis = f"draw_graph_{layout}"
if f"X_{basis}" not in adata.obsm:
msg = f"Did not find {basis} in adata.obs. Did you compute layout {layout}?"
raise ValueError(msg)
return embedding(adata, basis, **kwargs)
@_wraps_plot_scatter
@_doc_params(
adata_color_etc=doc_adata_color_etc,
scatter_bulk=doc_scatter_embedding,
show_save_ax=doc_show_save_ax,
)
def pca(
adata: AnnData,
*,
annotate_var_explained: bool = False,
show: bool | None = None,
return_fig: bool | None = None,
save: bool | str | None = None, # deprecated
**kwargs,
) -> Figure | Axes | list[Axes] | None:
"""Scatter plot in PCA coordinates.
Use the parameter `annotate_var_explained` to annotate the explained variance.
Parameters
----------
{adata_color_etc}
annotate_var_explained
{scatter_bulk}
{show_save_ax}
Returns
-------
If `show==False` a :class:`~matplotlib.axes.Axes` or a list of it.
Examples
--------
.. plot::
:context: close-figs
import scanpy as sc
adata = sc.datasets.pbmc3k_processed()
sc.pl.pca(adata)
Colour points by discrete variable (Louvain clusters).
.. plot::
:context: close-figs
sc.pl.pca(adata, color="louvain")
Colour points by gene expression.
.. plot::
:context: close-figs
sc.pl.pca(adata, color="CST3")
.. currentmodule:: scanpy
See Also
--------
pp.pca
"""
if not annotate_var_explained:
return embedding(
adata, "pca", show=show, return_fig=return_fig, save=save, **kwargs
)
if "pca" not in adata.obsm and "X_pca" not in adata.obsm:
msg = (
f"Could not find entry in `obsm` for 'pca'.\n"
f"Available keys are: {list(adata.obsm.keys())}."
)
raise KeyError(msg)
label_dict = {
f"PC{i + 1}": f"PC{i + 1} ({round(v * 100, 2)}%)"
for i, v in enumerate(adata.uns["pca"]["variance_ratio"])
}
if return_fig is True:
# edit axis labels in returned figure
fig = embedding(adata, "pca", return_fig=return_fig, **kwargs)
for ax in fig.axes:
if xlabel := label_dict.get(ax.xaxis.get_label().get_text()):
ax.set_xlabel(xlabel)
if ylabel := label_dict.get(ax.yaxis.get_label().get_text()):
ax.set_ylabel(ylabel)
return fig
# get the axs, edit the labels and apply show and save from user
axs = embedding(adata, "pca", show=False, save=False, **kwargs)
if isinstance(axs, list):
for ax in axs:
ax.set_xlabel(label_dict[ax.xaxis.get_label().get_text()])
ax.set_ylabel(label_dict[ax.yaxis.get_label().get_text()])
else:
axs.set_xlabel(label_dict[axs.xaxis.get_label().get_text()])
axs.set_ylabel(label_dict[axs.yaxis.get_label().get_text()])
_utils.savefig_or_show("pca", show=show, save=save)
show = settings.autoshow if show is None else show
if show:
return None
return axs
@deprecated("Use `squidpy.pl.spatial_scatter` instead.")
@doctest_internet
@_wraps_plot_scatter
@_doc_params(
adata_color_etc=doc_adata_color_etc,
scatter_spatial=doc_scatter_spatial,
scatter_bulk=doc_scatter_embedding,
show_save_ax=doc_show_save_ax,
)
def spatial( # noqa: PLR0913
adata: AnnData,
*,
basis: str = "spatial",
img: np.ndarray | None = None,
img_key: str | None | Empty = _empty,
library_id: str | None | Empty = _empty,
crop_coord: tuple[int, int, int, int] | None = None,
alpha_img: float = 1.0,
bw: bool | None = False,
size: float = 1.0,
scale_factor: float | None = None,
spot_size: float | None = None,
na_color: ColorLike | None = None,
show: bool | None = None,
return_fig: bool | None = None,
save: bool | str | None = None, # deprecated
**kwargs,
) -> Figure | Axes | list[Axes] | None:
"""Scatter plot in spatial coordinates.
.. deprecated:: 1.11.0
Use :func:`squidpy.pl.spatial_scatter` instead.
This function allows overlaying data on top of images.
Use the parameter `img_key` to see the image in the background
And the parameter `library_id` to select the image.
By default, `'hires'` and `'lowres'` are attempted.
Use `crop_coord`, `alpha_img`, and `bw` to control how it is displayed.
Use `size` to scale the size of the Visium spots plotted on top.
As this function is designed to for imaging data, there are two key assumptions
about how coordinates are handled:
1. The origin (e.g `(0, 0)`) is at the top left – as is common convention
with image data.
2. Coordinates are in the pixel space of the source image, so an equal
aspect ratio is assumed.
If your anndata object has a `"spatial"` entry in `.uns`, the `img_key`