-
Notifications
You must be signed in to change notification settings - Fork 579
/
_anndata.py
executable file
·2545 lines (2275 loc) · 85.8 KB
/
_anndata.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
"""Plotting functions for AnnData.
"""
import collections.abc as cabc
from itertools import product
from collections import OrderedDict
from typing import Optional, Union, Mapping, Literal # Special
from typing import Sequence, Collection, Iterable # ABCs
from typing import Tuple, List # Classes
import numpy as np
import pandas as pd
from anndata import AnnData
from cycler import Cycler
from matplotlib.axes import Axes
from pandas.api.types import is_categorical_dtype, is_numeric_dtype
from scipy.sparse import issparse
from matplotlib import pyplot as pl
from matplotlib import rcParams
from matplotlib import gridspec
from matplotlib import patheffects
from matplotlib.colors import is_color_like, Colormap, ListedColormap, Normalize
from .. import get
from .. import logging as logg
from .._settings import settings
from .._utils import sanitize_anndata, _doc_params, _check_use_raw
from . import _utils
from ._utils import scatter_base, scatter_group, setup_axes, check_colornorm
from ._utils import ColorLike, _FontWeight, _FontSize
from ._docs import (
doc_scatter_basic,
doc_show_save_ax,
doc_common_plot_args,
doc_vboundnorm,
)
VALID_LEGENDLOCS = {
'none',
'right margin',
'on data',
'on data export',
'best',
'upper right',
'upper left',
'lower left',
'lower right',
'right',
'center left',
'center right',
'lower center',
'upper center',
'center',
}
# TODO: is that all?
_Basis = Literal['pca', 'tsne', 'umap', 'diffmap', 'draw_graph_fr']
_VarNames = Union[str, Sequence[str]]
@_doc_params(scatter_temp=doc_scatter_basic, show_save_ax=doc_show_save_ax)
def scatter(
adata: AnnData,
x: Optional[str] = None,
y: Optional[str] = None,
color: Union[str, Collection[str]] = None,
use_raw: Optional[bool] = None,
layers: Union[str, Collection[str]] = None,
sort_order: bool = True,
alpha: Optional[float] = None,
basis: Optional[_Basis] = None,
groups: Union[str, Iterable[str]] = None,
components: Union[str, Collection[str]] = None,
projection: Literal['2d', '3d'] = '2d',
legend_loc: str = 'right margin',
legend_fontsize: Union[int, float, _FontSize, None] = None,
legend_fontweight: Union[int, _FontWeight, None] = None,
legend_fontoutline: float = None,
color_map: Union[str, Colormap] = None,
palette: Union[Cycler, ListedColormap, ColorLike, Sequence[ColorLike]] = None,
frameon: Optional[bool] = None,
right_margin: Optional[float] = None,
left_margin: Optional[float] = None,
size: Union[int, float, None] = None,
title: Optional[str] = None,
show: Optional[bool] = None,
save: Union[str, bool, None] = None,
ax: Optional[Axes] = None,
):
"""\
Scatter plot along observations or variables axes.
Color the plot using annotations of observations (`.obs`), variables
(`.var`) or expression of genes (`.var_names`).
Parameters
----------
adata
Annotated data matrix.
x
x coordinate.
y
y coordinate.
color
Keys for annotations of observations/cells or variables/genes,
or a hex color specification, e.g.,
`'ann1'`, `'#fe57a1'`, or `['ann1', 'ann2']`.
use_raw
Whether to use `raw` attribute of `adata`. Defaults to `True` if `.raw` is present.
layers
Use the `layers` attribute of `adata` if present: specify the layer for
`x`, `y` and `color`. If `layers` is a string, then it is expanded to
`(layers, layers, layers)`.
basis
String that denotes a plotting tool that computed coordinates.
{scatter_temp}
{show_save_ax}
Returns
-------
If `show==False` a :class:`~matplotlib.axes.Axes` or a list of it.
"""
args = locals()
if _check_use_raw(adata, use_raw):
var_index = adata.raw.var.index
else:
var_index = adata.var.index
if basis is not None:
return _scatter_obs(**args)
if x is None or y is None:
raise ValueError('Either provide a `basis` or `x` and `y`.')
if (
(x in adata.obs.keys() or x in var_index)
and (y in adata.obs.keys() or y in var_index)
and (color is None or color in adata.obs.keys() or color in var_index)
):
return _scatter_obs(**args)
if (
(x in adata.var.keys() or x in adata.obs.index)
and (y in adata.var.keys() or y in adata.obs.index)
and (color is None or color in adata.var.keys() or color in adata.obs.index)
):
adata_T = adata.T
axs = _scatter_obs(
adata=adata_T,
**{name: val for name, val in args.items() if name != 'adata'},
)
# store .uns annotations that were added to the new adata object
adata.uns = adata_T.uns
return axs
raise ValueError(
'`x`, `y`, and potential `color` inputs must all '
'come from either `.obs` or `.var`'
)
def _scatter_obs(
adata: AnnData,
x=None,
y=None,
color=None,
use_raw=None,
layers=None,
sort_order=True,
alpha=None,
basis=None,
groups=None,
components=None,
projection: Literal['2d', '3d'] = '2d',
legend_loc='right margin',
legend_fontsize=None,
legend_fontweight=None,
legend_fontoutline=None,
color_map=None,
palette=None,
frameon=None,
right_margin=None,
left_margin=None,
size=None,
title=None,
show=None,
save=None,
ax=None,
):
"""See docstring of scatter."""
sanitize_anndata(adata)
from scipy.sparse import issparse
use_raw = _check_use_raw(adata, use_raw)
# Process layers
if layers in ['X', None] or (
isinstance(layers, str) and layers in adata.layers.keys()
):
layers = (layers, layers, layers)
elif isinstance(layers, cabc.Collection) and len(layers) == 3:
layers = tuple(layers)
for layer in layers:
if layer not in adata.layers.keys() and layer not in ['X', None]:
raise ValueError(
'`layers` should have elements that are '
'either None or in adata.layers.keys().'
)
else:
raise ValueError(
"`layers` should be a string or a collection of strings "
f"with length 3, had value '{layers}'"
)
if use_raw and layers not in [('X', 'X', 'X'), (None, None, None)]:
ValueError('`use_raw` must be `False` if layers are used.')
if legend_loc not in VALID_LEGENDLOCS:
raise ValueError(
f'Invalid `legend_loc`, need to be one of: {VALID_LEGENDLOCS}.'
)
if components is None:
components = '1,2' if '2d' in projection else '1,2,3'
if isinstance(components, str):
components = components.split(',')
components = np.array(components).astype(int) - 1
# color can be a obs column name or a matplotlib color specification
keys = (
['grey']
if color is None
else [color]
if isinstance(color, str) or is_color_like(color)
else color
)
if title is not None and isinstance(title, str):
title = [title]
highlights = adata.uns['highlights'] if 'highlights' in adata.uns else []
if basis is not None:
try:
# ignore the '0th' diffusion component
if basis == 'diffmap':
components += 1
Y = adata.obsm['X_' + basis][:, components]
# correct the component vector for use in labeling etc.
if basis == 'diffmap':
components -= 1
except KeyError:
raise KeyError(
f'compute coordinates using visualization tool {basis} first'
)
elif x is not None and y is not None:
if use_raw:
if x in adata.obs.columns:
x_arr = adata.obs_vector(x)
else:
x_arr = adata.raw.obs_vector(x)
if y in adata.obs.columns:
y_arr = adata.obs_vector(y)
else:
y_arr = adata.raw.obs_vector(y)
else:
x_arr = adata.obs_vector(x, layer=layers[0])
y_arr = adata.obs_vector(y, layer=layers[1])
Y = np.c_[x_arr, y_arr]
else:
raise ValueError('Either provide a `basis` or `x` and `y`.')
if size is None:
n = Y.shape[0]
size = 120000 / n
if legend_loc.startswith('on data') and legend_fontsize is None:
legend_fontsize = rcParams['legend.fontsize']
elif legend_fontsize is None:
legend_fontsize = rcParams['legend.fontsize']
palette_was_none = False
if palette is None:
palette_was_none = True
if isinstance(palette, cabc.Sequence) and not isinstance(palette, str):
if not is_color_like(palette[0]):
palettes = palette
else:
palettes = [palette]
else:
palettes = [palette for _ in range(len(keys))]
palettes = [_utils.default_palette(palette) for palette in palettes]
if basis is not None:
component_name = (
'DC'
if basis == 'diffmap'
else 'tSNE'
if basis == 'tsne'
else 'UMAP'
if basis == 'umap'
else 'PC'
if basis == 'pca'
else 'TriMap'
if basis == 'trimap'
else basis.replace('draw_graph_', '').upper()
if 'draw_graph' in basis
else basis
)
else:
component_name = None
axis_labels = (x, y) if component_name is None else None
show_ticks = True if component_name is None else False
# generate the colors
color_ids = []
categoricals = []
colorbars = []
for ikey, key in enumerate(keys):
c = 'white'
categorical = False # by default, assume continuous or flat color
colorbar = None
# test whether we have categorial or continuous annotation
if key in adata.obs_keys():
if is_categorical_dtype(adata.obs[key]):
categorical = True
else:
c = adata.obs[key]
# coloring according to gene expression
elif use_raw and adata.raw is not None and key in adata.raw.var_names:
c = adata.raw.obs_vector(key)
elif key in adata.var_names:
c = adata.obs_vector(key, layer=layers[2])
elif is_color_like(key): # a flat color
c = key
colorbar = False
else:
raise ValueError(
f'key {key!r} is invalid! pass valid observation annotation, '
f'one of {adata.obs_keys()} or a gene name {adata.var_names}'
)
if colorbar is None:
colorbar = not categorical
colorbars.append(colorbar)
if categorical:
categoricals.append(ikey)
color_ids.append(c)
if right_margin is None and len(categoricals) > 0:
if legend_loc == 'right margin':
right_margin = 0.5
if title is None and keys[0] is not None:
title = [
key.replace('_', ' ') if not is_color_like(key) else '' for key in keys
]
axs = scatter_base(
Y,
title=title,
alpha=alpha,
component_name=component_name,
axis_labels=axis_labels,
component_indexnames=components + 1,
projection=projection,
colors=color_ids,
highlights=highlights,
colorbars=colorbars,
right_margin=right_margin,
left_margin=left_margin,
sizes=[size for _ in keys],
color_map=color_map,
show_ticks=show_ticks,
ax=ax,
)
def add_centroid(centroids, name, Y, mask):
Y_mask = Y[mask]
if Y_mask.shape[0] == 0:
return
median = np.median(Y_mask, axis=0)
i = np.argmin(np.sum(np.abs(Y_mask - median), axis=1))
centroids[name] = Y_mask[i]
# loop over all categorical annotation and plot it
for ikey, palette in zip(categoricals, palettes):
key = keys[ikey]
_utils.add_colors_for_categorical_sample_annotation(
adata, key, palette, force_update_colors=not palette_was_none
)
# actually plot the groups
mask_remaining = np.ones(Y.shape[0], dtype=bool)
centroids = {}
if groups is None:
for iname, name in enumerate(adata.obs[key].cat.categories):
if name not in settings.categories_to_ignore:
mask = scatter_group(
axs[ikey],
key,
iname,
adata,
Y,
projection,
size=size,
alpha=alpha,
)
mask_remaining[mask] = False
if legend_loc.startswith('on data'):
add_centroid(centroids, name, Y, mask)
else:
groups = [groups] if isinstance(groups, str) else groups
for name in groups:
if name not in set(adata.obs[key].cat.categories):
raise ValueError(
f'{name!r} is invalid! specify valid name, '
f'one of {adata.obs[key].cat.categories}'
)
else:
iname = np.flatnonzero(
adata.obs[key].cat.categories.values == name
)[0]
mask = scatter_group(
axs[ikey],
key,
iname,
adata,
Y,
projection,
size=size,
alpha=alpha,
)
if legend_loc.startswith('on data'):
add_centroid(centroids, name, Y, mask)
mask_remaining[mask] = False
if mask_remaining.sum() > 0:
data = [Y[mask_remaining, 0], Y[mask_remaining, 1]]
if projection == '3d':
data.append(Y[mask_remaining, 2])
axs[ikey].scatter(
*data,
marker='.',
c='lightgrey',
s=size,
edgecolors='none',
zorder=-1,
)
legend = None
if legend_loc.startswith('on data'):
if legend_fontweight is None:
legend_fontweight = 'bold'
if legend_fontoutline is not None:
path_effect = [
patheffects.withStroke(linewidth=legend_fontoutline, foreground='w')
]
else:
path_effect = None
for name, pos in centroids.items():
axs[ikey].text(
pos[0],
pos[1],
name,
weight=legend_fontweight,
verticalalignment='center',
horizontalalignment='center',
fontsize=legend_fontsize,
path_effects=path_effect,
)
all_pos = np.zeros((len(adata.obs[key].cat.categories), 2))
for iname, name in enumerate(adata.obs[key].cat.categories):
if name in centroids:
all_pos[iname] = centroids[name]
else:
all_pos[iname] = [np.nan, np.nan]
if legend_loc == 'on data export':
filename = settings.writedir / 'pos.csv'
logg.warning(f'exporting label positions to {filename}')
settings.writedir.mkdir(parents=True, exist_ok=True)
np.savetxt(filename, all_pos, delimiter=',')
elif legend_loc == 'right margin':
legend = axs[ikey].legend(
frameon=False,
loc='center left',
bbox_to_anchor=(1, 0.5),
ncol=(
1
if len(adata.obs[key].cat.categories) <= 14
else 2
if len(adata.obs[key].cat.categories) <= 30
else 3
),
fontsize=legend_fontsize,
)
elif legend_loc != 'none':
legend = axs[ikey].legend(
frameon=False, loc=legend_loc, fontsize=legend_fontsize
)
if legend is not None:
for handle in legend.legendHandles:
handle.set_sizes([300.0])
# draw a frame around the scatter
frameon = settings._frameon if frameon is None else frameon
if not frameon and x is None and y is None:
for ax in axs:
ax.set_xlabel('')
ax.set_ylabel('')
ax.set_frame_on(False)
show = settings.autoshow if show is None else show
_utils.savefig_or_show('scatter' if basis is None else basis, show=show, save=save)
if not show:
return axs if len(keys) > 1 else axs[0]
def ranking(
adata: AnnData,
attr: Literal['var', 'obs', 'uns', 'varm', 'obsm'],
keys: Union[str, Sequence[str]],
dictionary=None,
indices=None,
labels=None,
color='black',
n_points=30,
log=False,
include_lowest=False,
show=None,
):
"""\
Plot rankings.
See, for example, how this is used in pl.pca_ranking.
Parameters
----------
adata
The data.
attr
The attribute of AnnData that contains the score.
keys
The scores to look up an array from the attribute of adata.
Returns
-------
Returns matplotlib gridspec with access to the axes.
"""
if isinstance(keys, str) and indices is not None:
scores = getattr(adata, attr)[keys][:, indices]
keys = [f'{keys[:-1]}{i + 1}' for i in indices]
else:
if dictionary is None:
scores = getattr(adata, attr)[keys]
else:
scores = getattr(adata, attr)[dictionary][keys]
n_panels = len(keys) if isinstance(keys, list) else 1
if n_panels == 1:
scores, keys = scores[:, None], [keys]
if log:
scores = np.log(scores)
if labels is None:
labels = (
adata.var_names
if attr in {'var', 'varm'}
else np.arange(scores.shape[0]).astype(str)
)
if isinstance(labels, str):
labels = [labels + str(i + 1) for i in range(scores.shape[0])]
if n_panels <= 5:
n_rows, n_cols = 1, n_panels
else:
n_rows, n_cols = 2, int(n_panels / 2 + 0.5)
_ = pl.figure(
figsize=(
n_cols * rcParams['figure.figsize'][0],
n_rows * rcParams['figure.figsize'][1],
)
)
left, bottom = 0.2 / n_cols, 0.13 / n_rows
gs = gridspec.GridSpec(
wspace=0.2,
nrows=n_rows,
ncols=n_cols,
left=left,
bottom=bottom,
right=1 - (n_cols - 1) * left - 0.01 / n_cols,
top=1 - (n_rows - 1) * bottom - 0.1 / n_rows,
)
for iscore, score in enumerate(scores.T):
pl.subplot(gs[iscore])
order_scores = np.argsort(score)[::-1]
if not include_lowest:
indices = order_scores[: n_points + 1]
else:
indices = order_scores[: n_points // 2]
neg_indices = order_scores[-(n_points - (n_points // 2)) :]
txt_args = dict(
color=color,
rotation='vertical',
verticalalignment='bottom',
horizontalalignment='center',
fontsize=8,
)
for ig, g in enumerate(indices):
pl.text(ig, score[g], labels[g], **txt_args)
if include_lowest:
score_mid = (score[g] + score[neg_indices[0]]) / 2
if (len(indices) + len(neg_indices)) < len(order_scores):
pl.text(len(indices), score_mid, '⋮', **txt_args)
for ig, g in enumerate(neg_indices):
pl.text(ig + len(indices) + 2, score[g], labels[g], **txt_args)
else:
for ig, g in enumerate(neg_indices):
pl.text(ig + len(indices), score[g], labels[g], **txt_args)
pl.xticks([])
pl.title(keys[iscore].replace('_', ' '))
if n_panels <= 5 or iscore > n_cols:
pl.xlabel('ranking')
pl.xlim(-0.9, n_points + 0.9 + (1 if include_lowest else 0))
score_min, score_max = (
np.min(score[neg_indices if include_lowest else indices]),
np.max(score[indices]),
)
pl.ylim(
(0.95 if score_min > 0 else 1.05) * score_min,
(1.05 if score_max > 0 else 0.95) * score_max,
)
show = settings.autoshow if show is None else show
if not show:
return gs
@_doc_params(show_save_ax=doc_show_save_ax)
def violin(
adata: AnnData,
keys: Union[str, Sequence[str]],
groupby: Optional[str] = None,
log: bool = False,
use_raw: Optional[bool] = None,
stripplot: bool = True,
jitter: Union[float, bool] = True,
size: int = 1,
layer: Optional[str] = None,
scale: Literal['area', 'count', 'width'] = 'width',
order: Optional[Sequence[str]] = None,
multi_panel: Optional[bool] = None,
xlabel: str = '',
ylabel: Optional[Union[str, Sequence[str]]] = None,
rotation: Optional[float] = None,
show: Optional[bool] = None,
save: Union[bool, str, None] = None,
ax: Optional[Axes] = None,
**kwds,
):
"""\
Violin plot.
Wraps :func:`seaborn.violinplot` for :class:`~anndata.AnnData`.
Parameters
----------
adata
Annotated data matrix.
keys
Keys for accessing variables of `.var_names` or fields of `.obs`.
groupby
The key of the observation grouping to consider.
log
Plot on logarithmic axis.
use_raw
Whether to use `raw` attribute of `adata`. Defaults to `True` if `.raw` is present.
stripplot
Add a stripplot on top of the violin plot.
See :func:`~seaborn.stripplot`.
jitter
Add jitter to the stripplot (only when stripplot is True)
See :func:`~seaborn.stripplot`.
size
Size of the jitter points.
layer
Name of the AnnData object layer that wants to be plotted. By
default adata.raw.X is plotted. If `use_raw=False` is set,
then `adata.X` is plotted. If `layer` is set to a valid layer name,
then the layer is plotted. `layer` takes precedence over `use_raw`.
scale
The method used to scale the width of each violin.
If 'width' (the default), each violin will have the same width.
If 'area', each violin will have the same area.
If 'count', a violin’s width corresponds to the number of observations.
order
Order in which to show the categories.
multi_panel
Display keys in multiple panels also when `groupby is not None`.
xlabel
Label of the x axis. Defaults to `groupby` if `rotation` is `None`,
otherwise, no label is shown.
ylabel
Label of the y axis. If `None` and `groupby` is `None`, defaults
to `'value'`. If `None` and `groubpy` is not `None`, defaults to `keys`.
rotation
Rotation of xtick labels.
{show_save_ax}
**kwds
Are passed to :func:`~seaborn.violinplot`.
Returns
-------
A :class:`~matplotlib.axes.Axes` object if `ax` is `None` else `None`.
Examples
--------
.. plot::
:context: close-figs
import scanpy as sc
adata = sc.datasets.pbmc68k_reduced()
sc.pl.violin(adata, keys='S_score')
Plot by category. Rotate x-axis labels so that they do not overlap.
.. plot::
:context: close-figs
sc.pl.violin(adata, keys='S_score', groupby='bulk_labels', rotation=90)
Set order of categories to be plotted or select specific categories to be plotted.
.. plot::
:context: close-figs
groupby_order = ['CD34+', 'CD19+ B']
sc.pl.violin(adata, keys='S_score', groupby='bulk_labels', rotation=90,
order=groupby_order)
Plot multiple keys.
.. plot::
:context: close-figs
sc.pl.violin(adata, keys=['S_score', 'G2M_score'], groupby='bulk_labels',
rotation=90)
For large datasets consider omitting the overlaid scatter plot.
.. plot::
:context: close-figs
sc.pl.violin(adata, keys='S_score', stripplot=False)
.. currentmodule:: scanpy
See also
--------
pl.stacked_violin
"""
import seaborn as sns # Slow import, only import if called
sanitize_anndata(adata)
use_raw = _check_use_raw(adata, use_raw)
if isinstance(keys, str):
keys = [keys]
keys = list(OrderedDict.fromkeys(keys)) # remove duplicates, preserving the order
if isinstance(ylabel, (str, type(None))):
ylabel = [ylabel] * (1 if groupby is None else len(keys))
if groupby is None:
if len(ylabel) != 1:
raise ValueError(
f'Expected number of y-labels to be `1`, found `{len(ylabel)}`.'
)
elif len(ylabel) != len(keys):
raise ValueError(
f'Expected number of y-labels to be `{len(keys)}`, '
f'found `{len(ylabel)}`.'
)
if groupby is not None:
obs_df = get.obs_df(adata, keys=[groupby] + keys, layer=layer, use_raw=use_raw)
if kwds.get('palette', None) is None:
if not is_categorical_dtype(adata.obs[groupby]):
raise ValueError(
f'The column `adata.obs[{groupby!r}]` needs to be categorical, '
f'but is of dtype {adata.obs[groupby].dtype}.'
)
_utils.add_colors_for_categorical_sample_annotation(adata, groupby)
kwds['palette'] = dict(
zip(obs_df[groupby].cat.categories, adata.uns[f'{groupby}_colors'])
)
else:
obs_df = get.obs_df(adata, keys=keys, layer=layer, use_raw=use_raw)
if groupby is None:
obs_tidy = pd.melt(obs_df, value_vars=keys)
x = 'variable'
ys = ['value']
else:
obs_tidy = obs_df
x = groupby
ys = keys
if multi_panel and groupby is None and len(ys) == 1:
# This is a quick and dirty way for adapting scales across several
# keys if groupby is None.
y = ys[0]
g = sns.catplot(
y=y,
data=obs_tidy,
kind="violin",
scale=scale,
col=x,
col_order=keys,
sharey=False,
order=keys,
cut=0,
inner=None,
**kwds,
)
if stripplot:
grouped_df = obs_tidy.groupby(x)
for ax_id, key in zip(range(g.axes.shape[1]), keys):
sns.stripplot(
y=y,
data=grouped_df.get_group(key),
jitter=jitter,
size=size,
color="black",
ax=g.axes[0, ax_id],
)
if log:
g.set(yscale='log')
g.set_titles(col_template='{col_name}').set_xlabels('')
if rotation is not None:
for ax in g.axes[0]:
ax.tick_params(axis='x', labelrotation=rotation)
else:
# set by default the violin plot cut=0 to limit the extend
# of the violin plot (see stacked_violin code) for more info.
kwds.setdefault('cut', 0)
kwds.setdefault('inner')
if ax is None:
axs, _, _, _ = setup_axes(
ax=ax,
panels=['x'] if groupby is None else keys,
show_ticks=True,
right_margin=0.3,
)
else:
axs = [ax]
for ax, y, ylab in zip(axs, ys, ylabel):
ax = sns.violinplot(
x=x,
y=y,
data=obs_tidy,
order=order,
orient='vertical',
scale=scale,
ax=ax,
**kwds,
)
if stripplot:
ax = sns.stripplot(
x=x,
y=y,
data=obs_tidy,
order=order,
jitter=jitter,
color='black',
size=size,
ax=ax,
)
if xlabel == '' and groupby is not None and rotation is None:
xlabel = groupby.replace('_', ' ')
ax.set_xlabel(xlabel)
if ylab is not None:
ax.set_ylabel(ylab)
if log:
ax.set_yscale('log')
if rotation is not None:
ax.tick_params(axis='x', labelrotation=rotation)
show = settings.autoshow if show is None else show
_utils.savefig_or_show('violin', show=show, save=save)
if not show:
if multi_panel and groupby is None and len(ys) == 1:
return g
elif len(axs) == 1:
return axs[0]
else:
return axs
@_doc_params(show_save_ax=doc_show_save_ax)
def clustermap(
adata: AnnData,
obs_keys: str = None,
use_raw: Optional[bool] = None,
show: Optional[bool] = None,
save: Union[bool, str, None] = None,
**kwds,
):
"""\
Hierarchically-clustered heatmap.
Wraps :func:`seaborn.clustermap` for :class:`~anndata.AnnData`.
Parameters
----------
adata
Annotated data matrix.
obs_keys
Categorical annotation to plot with a different color map.
Currently, only a single key is supported.
use_raw
Whether to use `raw` attribute of `adata`. Defaults to `True` if `.raw` is present.
{show_save_ax}
**kwds
Keyword arguments passed to :func:`~seaborn.clustermap`.
Returns
-------
If `show` is `False`, a :class:`~seaborn.ClusterGrid` object
(see :func:`~seaborn.clustermap`).
Examples
--------
Soon to come with figures. In the meanwile, see :func:`~seaborn.clustermap`.
>>> import scanpy as sc
>>> adata = sc.datasets.krumsiek11()
>>> sc.pl.clustermap(adata, obs_keys='cell_type')
"""
import seaborn as sns # Slow import, only import if called
if not isinstance(obs_keys, (str, type(None))):
raise ValueError('Currently, only a single key is supported.')
sanitize_anndata(adata)
use_raw = _check_use_raw(adata, use_raw)
X = adata.raw.X if use_raw else adata.X
if issparse(X):
X = X.toarray()
df = pd.DataFrame(X, index=adata.obs_names, columns=adata.var_names)
if obs_keys is not None:
row_colors = adata.obs[obs_keys]
_utils.add_colors_for_categorical_sample_annotation(adata, obs_keys)
# do this more efficiently... just a quick solution
lut = dict(zip(row_colors.cat.categories, adata.uns[obs_keys + '_colors']))
row_colors = adata.obs[obs_keys].map(lut)
g = sns.clustermap(df, row_colors=row_colors.values, **kwds)
else:
g = sns.clustermap(df, **kwds)
show = settings.autoshow if show is None else show
_utils.savefig_or_show('clustermap', show=show, save=save)
if show:
pl.show()
else:
return g
@_doc_params(
vminmax=doc_vboundnorm,
show_save_ax=doc_show_save_ax,
common_plot_args=doc_common_plot_args,
)
def heatmap(
adata: AnnData,
var_names: Union[_VarNames, Mapping[str, _VarNames]],
groupby: Union[str, Sequence[str]],
use_raw: Optional[bool] = None,
log: bool = False,
num_categories: int = 7,
dendrogram: Union[bool, str] = False,
gene_symbols: Optional[str] = None,
var_group_positions: Optional[Sequence[Tuple[int, int]]] = None,
var_group_labels: Optional[Sequence[str]] = None,
var_group_rotation: Optional[float] = None,
layer: Optional[str] = None,
standard_scale: Optional[Literal['var', 'obs']] = None,
swap_axes: bool = False,
show_gene_labels: Optional[bool] = None,
show: Optional[bool] = None,
save: Union[str, bool, None] = None,
figsize: Optional[Tuple[float, float]] = None,
vmin: Optional[float] = None,
vmax: Optional[float] = None,
vcenter: Optional[float] = None,
norm: Optional[Normalize] = None,
**kwds,
):
"""\
Heatmap of the expression values of genes.
If `groupby` is given, the heatmap is ordered by the respective group. For
example, a list of marker genes can be plotted, ordered by clustering. If
the `groupby` observation annotation is not categorical the observation
annotation is turned into a categorical by binning the data into the number
specified in `num_categories`.
Parameters
----------
{common_plot_args}
standard_scale
Whether or not to standardize that dimension between 0 and 1, meaning for each variable or observation,
subtract the minimum and divide each by its maximum.
swap_axes
By default, the x axis contains `var_names` (e.g. genes) and the y axis the `groupby`
categories (if any). By setting `swap_axes` then x are the `groupby` categories and y the `var_names`.
show_gene_labels
By default gene labels are shown when there are 50 or less genes. Otherwise the labels are removed.
{show_save_ax}
{vminmax}