-
Notifications
You must be signed in to change notification settings - Fork 30
Expand file tree
/
Copy pathQC_plot.py
More file actions
157 lines (138 loc) · 4.19 KB
/
QC_plot.py
File metadata and controls
157 lines (138 loc) · 4.19 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
from matplotlib import pyplot as plt
import numpy as np
from typing import Optional, Union
from anndata import AnnData
def QC_plot(
adata: AnnData,
library_id: str = None,
name: str = None,
data_alpha: float = 0.8,
tissue_alpha: float = 1.0,
cmap: str = "Spectral_r",
spot_size: tuple = (5, 40),
show_color_bar: bool = True,
show_size_legend: bool = True,
show_axis: bool = False,
cropped: bool = True,
margin: int = 100,
dpi: int = 150,
output: str = None,
) -> Optional[AnnData]:
"""\
QC plot for sptial transcriptomics data.
Parameters
----------
adata
Annotated data matrix.
library_id
Library id stored in AnnData.
data_alpha
Opacity of the spot.
tissue_alpha
Opacity of the tissue.
cmap
Color map to use.
spot_size
Size of the spot (min, max).
show_color_bar
Show color bar or not.
show_axis
Show axis or not.
show_size_legend
Show size legend or not.
name
Name of the output figure file.
output
Save the figure as file or not.
copy
Return a copy instead of writing to adata.
Returns
-------
Nothing
"""
imagecol = adata.obs["imagecol"]
imagerow = adata.obs["imagerow"]
from sklearn.preprocessing import MinMaxScaler
reads_per_spot = adata.to_df().sum(axis=1)
scaler = MinMaxScaler(feature_range=spot_size)
reads_per_spot_size = scaler.fit_transform(reads_per_spot.to_numpy().reshape(-1, 1))
genes_per_spot = adata.to_df().astype(bool).sum(axis=1)
# plt.rcParams['figure.dpi'] = dpi
# Option for turning off showing figure
plt.ioff()
# Initialize matplotlib
fig, a = plt.subplots()
vmin = min(genes_per_spot)
vmax = max(genes_per_spot)
# Plot scatter plot based on pixel of spots
plot = a.scatter(
adata.obs["imagecol"],
adata.obs["imagerow"],
edgecolor="none",
alpha=data_alpha,
s=reads_per_spot_size,
marker="o",
vmin=vmin,
vmax=vmax,
cmap=plt.get_cmap(cmap),
c=genes_per_spot,
)
if show_color_bar:
from mpl_toolkits.axes_grid1.inset_locator import inset_axes
axins = inset_axes(
a,
width="100%",
height="100%",
loc="upper left",
bbox_to_anchor=(1.0, 0.73, 0.05, 0.35),
bbox_transform=a.transAxes,
borderpad=4.3,
)
cb = plt.colorbar(plot, cax=axins)
cb.ax.set_xlabel("Number of Genes", fontsize=10)
cb.ax.xaxis.set_label_coords(0.98, 1.20)
cb.outline.set_visible(False)
if show_size_legend:
size_min, size_max = spot_size
markers = [
size_min,
size_min + 1 / 3 * (size_max - size_min),
size_min + 2 / 3 * (size_max - size_min),
size_max,
]
legend_markers = [plt.scatter([], [], s=i, c="grey") for i in markers]
labels = [
str(int(scaler.inverse_transform(np.array(i).reshape(1, 1))))
for i in markers
]
a.legend(
handles=legend_markers,
labels=labels,
loc="lower left",
bbox_to_anchor=(1, 0.05),
scatterpoints=1,
frameon=False,
title="Number of Reads",
)
if not show_axis:
a.axis("off")
if library_id is None:
library_id = list(adata.uns["spatial"].keys())[0]
image = adata.uns["spatial"][library_id]["images"][
adata.uns["spatial"][library_id]["use_quality"]
]
# Overlay the tissue image
a.imshow(
image,
alpha=tissue_alpha,
zorder=-1,
)
if cropped:
a.set_xlim(imagecol.min() - margin, imagecol.max() + margin)
a.set_ylim(imagerow.min() - margin, imagerow.max() + margin)
a.set_ylim(a.get_ylim()[::-1])
# plt.gca().invert_yaxis()
# fig.tight_layout()
if output is not None:
fig.savefig(output + "/" + name, dpi=dpi, bbox_inches="tight", pad_inches=0)
plt.show()