SPACEc 0.0.2__py3-none-any.whl
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- SPACEc-0.0.2.dist-info/LICENSE.txt +21 -0
- SPACEc-0.0.2.dist-info/METADATA +135 -0
- SPACEc-0.0.2.dist-info/RECORD +21 -0
- SPACEc-0.0.2.dist-info/WHEEL +5 -0
- SPACEc-0.0.2.dist-info/top_level.txt +1 -0
- spacec/__init__.py +38 -0
- spacec/_shared/segmentation.py +194 -0
- spacec/_shared/segmentation_unused.py +80 -0
- spacec/helperfunctions/__init__.py +4 -0
- spacec/helperfunctions/_general.py +1076 -0
- spacec/helperfunctions/_qptiff_converter.py +44 -0
- spacec/plotting/__init__.py +40 -0
- spacec/plotting/_general.py +4665 -0
- spacec/plotting/_qptiff_converter.py +40 -0
- spacec/plotting/_segmentation.py +227 -0
- spacec/preprocessing/__init__.py +8 -0
- spacec/preprocessing/_general.py +431 -0
- spacec/tools/__init__.py +32 -0
- spacec/tools/_general.py +3561 -0
- spacec/tools/_qptiff_converter.py +144 -0
- spacec/tools/_segmentation.py +895 -0
|
@@ -0,0 +1,4665 @@
|
|
|
1
|
+
# load required packages
|
|
2
|
+
import os as os
|
|
3
|
+
import pathlib
|
|
4
|
+
import textwrap
|
|
5
|
+
|
|
6
|
+
import matplotlib.colors as mcolors
|
|
7
|
+
import matplotlib.patches as mpatches
|
|
8
|
+
import matplotlib.pyplot as plt
|
|
9
|
+
import networkx as nx
|
|
10
|
+
import numpy as np
|
|
11
|
+
import pandas as pd
|
|
12
|
+
import scipy as sp
|
|
13
|
+
import seaborn as sns
|
|
14
|
+
import skimage
|
|
15
|
+
import tensorly as tl
|
|
16
|
+
from scipy import stats
|
|
17
|
+
from statsmodels.stats.multicomp import pairwise_tukeyhsd
|
|
18
|
+
from tensorly.decomposition import non_negative_tucker
|
|
19
|
+
|
|
20
|
+
from ..helperfunctions._general import *
|
|
21
|
+
|
|
22
|
+
# Setup
|
|
23
|
+
sns.set_style("ticks")
|
|
24
|
+
|
|
25
|
+
|
|
26
|
+
# plotting functions
|
|
27
|
+
############################################################
|
|
28
|
+
|
|
29
|
+
|
|
30
|
+
"""
|
|
31
|
+
This is a function that creates a stacked bar plot of the percentage of observations in each category in a dataset. The input data can be normalized by a grouping variable or not, and the output can be saved as a file.
|
|
32
|
+
|
|
33
|
+
data: a Pandas DataFrame containing the data to be plotted.
|
|
34
|
+
per_cat: a string representing the column name containing the categories to be plotted.
|
|
35
|
+
grouping: a string representing the column name used to group the data.
|
|
36
|
+
cell_list: a list of strings representing the categories to be plotted.
|
|
37
|
+
output_dir: a string representing the output directory to save the plot.
|
|
38
|
+
norm: a boolean value indicating whether to normalize the data or not (default: True).
|
|
39
|
+
save_name: a string representing the filename to save the plot (default: None).
|
|
40
|
+
col_order: a list of strings representing the order of the columns in the plot (default: None).
|
|
41
|
+
sub_col: a string representing the column name used to subset the data (default: None).
|
|
42
|
+
name_cat: a string representing the name of the category column in the plot (default: 'Cell Type').
|
|
43
|
+
fig_sizing: a tuple representing the size of the plot (default: (8,4)).
|
|
44
|
+
plot_order: a list of strings representing the order of the categories in the plot (default: None).
|
|
45
|
+
color_dic: a dictionary containing color codes for the categories in the plot (default: None).
|
|
46
|
+
remove_leg: a boolean value indicating whether to remove the legend or not (default: False).
|
|
47
|
+
|
|
48
|
+
The function returns a Pandas DataFrame and a list of strings. The DataFrame contains the data used to create the plot, and the list of strings represents the order of the categories in the plot.
|
|
49
|
+
"""
|
|
50
|
+
|
|
51
|
+
|
|
52
|
+
def pl_stacked_bar_plot(
|
|
53
|
+
data,
|
|
54
|
+
per_cat,
|
|
55
|
+
grouping,
|
|
56
|
+
cell_list,
|
|
57
|
+
output_dir,
|
|
58
|
+
norm=True,
|
|
59
|
+
save_name=None,
|
|
60
|
+
col_order=None,
|
|
61
|
+
sub_col=None,
|
|
62
|
+
name_cat="Cell Type",
|
|
63
|
+
fig_sizing=(8, 4),
|
|
64
|
+
plot_order=None,
|
|
65
|
+
color_dic=None,
|
|
66
|
+
remove_leg=False,
|
|
67
|
+
):
|
|
68
|
+
"""
|
|
69
|
+
Plot a stacked bar plot based on the given data.
|
|
70
|
+
|
|
71
|
+
Parameters
|
|
72
|
+
----------
|
|
73
|
+
data : pandas.DataFrame
|
|
74
|
+
The input data containing the necessary information for plotting.
|
|
75
|
+
per_cat : str
|
|
76
|
+
The column name representing the categories.
|
|
77
|
+
grouping : str
|
|
78
|
+
The column name representing the grouping.
|
|
79
|
+
cell_list : list
|
|
80
|
+
The list of cell types to include in the plot.
|
|
81
|
+
output_dir : str
|
|
82
|
+
The output directory for saving the plot.
|
|
83
|
+
norm : bool, optional
|
|
84
|
+
Flag indicating whether to normalize the values. Defaults to True.
|
|
85
|
+
save_name : str, optional
|
|
86
|
+
The name to use when saving the plot. Defaults to None.
|
|
87
|
+
col_order : list, optional
|
|
88
|
+
The order of columns/categories for plotting. Defaults to None.
|
|
89
|
+
sub_col : str, optional
|
|
90
|
+
The column name representing sub-categories. Defaults to None.
|
|
91
|
+
name_cat : str, optional
|
|
92
|
+
The name for the category column in the plot. Defaults to 'Cell Type'.
|
|
93
|
+
fig_sizing : tuple, optional
|
|
94
|
+
The size of the figure (width, height) in inches. Defaults to (8, 4).
|
|
95
|
+
plot_order : list, optional
|
|
96
|
+
The order of categories for plotting. Defaults to None.
|
|
97
|
+
color_dic : dict, optional
|
|
98
|
+
A dictionary mapping categories to colors for custom colorization. Defaults to None.
|
|
99
|
+
remove_leg : bool, optional
|
|
100
|
+
Flag indicating whether to remove the legend. Defaults to False.
|
|
101
|
+
|
|
102
|
+
Returns
|
|
103
|
+
-------
|
|
104
|
+
pandas.DataFrame
|
|
105
|
+
The pivoted data used for plotting.
|
|
106
|
+
list
|
|
107
|
+
The order of categories used for plotting.
|
|
108
|
+
"""
|
|
109
|
+
|
|
110
|
+
# Find Percentage of cell type
|
|
111
|
+
if norm == True:
|
|
112
|
+
if sub_col is None:
|
|
113
|
+
test1 = data.loc[data[per_cat].isin(cell_list)]
|
|
114
|
+
sub_cell_list = list(test1[per_cat].unique())
|
|
115
|
+
else:
|
|
116
|
+
test1 = data.loc[data[sub_col].isin(cell_list)]
|
|
117
|
+
sub_cell_list = list(test1[per_cat].unique())
|
|
118
|
+
else:
|
|
119
|
+
if sub_col is None:
|
|
120
|
+
test1 = data.copy()
|
|
121
|
+
sub_cell_list = list(
|
|
122
|
+
data.loc[data[per_cat].isin(cell_list)][per_cat].unique()
|
|
123
|
+
)
|
|
124
|
+
else:
|
|
125
|
+
test1 = data.copy()
|
|
126
|
+
sub_cell_list = list(
|
|
127
|
+
data.loc[data[sub_col].isin(cell_list)][per_cat].unique()
|
|
128
|
+
)
|
|
129
|
+
|
|
130
|
+
test1[per_cat] = test1[per_cat].astype("category")
|
|
131
|
+
test_freq = test1.groupby(grouping).apply(
|
|
132
|
+
lambda x: x[per_cat].value_counts(normalize=True, sort=False) * 100
|
|
133
|
+
)
|
|
134
|
+
test_freq.columns = test_freq.columns.astype(str)
|
|
135
|
+
|
|
136
|
+
##### Can subset it here if I do not want normalized per the group
|
|
137
|
+
test_freq.reset_index(inplace=True)
|
|
138
|
+
sub_cell_list.append(grouping)
|
|
139
|
+
test_freq = test_freq[sub_cell_list]
|
|
140
|
+
melt_test = pd.melt(
|
|
141
|
+
test_freq, id_vars=[grouping]
|
|
142
|
+
) # , value_vars=test_freq.columns)
|
|
143
|
+
melt_test.rename(columns={per_cat: name_cat, "value": "percent"}, inplace=True)
|
|
144
|
+
|
|
145
|
+
if norm == True:
|
|
146
|
+
if col_order is None:
|
|
147
|
+
bb = melt_test.groupby([grouping, per_cat]).sum().reset_index()
|
|
148
|
+
col_order = (
|
|
149
|
+
bb.loc[bb[per_cat] == bb[per_cat][0]]
|
|
150
|
+
.sort_values(by="percent")[grouping]
|
|
151
|
+
.to_list()
|
|
152
|
+
)
|
|
153
|
+
else:
|
|
154
|
+
if col_order is None:
|
|
155
|
+
col_order = (
|
|
156
|
+
melt_test.groupby(grouping)
|
|
157
|
+
.sum()
|
|
158
|
+
.reset_index()
|
|
159
|
+
.sort_values(by="percent")[grouping]
|
|
160
|
+
.to_list()
|
|
161
|
+
)
|
|
162
|
+
|
|
163
|
+
if plot_order is None:
|
|
164
|
+
plot_order = list(melt_test[per_cat].unique())
|
|
165
|
+
|
|
166
|
+
# Set up for plotting
|
|
167
|
+
melt_test_piv = pd.pivot_table(
|
|
168
|
+
melt_test, columns=[name_cat], index=[grouping], values=["percent"]
|
|
169
|
+
)
|
|
170
|
+
melt_test_piv.columns = melt_test_piv.columns.droplevel(0)
|
|
171
|
+
melt_test_piv.reset_index(inplace=True)
|
|
172
|
+
melt_test_piv.set_index(grouping, inplace=True)
|
|
173
|
+
melt_test_piv = melt_test_piv.reindex(col_order)
|
|
174
|
+
melt_test_piv = melt_test_piv[plot_order]
|
|
175
|
+
|
|
176
|
+
# Get color dictionary
|
|
177
|
+
if color_dic is None:
|
|
178
|
+
# first subplot
|
|
179
|
+
ax1 = melt_test_piv.plot.bar(
|
|
180
|
+
alpha=0.8,
|
|
181
|
+
linewidth=1,
|
|
182
|
+
figsize=fig_sizing,
|
|
183
|
+
rot=90,
|
|
184
|
+
stacked=True,
|
|
185
|
+
edgecolor="black",
|
|
186
|
+
)
|
|
187
|
+
|
|
188
|
+
else:
|
|
189
|
+
# first subplot
|
|
190
|
+
ax1 = melt_test_piv.plot.bar(
|
|
191
|
+
alpha=0.8,
|
|
192
|
+
linewidth=1,
|
|
193
|
+
color=[color_dic.get(x) for x in melt_test_piv.columns],
|
|
194
|
+
figsize=fig_sizing,
|
|
195
|
+
rot=90,
|
|
196
|
+
stacked=True,
|
|
197
|
+
edgecolor="black",
|
|
198
|
+
)
|
|
199
|
+
|
|
200
|
+
for line in ax1.lines:
|
|
201
|
+
line.set_color("black")
|
|
202
|
+
ax1.spines["top"].set_visible(False)
|
|
203
|
+
ax1.spines["right"].set_visible(False)
|
|
204
|
+
if remove_leg == True:
|
|
205
|
+
ax1.set_ylabel("")
|
|
206
|
+
ax1.set_xlabel("")
|
|
207
|
+
else:
|
|
208
|
+
ax1.set_ylabel("percent")
|
|
209
|
+
# ax1.spines['left'].set_position(('data', 1.0))
|
|
210
|
+
# ax1.set_xticks(np.arange(1,melt_test.day.max()+1,1))
|
|
211
|
+
# ax1.set_ylim([0, int(ceil(max(max(melt_test_piv.sum(axis=1)), max(tm_piv.sum(axis=1)))))])
|
|
212
|
+
plt.xticks(
|
|
213
|
+
list(range(len(list(melt_test_piv.index)))),
|
|
214
|
+
list(melt_test_piv.index),
|
|
215
|
+
rotation=90,
|
|
216
|
+
)
|
|
217
|
+
lgd2 = ax1.legend(
|
|
218
|
+
loc="center left", bbox_to_anchor=(1.0, 0.5), ncol=1, frameon=False
|
|
219
|
+
)
|
|
220
|
+
if save_name:
|
|
221
|
+
plt.savefig(
|
|
222
|
+
output_dir + save_name + "_stacked_barplot.pdf",
|
|
223
|
+
dpi=300,
|
|
224
|
+
transparent=True,
|
|
225
|
+
bbox_inches="tight",
|
|
226
|
+
)
|
|
227
|
+
return melt_test_piv, plot_order
|
|
228
|
+
|
|
229
|
+
|
|
230
|
+
#############
|
|
231
|
+
|
|
232
|
+
"""
|
|
233
|
+
data: pandas DataFrame containing the data to be plotted
|
|
234
|
+
grouping: name of the column containing the grouping variable for the swarm boxplot
|
|
235
|
+
replicate: name of the column containing the replicate variable for the swarm boxplot
|
|
236
|
+
sub_col: name of the column containing the subsetting variable for the swarm boxplot
|
|
237
|
+
sub_list: list of values to subset the data by
|
|
238
|
+
per_cat: name of the column containing the categorical variable for the swarm boxplot
|
|
239
|
+
output_dir: directory where the output plot will be saved
|
|
240
|
+
norm: boolean (default True) to normalize data by subsetting variable before plotting
|
|
241
|
+
figure_sizing: tuple (default (10,5)) containing the size of the output plot
|
|
242
|
+
save_name: name of the file to save the output plot (if output_dir is provided)
|
|
243
|
+
plot_order: list of values to specify the order of the horizontal axis
|
|
244
|
+
col_in: list of values to subset the data by the per_cat column
|
|
245
|
+
color_dic: seaborn color palette for the boxplot and swarmplot
|
|
246
|
+
flip: boolean (default False) to flip the orientation of the plot
|
|
247
|
+
"""
|
|
248
|
+
# This function creates a box plot and swarm plot from the given data
|
|
249
|
+
# and returns a plot object.
|
|
250
|
+
|
|
251
|
+
|
|
252
|
+
def pl_swarm_box(
|
|
253
|
+
data,
|
|
254
|
+
grouping,
|
|
255
|
+
per_cat,
|
|
256
|
+
replicate,
|
|
257
|
+
sub_col,
|
|
258
|
+
sub_list,
|
|
259
|
+
output_dir,
|
|
260
|
+
norm=True,
|
|
261
|
+
figure_sizing=(10, 5),
|
|
262
|
+
save_name=None,
|
|
263
|
+
plot_order=None,
|
|
264
|
+
col_in=None,
|
|
265
|
+
color_dic=None,
|
|
266
|
+
flip=False,
|
|
267
|
+
):
|
|
268
|
+
# Find Percentage of cell type
|
|
269
|
+
test = data.copy()
|
|
270
|
+
sub_list1 = sub_list.copy()
|
|
271
|
+
|
|
272
|
+
if norm == True:
|
|
273
|
+
test1 = test.loc[test[sub_col].isin(sub_list1)]
|
|
274
|
+
immune_list = list(test1[per_cat].unique())
|
|
275
|
+
else:
|
|
276
|
+
test1 = test.copy()
|
|
277
|
+
immune_list = list(test.loc[test[sub_col].isin(sub_list1)][per_cat].unique())
|
|
278
|
+
|
|
279
|
+
test1[per_cat] = test1[per_cat].astype("category")
|
|
280
|
+
test_freq = test1.groupby([grouping, replicate]).apply(
|
|
281
|
+
lambda x: x[per_cat].value_counts(normalize=True, sort=False) * 100
|
|
282
|
+
)
|
|
283
|
+
test_freq.columns = test_freq.columns.astype(str)
|
|
284
|
+
test_freq.reset_index(inplace=True)
|
|
285
|
+
immune_list.extend([grouping, replicate])
|
|
286
|
+
test_freq1 = test_freq[immune_list]
|
|
287
|
+
|
|
288
|
+
melt_per_plot = pd.melt(
|
|
289
|
+
test_freq1,
|
|
290
|
+
id_vars=[
|
|
291
|
+
grouping,
|
|
292
|
+
replicate,
|
|
293
|
+
],
|
|
294
|
+
) # ,value_vars=immune_list)
|
|
295
|
+
melt_per_plot.rename(columns={"value": "percentage"}, inplace=True)
|
|
296
|
+
|
|
297
|
+
if col_in:
|
|
298
|
+
melt_per_plot = melt_per_plot.loc[melt_per_plot[per_cat].isin(col_in)]
|
|
299
|
+
else:
|
|
300
|
+
melt_per_plot = melt_per_plot
|
|
301
|
+
|
|
302
|
+
if plot_order is None:
|
|
303
|
+
plot_order = list(melt_per_plot[grouping].unique())
|
|
304
|
+
else:
|
|
305
|
+
# Order by average
|
|
306
|
+
plot_order = (
|
|
307
|
+
melt_per_plot.groupby(per_cat)
|
|
308
|
+
.mean()
|
|
309
|
+
.reset_index()
|
|
310
|
+
.sort_values(by="percentage")[per_cat]
|
|
311
|
+
.to_list()
|
|
312
|
+
)
|
|
313
|
+
|
|
314
|
+
# swarmplot to compare clustering
|
|
315
|
+
plt.figure(figsize=figure_sizing)
|
|
316
|
+
if flip == True:
|
|
317
|
+
plt.figure(figsize=figure_sizing)
|
|
318
|
+
if color_dic is None:
|
|
319
|
+
ax = sns.boxplot(
|
|
320
|
+
data=melt_per_plot,
|
|
321
|
+
x=grouping,
|
|
322
|
+
y="percentage",
|
|
323
|
+
dodge=True,
|
|
324
|
+
order=plot_order,
|
|
325
|
+
)
|
|
326
|
+
ax = sns.swarmplot(
|
|
327
|
+
data=melt_per_plot,
|
|
328
|
+
x=grouping,
|
|
329
|
+
y="percentage",
|
|
330
|
+
dodge=True,
|
|
331
|
+
order=plot_order,
|
|
332
|
+
edgecolor="black",
|
|
333
|
+
linewidth=1,
|
|
334
|
+
color="white",
|
|
335
|
+
palette=color_dic,
|
|
336
|
+
)
|
|
337
|
+
else:
|
|
338
|
+
ax = sns.boxplot(
|
|
339
|
+
data=melt_per_plot,
|
|
340
|
+
x=grouping,
|
|
341
|
+
y="percentage",
|
|
342
|
+
dodge=True,
|
|
343
|
+
order=plot_order,
|
|
344
|
+
palette=color_dic,
|
|
345
|
+
)
|
|
346
|
+
ax = sns.swarmplot(
|
|
347
|
+
data=melt_per_plot,
|
|
348
|
+
x=grouping,
|
|
349
|
+
y="percentage",
|
|
350
|
+
dodge=True,
|
|
351
|
+
order=plot_order,
|
|
352
|
+
edgecolor="black",
|
|
353
|
+
linewidth=1,
|
|
354
|
+
palette=color_dic,
|
|
355
|
+
)
|
|
356
|
+
|
|
357
|
+
for patch in ax.artists:
|
|
358
|
+
r, g, b, a = patch.get_facecolor()
|
|
359
|
+
patch.set_facecolor((r, g, b, 0.3))
|
|
360
|
+
plt.xticks(rotation=90)
|
|
361
|
+
plt.xlabel("")
|
|
362
|
+
plt.ylabel("")
|
|
363
|
+
plt.title(sub_list[0])
|
|
364
|
+
sns.despine()
|
|
365
|
+
|
|
366
|
+
else:
|
|
367
|
+
if color_dic is None:
|
|
368
|
+
ax = sns.boxplot(
|
|
369
|
+
data=melt_per_plot,
|
|
370
|
+
x=grouping,
|
|
371
|
+
y="percentage",
|
|
372
|
+
dodge=True,
|
|
373
|
+
order=plot_order,
|
|
374
|
+
)
|
|
375
|
+
ax = sns.swarmplot(
|
|
376
|
+
data=melt_per_plot,
|
|
377
|
+
x=grouping,
|
|
378
|
+
y="percentage",
|
|
379
|
+
dodge=True,
|
|
380
|
+
order=plot_order,
|
|
381
|
+
edgecolor="black",
|
|
382
|
+
linewidth=1,
|
|
383
|
+
color="white",
|
|
384
|
+
)
|
|
385
|
+
else:
|
|
386
|
+
ax = sns.boxplot(
|
|
387
|
+
data=melt_per_plot,
|
|
388
|
+
x=grouping,
|
|
389
|
+
y="percentage",
|
|
390
|
+
dodge=True,
|
|
391
|
+
order=plot_order,
|
|
392
|
+
palette=color_dic,
|
|
393
|
+
)
|
|
394
|
+
ax = sns.swarmplot(
|
|
395
|
+
data=melt_per_plot,
|
|
396
|
+
x=grouping,
|
|
397
|
+
y="percentage",
|
|
398
|
+
dodge=True,
|
|
399
|
+
order=plot_order,
|
|
400
|
+
edgecolor="black",
|
|
401
|
+
linewidth=1,
|
|
402
|
+
palette=color_dic,
|
|
403
|
+
)
|
|
404
|
+
for patch in ax.artists:
|
|
405
|
+
r, g, b, a = patch.get_facecolor()
|
|
406
|
+
patch.set_facecolor((r, g, b, 0.3))
|
|
407
|
+
# ax.set_yscale(\log\)
|
|
408
|
+
plt.xlabel("")
|
|
409
|
+
handles, labels = ax.get_legend_handles_labels()
|
|
410
|
+
plt.legend(
|
|
411
|
+
handles[: len(melt_per_plot[grouping].unique())],
|
|
412
|
+
labels[: len(melt_per_plot[grouping].unique())],
|
|
413
|
+
bbox_to_anchor=(1.05, 1),
|
|
414
|
+
loc=2,
|
|
415
|
+
borderaxespad=0.0,
|
|
416
|
+
frameon=False,
|
|
417
|
+
)
|
|
418
|
+
plt.xticks(rotation=90)
|
|
419
|
+
|
|
420
|
+
ax.set(ylim=(0, melt_per_plot["percentage"].max() + 1))
|
|
421
|
+
sns.despine()
|
|
422
|
+
|
|
423
|
+
if output_dir:
|
|
424
|
+
if save_name:
|
|
425
|
+
plt.savefig(
|
|
426
|
+
output_dir + save_name + "_swarm_boxplot.pdf",
|
|
427
|
+
dpi=300,
|
|
428
|
+
transparent=True,
|
|
429
|
+
bbox_inches="tight",
|
|
430
|
+
)
|
|
431
|
+
else:
|
|
432
|
+
print("define save_name")
|
|
433
|
+
else:
|
|
434
|
+
print("plot was not saved - to save the plot specify an output directory")
|
|
435
|
+
return melt_per_plot
|
|
436
|
+
|
|
437
|
+
|
|
438
|
+
#############
|
|
439
|
+
|
|
440
|
+
|
|
441
|
+
def pl_Shan_div(
|
|
442
|
+
tt,
|
|
443
|
+
test_results,
|
|
444
|
+
res,
|
|
445
|
+
grouping,
|
|
446
|
+
color_dic,
|
|
447
|
+
sub_list,
|
|
448
|
+
output_dir,
|
|
449
|
+
save=False,
|
|
450
|
+
plot_order=None,
|
|
451
|
+
fig_size=1.5,
|
|
452
|
+
):
|
|
453
|
+
"""
|
|
454
|
+
Plot Shannon Diversity using boxplot and swarmplot.
|
|
455
|
+
|
|
456
|
+
Parameters
|
|
457
|
+
----------
|
|
458
|
+
tt : unused
|
|
459
|
+
Not used in the function.
|
|
460
|
+
test_results : float
|
|
461
|
+
The p-value from the statistical test.
|
|
462
|
+
res : pandas.DataFrame
|
|
463
|
+
The input data containing the results and grouping information.
|
|
464
|
+
grouping : str
|
|
465
|
+
The column name representing the grouping.
|
|
466
|
+
color_dic : dict
|
|
467
|
+
A dictionary mapping groups to colors for custom colorization.
|
|
468
|
+
sub_list : list
|
|
469
|
+
The list of sub-groups.
|
|
470
|
+
output_dir : str
|
|
471
|
+
The output directory for saving the plots.
|
|
472
|
+
save : bool, optional
|
|
473
|
+
Flag indicating whether to save the plots. Defaults to False.
|
|
474
|
+
plot_order : list, optional
|
|
475
|
+
The order of groups for plotting. Defaults to None.
|
|
476
|
+
fig_size : float, optional
|
|
477
|
+
The size of the figure. Defaults to 1.5.
|
|
478
|
+
|
|
479
|
+
Returns
|
|
480
|
+
-------
|
|
481
|
+
pandas.DataFrame or bool
|
|
482
|
+
The Tukey's test results if the p-value is less than 0.05, otherwise False.
|
|
483
|
+
"""
|
|
484
|
+
|
|
485
|
+
# Order by average
|
|
486
|
+
if color_dic is None:
|
|
487
|
+
if plot_order is None:
|
|
488
|
+
plot_order = res[grouping].unique()
|
|
489
|
+
else:
|
|
490
|
+
plot_order = plot_order
|
|
491
|
+
# Plot the swarmplot of results
|
|
492
|
+
plt.figure(figsize=(fig_size, 3))
|
|
493
|
+
|
|
494
|
+
ax = sns.boxplot(
|
|
495
|
+
data=res, x=grouping, y="Shannon Diversity", dodge=True, order=plot_order
|
|
496
|
+
)
|
|
497
|
+
|
|
498
|
+
ax = sns.swarmplot(
|
|
499
|
+
data=res,
|
|
500
|
+
x=grouping,
|
|
501
|
+
y="Shannon Diversity",
|
|
502
|
+
dodge=True,
|
|
503
|
+
order=plot_order,
|
|
504
|
+
edgecolor="black",
|
|
505
|
+
linewidth=1,
|
|
506
|
+
color="white",
|
|
507
|
+
)
|
|
508
|
+
|
|
509
|
+
else:
|
|
510
|
+
if plot_order is None:
|
|
511
|
+
plot_order = res[grouping].unique()
|
|
512
|
+
else:
|
|
513
|
+
plot_order = plot_order
|
|
514
|
+
# Plot the swarmplot of results
|
|
515
|
+
plt.figure(figsize=(fig_size, 3))
|
|
516
|
+
|
|
517
|
+
ax = sns.boxplot(
|
|
518
|
+
data=res,
|
|
519
|
+
x=grouping,
|
|
520
|
+
y="Shannon Diversity",
|
|
521
|
+
dodge=True,
|
|
522
|
+
order=plot_order,
|
|
523
|
+
palette=color_dic,
|
|
524
|
+
)
|
|
525
|
+
ax = sns.swarmplot(
|
|
526
|
+
data=res,
|
|
527
|
+
x=grouping,
|
|
528
|
+
y="Shannon Diversity",
|
|
529
|
+
dodge=True,
|
|
530
|
+
order=plot_order,
|
|
531
|
+
edgecolor="black",
|
|
532
|
+
linewidth=1,
|
|
533
|
+
palette=color_dic,
|
|
534
|
+
)
|
|
535
|
+
|
|
536
|
+
for patch in ax.artists:
|
|
537
|
+
r, g, b, a = patch.get_facecolor()
|
|
538
|
+
patch.set_facecolor((r, g, b, 0.3))
|
|
539
|
+
plt.xticks(rotation=90)
|
|
540
|
+
plt.xlabel("")
|
|
541
|
+
plt.ylabel("Shannon Diversity")
|
|
542
|
+
plt.title("")
|
|
543
|
+
sns.despine()
|
|
544
|
+
if save == True:
|
|
545
|
+
plt.savefig(
|
|
546
|
+
output_dir + sub_list[0] + "_Shannon.pdf",
|
|
547
|
+
dpi=300,
|
|
548
|
+
transparent=True,
|
|
549
|
+
bbox_inches="tight",
|
|
550
|
+
)
|
|
551
|
+
|
|
552
|
+
plt.show()
|
|
553
|
+
if test_results < 0.05:
|
|
554
|
+
plt.figure(figsize=(fig_size, fig_size))
|
|
555
|
+
tukey = pairwise_tukeyhsd(
|
|
556
|
+
endog=res["Shannon Diversity"], groups=res[grouping], alpha=0.05
|
|
557
|
+
)
|
|
558
|
+
tukeydf = pd.DataFrame(
|
|
559
|
+
data=tukey._results_table.data[1:], columns=tukey._results_table.data[0]
|
|
560
|
+
)
|
|
561
|
+
tukedf_rev = tukeydf.copy()
|
|
562
|
+
tukedf_rev.rename(
|
|
563
|
+
columns={"group1": "groupa", "group2": "groupb"}, inplace=True
|
|
564
|
+
)
|
|
565
|
+
tukedf_rev.rename(
|
|
566
|
+
columns={"groupa": "group2", "groupb": "group1"}, inplace=True
|
|
567
|
+
)
|
|
568
|
+
tukedf_rev = tukedf_rev[tukeydf.columns]
|
|
569
|
+
tukey_all = pd.concat([tukedf_rev, tukeydf])
|
|
570
|
+
|
|
571
|
+
# Plot with tissue order preserved
|
|
572
|
+
table1 = pd.pivot_table(
|
|
573
|
+
tukey_all, values="p-adj", index=["group1"], columns=["group2"]
|
|
574
|
+
)
|
|
575
|
+
table1 = table1[plot_order]
|
|
576
|
+
table1 = table1.reindex(plot_order)
|
|
577
|
+
|
|
578
|
+
plt.figure(figsize=(5, 5))
|
|
579
|
+
ax = sns.heatmap(table1, cmap="coolwarm", center=0.05, vmax=0.05)
|
|
580
|
+
ax.set_title("Shannon Diversity")
|
|
581
|
+
ax.set_ylabel("")
|
|
582
|
+
ax.set_xlabel("")
|
|
583
|
+
if save == True:
|
|
584
|
+
plt.savefig(
|
|
585
|
+
output_dir + sub_list[0] + "_tukey.png",
|
|
586
|
+
format="png",
|
|
587
|
+
dpi=300,
|
|
588
|
+
transparent=True,
|
|
589
|
+
bbox_inches="tight",
|
|
590
|
+
)
|
|
591
|
+
plt.show()
|
|
592
|
+
else:
|
|
593
|
+
table1 = False
|
|
594
|
+
|
|
595
|
+
|
|
596
|
+
#############
|
|
597
|
+
|
|
598
|
+
|
|
599
|
+
def pl_cell_type_composition_vis(
|
|
600
|
+
data,
|
|
601
|
+
sample_column="sample",
|
|
602
|
+
cell_type_column="Cell Type",
|
|
603
|
+
figsize=(10, 10),
|
|
604
|
+
output_dir=None,
|
|
605
|
+
):
|
|
606
|
+
"""
|
|
607
|
+
Visualize cell type composition using stacked and unstacked bar plots.
|
|
608
|
+
|
|
609
|
+
Parameters
|
|
610
|
+
----------
|
|
611
|
+
data : pandas.DataFrame
|
|
612
|
+
The input data containing the sample and cell type information.
|
|
613
|
+
sample_column : str, optional
|
|
614
|
+
The column name representing the sample. Defaults to "sample".
|
|
615
|
+
cell_type_column : str, optional
|
|
616
|
+
The column name representing the cell type. Defaults to "Cell Type".
|
|
617
|
+
figsize : tuple, optional
|
|
618
|
+
The size of the figure (width, height) in inches. Defaults to (10, 10).
|
|
619
|
+
output_dir : str, optional
|
|
620
|
+
The output directory for saving the plots. Defaults to None.
|
|
621
|
+
|
|
622
|
+
Returns
|
|
623
|
+
-------
|
|
624
|
+
None
|
|
625
|
+
"""
|
|
626
|
+
|
|
627
|
+
if output_dir == None:
|
|
628
|
+
print("You have defined no output directory!")
|
|
629
|
+
|
|
630
|
+
# plotting option1
|
|
631
|
+
# pd.crosstab(df['sample'], df['final_cell_types']).plot(kind='barh', stacked=True,figsize = (10,12))
|
|
632
|
+
# plt.legend(loc='center left', bbox_to_anchor=(1.0, 0.5))
|
|
633
|
+
# plt.show()
|
|
634
|
+
|
|
635
|
+
# plotting option2
|
|
636
|
+
ax = pd.crosstab(data[sample_column], data[cell_type_column]).plot(
|
|
637
|
+
kind="barh", stacked=True, figsize=figsize
|
|
638
|
+
)
|
|
639
|
+
ax.legend(loc="center left", bbox_to_anchor=(1.0, 0.5))
|
|
640
|
+
fig = ax.get_figure()
|
|
641
|
+
ax.set(xlabel="count")
|
|
642
|
+
plt.savefig(output_dir + "/cell_types_composition_hstack.png", bbox_inches="tight")
|
|
643
|
+
|
|
644
|
+
# plotting option1
|
|
645
|
+
# pd.crosstab(df['sample'], df['final_cell_types']).plot(kind='barh', figsize = (10,10))
|
|
646
|
+
# plt.legend(loc='center left', bbox_to_anchor=(1.0, 0.5))
|
|
647
|
+
# plt.show()
|
|
648
|
+
|
|
649
|
+
# plotting option2
|
|
650
|
+
ax = pd.crosstab(data[sample_column], data[cell_type_column]).plot(
|
|
651
|
+
kind="barh", stacked=False, figsize=figsize
|
|
652
|
+
)
|
|
653
|
+
ax.legend(loc="center left", bbox_to_anchor=(1.0, 0.5))
|
|
654
|
+
fig = ax.get_figure()
|
|
655
|
+
ax.set(xlabel="count")
|
|
656
|
+
plt.savefig(
|
|
657
|
+
output_dir + "/cell_types_composition_hUNstack.png", bbox_inches="tight"
|
|
658
|
+
)
|
|
659
|
+
|
|
660
|
+
# Cell type percentage
|
|
661
|
+
st = pd.crosstab(data[sample_column], data[cell_type_column])
|
|
662
|
+
df_perc = (st / np.sum(st, axis=1)[:, None]) * 100
|
|
663
|
+
df_perc
|
|
664
|
+
# df_perc['sample'] = df_perc.index
|
|
665
|
+
# df_perc
|
|
666
|
+
|
|
667
|
+
tmp = st.T.apply(lambda x: 100 * x / x.sum())
|
|
668
|
+
|
|
669
|
+
ax = tmp.T.plot(kind="barh", stacked=True, figsize=figsize)
|
|
670
|
+
ax.legend(loc="center left", bbox_to_anchor=(1.0, 0.5))
|
|
671
|
+
fig = ax.get_figure()
|
|
672
|
+
ax.set(xlabel="percentage")
|
|
673
|
+
plt.savefig(
|
|
674
|
+
output_dir + "/cell_types_composition_perc_hstack.png", bbox_inches="tight"
|
|
675
|
+
)
|
|
676
|
+
|
|
677
|
+
|
|
678
|
+
##############
|
|
679
|
+
|
|
680
|
+
|
|
681
|
+
def pl_regions_per_sample(data, sample_col, region_col, bar_color="grey"):
|
|
682
|
+
# Group the dataframe by the specified sample column and count the unique regions
|
|
683
|
+
region_counts = data.groupby(sample_col)[region_col].nunique()
|
|
684
|
+
|
|
685
|
+
# Create a bar chart with the specified color
|
|
686
|
+
plt.bar(region_counts.index, region_counts.values, color=bar_color)
|
|
687
|
+
|
|
688
|
+
# Set chart title and axis labels
|
|
689
|
+
plt.title("Count of Unique Regions per Sample")
|
|
690
|
+
plt.xlabel("Samples")
|
|
691
|
+
plt.ylabel("Unique Regions")
|
|
692
|
+
|
|
693
|
+
# Rotate x-axis labels if needed
|
|
694
|
+
plt.xticks(rotation=45)
|
|
695
|
+
|
|
696
|
+
# Display the chart
|
|
697
|
+
plt.show()
|
|
698
|
+
|
|
699
|
+
|
|
700
|
+
##############
|
|
701
|
+
|
|
702
|
+
|
|
703
|
+
def pl_neighborhood_analysis_2(
|
|
704
|
+
data,
|
|
705
|
+
k_centroids,
|
|
706
|
+
values,
|
|
707
|
+
sum_cols,
|
|
708
|
+
X="x",
|
|
709
|
+
Y="y",
|
|
710
|
+
reg="unique_region",
|
|
711
|
+
output_dir=None,
|
|
712
|
+
k=35,
|
|
713
|
+
plot_specific_neighborhoods=None,
|
|
714
|
+
size=3,
|
|
715
|
+
axis="on",
|
|
716
|
+
ticks_fontsize=15,
|
|
717
|
+
show_spatial_plots=True,
|
|
718
|
+
palette="tab20",
|
|
719
|
+
):
|
|
720
|
+
"""
|
|
721
|
+
Perform neighborhood analysis and visualize results.
|
|
722
|
+
|
|
723
|
+
Parameters
|
|
724
|
+
----------
|
|
725
|
+
data : pandas.DataFrame
|
|
726
|
+
The input data containing the neighborhood information.
|
|
727
|
+
k_centroids : numpy.ndarray
|
|
728
|
+
The centroids of the neighborhoods.
|
|
729
|
+
values : numpy.ndarray
|
|
730
|
+
The values associated with each cell.
|
|
731
|
+
sum_cols : list
|
|
732
|
+
The column names to sum.
|
|
733
|
+
X : str, optional
|
|
734
|
+
The column name representing the x-coordinate. Defaults to 'x'.
|
|
735
|
+
Y : str, optional
|
|
736
|
+
The column name representing the y-coordinate. Defaults to 'y'.
|
|
737
|
+
reg : str, optional
|
|
738
|
+
The column name representing the region. Defaults to 'unique_region'.
|
|
739
|
+
output_dir : str, optional
|
|
740
|
+
The output directory for saving the plots. Defaults to None.
|
|
741
|
+
k : int, optional
|
|
742
|
+
The number of neighborhoods. Defaults to 35.
|
|
743
|
+
plot_specific_neighborhoods : bool or int, optional
|
|
744
|
+
Flag indicating whether to plot specific neighborhoods or not. If True, all neighborhoods will be plotted.
|
|
745
|
+
If an integer, only the specified neighborhood will be plotted. Defaults to None.
|
|
746
|
+
|
|
747
|
+
Returns
|
|
748
|
+
-------
|
|
749
|
+
None
|
|
750
|
+
"""
|
|
751
|
+
|
|
752
|
+
if show_spatial_plots == True:
|
|
753
|
+
# modify figure size aesthetics for each neighborhood
|
|
754
|
+
figs = pl_catplot(
|
|
755
|
+
data,
|
|
756
|
+
X=X,
|
|
757
|
+
Y=Y,
|
|
758
|
+
exp=reg,
|
|
759
|
+
hue="neighborhood" + str(k),
|
|
760
|
+
invert_y=True,
|
|
761
|
+
size=size,
|
|
762
|
+
axis=axis,
|
|
763
|
+
ticks_fontsize=ticks_fontsize,
|
|
764
|
+
palette=palette,
|
|
765
|
+
)
|
|
766
|
+
|
|
767
|
+
# Save Plots for Publication
|
|
768
|
+
for n, f in enumerate(figs):
|
|
769
|
+
f.savefig(output_dir + "neighborhood_" + str(k) + "_id{}.png".format(n))
|
|
770
|
+
|
|
771
|
+
# this plot shows the types of cells (ClusterIDs) in the different niches (0-9)
|
|
772
|
+
k_to_plot = k
|
|
773
|
+
niche_clusters = k_centroids[k_to_plot]
|
|
774
|
+
tissue_avgs = values.mean(axis=0)
|
|
775
|
+
fc = np.log2(
|
|
776
|
+
(
|
|
777
|
+
(niche_clusters + tissue_avgs)
|
|
778
|
+
/ (niche_clusters + tissue_avgs).sum(axis=1, keepdims=True)
|
|
779
|
+
)
|
|
780
|
+
/ tissue_avgs
|
|
781
|
+
)
|
|
782
|
+
fc = pd.DataFrame(fc, columns=sum_cols)
|
|
783
|
+
s = sns.clustermap(
|
|
784
|
+
fc, vmin=-3, vmax=3, cmap="bwr", row_colors=sns.color_palette(palette, len(fc))
|
|
785
|
+
)
|
|
786
|
+
s.savefig(output_dir + "celltypes_perniche_" + "_" + str(k) + ".png", dpi=600)
|
|
787
|
+
|
|
788
|
+
if plot_specific_neighborhoods is True:
|
|
789
|
+
# this plot shows the types of cells (ClusterIDs) in the different niches (0-9)
|
|
790
|
+
k_to_plot = k
|
|
791
|
+
niche_clusters = k_centroids[k_to_plot]
|
|
792
|
+
tissue_avgs = values.mean(axis=0)
|
|
793
|
+
fc = np.log2(
|
|
794
|
+
(
|
|
795
|
+
(niche_clusters + tissue_avgs)
|
|
796
|
+
/ (niche_clusters + tissue_avgs).sum(axis=1, keepdims=True)
|
|
797
|
+
)
|
|
798
|
+
/ tissue_avgs
|
|
799
|
+
)
|
|
800
|
+
fc = pd.DataFrame(fc, columns=sum_cols)
|
|
801
|
+
s = sns.clustermap(
|
|
802
|
+
fc.iloc[plot_specific_neighborhoods, :], vmin=-3, vmax=3, cmap="bwr"
|
|
803
|
+
)
|
|
804
|
+
s.savefig(output_dir + "celltypes_perniche_" + "_" + str(k) + ".png", dpi=600)
|
|
805
|
+
|
|
806
|
+
|
|
807
|
+
##############
|
|
808
|
+
|
|
809
|
+
|
|
810
|
+
def pl_highlighted_dot(
|
|
811
|
+
df,
|
|
812
|
+
x_col,
|
|
813
|
+
y_col,
|
|
814
|
+
group_col,
|
|
815
|
+
highlight_group,
|
|
816
|
+
highlight_color="red",
|
|
817
|
+
region_col="unique_region",
|
|
818
|
+
subset_col=None,
|
|
819
|
+
subset_list=None,
|
|
820
|
+
):
|
|
821
|
+
"""
|
|
822
|
+
Plots an XY dot plot colored by a grouping column for each unique region.
|
|
823
|
+
|
|
824
|
+
Parameters
|
|
825
|
+
----------
|
|
826
|
+
df : pandas.DataFrame
|
|
827
|
+
Input DataFrame.
|
|
828
|
+
x_col : str
|
|
829
|
+
Name of the column to be plotted on the x-axis.
|
|
830
|
+
y_col : str
|
|
831
|
+
Name of the column to be plotted on the y-axis.
|
|
832
|
+
group_col : str
|
|
833
|
+
Name of the column used for grouping and coloring the dots.
|
|
834
|
+
highlight_group : object
|
|
835
|
+
Value of the group to be highlighted.
|
|
836
|
+
highlight_color : str, optional
|
|
837
|
+
Color of the dots for the highlighted group (default: "red").
|
|
838
|
+
region_col : str, optional
|
|
839
|
+
Name of the column with information about the unique regions (default: "unique_region").
|
|
840
|
+
subset_col : str, optional
|
|
841
|
+
Name of the column to subset the data (default: None).
|
|
842
|
+
subset_list : list, optional
|
|
843
|
+
List of values to subset the data from the subset column (default: None).
|
|
844
|
+
|
|
845
|
+
Returns
|
|
846
|
+
-------
|
|
847
|
+
None
|
|
848
|
+
"""
|
|
849
|
+
|
|
850
|
+
# Create a colormap dictionary for coloring dots
|
|
851
|
+
colormap = {highlight_group: highlight_color, "default": "grey"}
|
|
852
|
+
|
|
853
|
+
# Subset the data based on the subset column and list
|
|
854
|
+
if subset_col and subset_list:
|
|
855
|
+
df = df[df[subset_col].isin(subset_list)]
|
|
856
|
+
|
|
857
|
+
unique_regions = df[region_col].unique()
|
|
858
|
+
|
|
859
|
+
# Determine the number of plots and the grid layout
|
|
860
|
+
num_plots = len(unique_regions)
|
|
861
|
+
|
|
862
|
+
if len(unique_regions) > 3:
|
|
863
|
+
num_cols = len(unique_regions) // 2 # Number of columns in the grid
|
|
864
|
+
else:
|
|
865
|
+
num_cols = 2
|
|
866
|
+
|
|
867
|
+
num_rows = (num_plots - 1) // num_cols + 1 # Number of rows in the grid
|
|
868
|
+
|
|
869
|
+
# Create the figure and subplots
|
|
870
|
+
fig, axs = plt.subplots(num_rows, num_cols, figsize=(15, 5 * num_rows))
|
|
871
|
+
|
|
872
|
+
# Iterate over unique regions and corresponding subplots
|
|
873
|
+
for region, ax in zip(unique_regions, axs.flatten()):
|
|
874
|
+
# Filter the dataframe for the current region
|
|
875
|
+
region_df = df[df[region_col] == region]
|
|
876
|
+
|
|
877
|
+
# Iterate over unique groups in the current region
|
|
878
|
+
for group in region_df[group_col].unique():
|
|
879
|
+
# Get x and y values for the group
|
|
880
|
+
x = region_df.loc[region_df[group_col] == group, x_col]
|
|
881
|
+
y = region_df.loc[region_df[group_col] == group, y_col]
|
|
882
|
+
|
|
883
|
+
# Get the color for the group
|
|
884
|
+
color = colormap.get(group, colormap["default"])
|
|
885
|
+
|
|
886
|
+
# Set the alpha value for red dots
|
|
887
|
+
alpha = 0.7 if group == highlight_group else 1.0
|
|
888
|
+
|
|
889
|
+
# Plot the dots
|
|
890
|
+
ax.scatter(x, y, color=color, label=group, alpha=alpha, zorder=2, s=1)
|
|
891
|
+
|
|
892
|
+
# Remove legend
|
|
893
|
+
ax.legend().remove()
|
|
894
|
+
|
|
895
|
+
# Set axis labels
|
|
896
|
+
ax.set_xlabel(x_col)
|
|
897
|
+
ax.set_ylabel(y_col)
|
|
898
|
+
|
|
899
|
+
# Set the title to the current region
|
|
900
|
+
ax.set_title(f"Region: {region}")
|
|
901
|
+
|
|
902
|
+
# Show the plot
|
|
903
|
+
plt.tight_layout()
|
|
904
|
+
plt.show()
|
|
905
|
+
|
|
906
|
+
|
|
907
|
+
##############
|
|
908
|
+
|
|
909
|
+
|
|
910
|
+
def pl_create_pie_charts(
|
|
911
|
+
data,
|
|
912
|
+
group_column,
|
|
913
|
+
count_column,
|
|
914
|
+
plot_order=None,
|
|
915
|
+
show_percentages=True,
|
|
916
|
+
color_dict=None,
|
|
917
|
+
):
|
|
918
|
+
"""
|
|
919
|
+
Create pie charts for each group based on a grouping column, showing the percentage of total rows based on a
|
|
920
|
+
count column.
|
|
921
|
+
|
|
922
|
+
Parameters:
|
|
923
|
+
data (pd.DataFrame): The input DataFrame.
|
|
924
|
+
group_column (str): The column name for grouping the data.
|
|
925
|
+
count_column (str): The column name used for counting occurrences.
|
|
926
|
+
plot_order (list, optional): The order of groups for plotting. Defaults to None.
|
|
927
|
+
show_percentages (bool, optional): Whether to show the percentage numbers on the pie charts. Defaults to True.
|
|
928
|
+
color_dict (dict, optional): A dictionary to manually set colors for neighborhoods. Defaults to None.
|
|
929
|
+
|
|
930
|
+
Returns:
|
|
931
|
+
None
|
|
932
|
+
"""
|
|
933
|
+
# Group the data by the grouping column
|
|
934
|
+
grouped_data = data.groupby(group_column)
|
|
935
|
+
|
|
936
|
+
# Sort the groups based on the plot_order if provided
|
|
937
|
+
if plot_order:
|
|
938
|
+
grouped_data = sorted(grouped_data, key=lambda x: plot_order.index(x[0]))
|
|
939
|
+
|
|
940
|
+
# Calculate the number of rows and columns for subplots
|
|
941
|
+
num_groups = len(grouped_data)
|
|
942
|
+
num_cols = 3 # Number of columns for subplots
|
|
943
|
+
num_rows = (num_groups - 1) // num_cols + 1
|
|
944
|
+
|
|
945
|
+
# Create subplots
|
|
946
|
+
fig, axes = plt.subplots(num_rows, num_cols, figsize=(15, 5 * num_rows))
|
|
947
|
+
axes = axes.flatten() # Flatten the subplots array
|
|
948
|
+
|
|
949
|
+
# Create a color dictionary if not provided
|
|
950
|
+
if color_dict is None:
|
|
951
|
+
color_dict = {}
|
|
952
|
+
|
|
953
|
+
# Generate a color dictionary for consistent colors if not provided
|
|
954
|
+
if not color_dict:
|
|
955
|
+
neighborhoods = data[count_column].unique()
|
|
956
|
+
color_cycle = plt.cm.tab20.colors
|
|
957
|
+
color_dict = {
|
|
958
|
+
neighborhood: color_cycle[i % 20]
|
|
959
|
+
for i, neighborhood in enumerate(neighborhoods)
|
|
960
|
+
}
|
|
961
|
+
|
|
962
|
+
# Iterate over each group and create a pie chart
|
|
963
|
+
for i, (group, group_df) in enumerate(grouped_data):
|
|
964
|
+
# Count the occurrences of each neighborhood within the group
|
|
965
|
+
neighborhood_counts = group_df[count_column].value_counts()
|
|
966
|
+
|
|
967
|
+
# Calculate the percentage of total rows for each neighborhood
|
|
968
|
+
percentages = neighborhood_counts / group_df.shape[0] * 100
|
|
969
|
+
|
|
970
|
+
# Create a color list for neighborhoods in the count column
|
|
971
|
+
colors = [
|
|
972
|
+
color_dict.get(neighborhood, "gray") for neighborhood in percentages.index
|
|
973
|
+
]
|
|
974
|
+
|
|
975
|
+
if show_percentages:
|
|
976
|
+
wedges, texts, autotexts = axes[i].pie(
|
|
977
|
+
percentages, labels=percentages.index, autopct="%1.1f%%", colors=colors
|
|
978
|
+
)
|
|
979
|
+
axes[i].set_title(f"Group: {group}")
|
|
980
|
+
else:
|
|
981
|
+
wedges, texts = axes[i].pie(
|
|
982
|
+
percentages, labels=percentages.index, colors=colors
|
|
983
|
+
)
|
|
984
|
+
axes[i].set_title(f"Group: {group}")
|
|
985
|
+
|
|
986
|
+
# Remove unused subplots
|
|
987
|
+
for j in range(num_groups, num_rows * num_cols):
|
|
988
|
+
fig.delaxes(axes[j])
|
|
989
|
+
|
|
990
|
+
# Adjust spacing between subplots
|
|
991
|
+
fig.tight_layout()
|
|
992
|
+
|
|
993
|
+
# Show the plot
|
|
994
|
+
plt.show()
|
|
995
|
+
|
|
996
|
+
|
|
997
|
+
##############
|
|
998
|
+
|
|
999
|
+
|
|
1000
|
+
def pl_cell_types_de(data, pvals, neigh_num, output_dir, figsize=(20, 10)):
|
|
1001
|
+
"""
|
|
1002
|
+
Plot cell types differential expression as a heatmap.
|
|
1003
|
+
|
|
1004
|
+
Parameters
|
|
1005
|
+
----------
|
|
1006
|
+
data : pandas.DataFrame
|
|
1007
|
+
The input data containing the differential expression values.
|
|
1008
|
+
pvals : numpy.ndarray
|
|
1009
|
+
The p-values associated with the differential expression values.
|
|
1010
|
+
neigh_num : dict
|
|
1011
|
+
A dictionary mapping neighborhood numbers to labels.
|
|
1012
|
+
output_dir : str
|
|
1013
|
+
The output directory for saving the plot.
|
|
1014
|
+
figsize : tuple, optional
|
|
1015
|
+
The size of the figure (width, height) in inches. Defaults to (20, 10).
|
|
1016
|
+
|
|
1017
|
+
Returns
|
|
1018
|
+
-------
|
|
1019
|
+
None
|
|
1020
|
+
"""
|
|
1021
|
+
|
|
1022
|
+
# plot as heatmap
|
|
1023
|
+
f, ax = plt.subplots(figsize=figsize)
|
|
1024
|
+
g = sns.heatmap(data, cmap="bwr", vmin=-1, vmax=1, cbar=False, ax=ax)
|
|
1025
|
+
for a, b in zip(*np.where(pvals < 0.05)):
|
|
1026
|
+
plt.text(b + 0.5, a + 0.55, "*", fontsize=20, ha="center", va="center")
|
|
1027
|
+
plt.tight_layout()
|
|
1028
|
+
|
|
1029
|
+
inv_map = {v: k for k, v in neigh_num.items()}
|
|
1030
|
+
inv_map
|
|
1031
|
+
|
|
1032
|
+
# plot as heatmap
|
|
1033
|
+
plt.style.use(["default"])
|
|
1034
|
+
# GENERAL GRAPH SETTINGs
|
|
1035
|
+
# font size of graph
|
|
1036
|
+
SMALL_SIZE = 14
|
|
1037
|
+
MEDIUM_SIZE = 16
|
|
1038
|
+
BIGGER_SIZE = 18
|
|
1039
|
+
|
|
1040
|
+
# Settings for graph
|
|
1041
|
+
plt.rc("font", size=SMALL_SIZE) # controls default text sizes
|
|
1042
|
+
plt.rc("axes", titlesize=SMALL_SIZE) # fontsize of the axes title
|
|
1043
|
+
plt.rc("axes", labelsize=MEDIUM_SIZE) # fontsize of the x and y labels
|
|
1044
|
+
plt.rc("xtick", labelsize=SMALL_SIZE) # fontsize of the tick labels
|
|
1045
|
+
plt.rc("ytick", labelsize=SMALL_SIZE) # fontsize of the tick labels
|
|
1046
|
+
plt.rc("legend", fontsize=SMALL_SIZE) # legend fontsize
|
|
1047
|
+
plt.rc("figure", titlesize=BIGGER_SIZE) # fontsize of the figure title
|
|
1048
|
+
|
|
1049
|
+
data_2 = data.rename(index=inv_map)
|
|
1050
|
+
|
|
1051
|
+
# Sort both axes
|
|
1052
|
+
sort_sum = data_2.abs().sum(axis=1).to_frame()
|
|
1053
|
+
sort_sum.columns = ["sum_col"]
|
|
1054
|
+
xx = sort_sum.sort_values(by="sum_col")
|
|
1055
|
+
sort_x = xx.index.values.tolist()
|
|
1056
|
+
sort_sum_y = data_2.abs().sum(axis=0).to_frame()
|
|
1057
|
+
sort_sum_y.columns = ["sum_col"]
|
|
1058
|
+
yy = sort_sum_y.sort_values(by="sum_col")
|
|
1059
|
+
sort_y = yy.index.values.tolist()
|
|
1060
|
+
df_sort = data_2.reindex(index=sort_x, columns=sort_y)
|
|
1061
|
+
|
|
1062
|
+
f, ax = plt.subplots(figsize=figsize)
|
|
1063
|
+
g = sns.heatmap(df_sort, cmap="bwr", vmin=-1, vmax=1, cbar=True, ax=ax)
|
|
1064
|
+
for a, b in zip(*np.where(pvals < 0.05)):
|
|
1065
|
+
plt.text(b + 0.5, a + 0.55, "*", fontsize=20, ha="center", va="center")
|
|
1066
|
+
plt.tight_layout()
|
|
1067
|
+
|
|
1068
|
+
f.savefig(
|
|
1069
|
+
output_dir + "tissue_neighborhood_coeff_pvalue_bar.png",
|
|
1070
|
+
format="png",
|
|
1071
|
+
dpi=300,
|
|
1072
|
+
transparent=True,
|
|
1073
|
+
bbox_inches="tight",
|
|
1074
|
+
)
|
|
1075
|
+
|
|
1076
|
+
df_sort.abs().sum()
|
|
1077
|
+
|
|
1078
|
+
|
|
1079
|
+
##############
|
|
1080
|
+
|
|
1081
|
+
|
|
1082
|
+
def pl_community_analysis_2(
|
|
1083
|
+
data,
|
|
1084
|
+
values,
|
|
1085
|
+
sum_cols,
|
|
1086
|
+
output_dir,
|
|
1087
|
+
# neighborhood_name,
|
|
1088
|
+
k_centroids,
|
|
1089
|
+
X="x",
|
|
1090
|
+
Y="y",
|
|
1091
|
+
reg="unique_region",
|
|
1092
|
+
save_path=None,
|
|
1093
|
+
k=100,
|
|
1094
|
+
size=3,
|
|
1095
|
+
axis="on",
|
|
1096
|
+
ticks_fontsize=15,
|
|
1097
|
+
plot_specific_community=None,
|
|
1098
|
+
show_spatial_plots=True,
|
|
1099
|
+
palette="tab20",
|
|
1100
|
+
):
|
|
1101
|
+
"""
|
|
1102
|
+
Plot community analysis.
|
|
1103
|
+
|
|
1104
|
+
Parameters
|
|
1105
|
+
----------
|
|
1106
|
+
data : pandas.DataFrame
|
|
1107
|
+
The input data containing the community information.
|
|
1108
|
+
output_dir : str
|
|
1109
|
+
The output directory for saving the plots.
|
|
1110
|
+
neighborhood_name : str
|
|
1111
|
+
The name of the neighborhood.
|
|
1112
|
+
figsize : tuple, optional
|
|
1113
|
+
The size of the figure. Defaults to (10, 10).
|
|
1114
|
+
plot_specific_community : bool, optional
|
|
1115
|
+
Whether to plot a specific community. Defaults to None.
|
|
1116
|
+
|
|
1117
|
+
Returns
|
|
1118
|
+
-------
|
|
1119
|
+
None
|
|
1120
|
+
"""
|
|
1121
|
+
|
|
1122
|
+
output_dir2 = output_dir + "community_analysis/"
|
|
1123
|
+
if not os.path.exists(output_dir2):
|
|
1124
|
+
os.makedirs(output_dir2)
|
|
1125
|
+
|
|
1126
|
+
# cells = data.copy()
|
|
1127
|
+
|
|
1128
|
+
# #modify figure size aesthetics for each neighborhood
|
|
1129
|
+
# plt.rcParams["legend.markerscale"] = 10
|
|
1130
|
+
# figs = pl_catplot(cells,X = X,Y=Y,exp = reg,
|
|
1131
|
+
# hue = neighborhood_name,invert_y=True,size = size,figsize=8, axis=axis, ticks_fontsize=ticks_fontsize)
|
|
1132
|
+
|
|
1133
|
+
# #Save Plots for Publication
|
|
1134
|
+
# for n,f in enumerate(figs):
|
|
1135
|
+
# f.savefig(output_dir2+neighborhood_name+'_id{}.png'.format(n))
|
|
1136
|
+
|
|
1137
|
+
# if plot_specific_community is True:
|
|
1138
|
+
# #this plot shows the types of cells (ClusterIDs) in the different niches (0-9)
|
|
1139
|
+
# k_to_plot = k
|
|
1140
|
+
# niche_clusters = (k_centroids[k_to_plot])
|
|
1141
|
+
# tissue_avgs = values.mean(axis = 0)
|
|
1142
|
+
# fc = np.log2(((niche_clusters+tissue_avgs)/(niche_clusters+tissue_avgs).sum(axis = 1, keepdims = True))/tissue_avgs)
|
|
1143
|
+
# fc = pd.DataFrame(fc,columns = sum_cols)
|
|
1144
|
+
# s=sns.clustermap(fc.iloc[plot_specific_community,:], vmin =-3,vmax = 3,cmap = 'bwr',figsize=(10,5))
|
|
1145
|
+
# s.savefig(output_dir2+"celltypes_perniche_"+"_"+str(k)+".png", dpi=600)
|
|
1146
|
+
|
|
1147
|
+
# #this plot shows the types of cells (ClusterIDs) in the different niches (0-9)
|
|
1148
|
+
# k_to_plot = k
|
|
1149
|
+
# niche_clusters = (k_centroids[k_to_plot])
|
|
1150
|
+
# tissue_avgs = values.mean(axis = 0)
|
|
1151
|
+
# fc = np.log2(((niche_clusters+tissue_avgs)/(niche_clusters+tissue_avgs).sum(axis = 1, keepdims = True))/tissue_avgs)
|
|
1152
|
+
# fc = pd.DataFrame(fc,columns = sum_cols)
|
|
1153
|
+
# s=sns.clustermap(fc, vmin =-3,vmax = 3,cmap = 'bwr', figsize=(10,10))
|
|
1154
|
+
# s.savefig(output_dir2+"celltypes_perniche_"+"_"+str(k)+".png", dpi=600)
|
|
1155
|
+
|
|
1156
|
+
if show_spatial_plots == True:
|
|
1157
|
+
# modify figure size aesthetics for each neighborhood
|
|
1158
|
+
figs = pl_catplot(
|
|
1159
|
+
data,
|
|
1160
|
+
X=X,
|
|
1161
|
+
Y=Y,
|
|
1162
|
+
exp=reg,
|
|
1163
|
+
hue="community" + str(k),
|
|
1164
|
+
invert_y=True,
|
|
1165
|
+
size=size,
|
|
1166
|
+
axis=axis,
|
|
1167
|
+
ticks_fontsize=ticks_fontsize,
|
|
1168
|
+
palette=palette,
|
|
1169
|
+
)
|
|
1170
|
+
|
|
1171
|
+
# Save Plots for Publication
|
|
1172
|
+
for n, f in enumerate(figs):
|
|
1173
|
+
f.savefig(output_dir + "community_" + str(k) + "_id{}.png".format(n))
|
|
1174
|
+
|
|
1175
|
+
# this plot shows the types of cells (ClusterIDs) in the different niches (0-9)
|
|
1176
|
+
k_to_plot = k
|
|
1177
|
+
niche_clusters = k_centroids[k_to_plot]
|
|
1178
|
+
tissue_avgs = values.mean(axis=0)
|
|
1179
|
+
fc = np.log2(
|
|
1180
|
+
(
|
|
1181
|
+
(niche_clusters + tissue_avgs)
|
|
1182
|
+
/ (niche_clusters + tissue_avgs).sum(axis=1, keepdims=True)
|
|
1183
|
+
)
|
|
1184
|
+
/ tissue_avgs
|
|
1185
|
+
)
|
|
1186
|
+
fc = pd.DataFrame(fc, columns=sum_cols)
|
|
1187
|
+
s = sns.clustermap(
|
|
1188
|
+
fc, vmin=-3, vmax=3, cmap="bwr", row_colors=sns.color_palette(palette, len(fc))
|
|
1189
|
+
)
|
|
1190
|
+
s.savefig(output_dir + "celltypes_perniche_" + "_" + str(k) + ".png", dpi=600)
|
|
1191
|
+
|
|
1192
|
+
if plot_specific_community is True:
|
|
1193
|
+
# this plot shows the types of cells (ClusterIDs) in the different niches (0-9)
|
|
1194
|
+
k_to_plot = k
|
|
1195
|
+
niche_clusters = k_centroids[k_to_plot]
|
|
1196
|
+
tissue_avgs = values.mean(axis=0)
|
|
1197
|
+
fc = np.log2(
|
|
1198
|
+
(
|
|
1199
|
+
(niche_clusters + tissue_avgs)
|
|
1200
|
+
/ (niche_clusters + tissue_avgs).sum(axis=1, keepdims=True)
|
|
1201
|
+
)
|
|
1202
|
+
/ tissue_avgs
|
|
1203
|
+
)
|
|
1204
|
+
fc = pd.DataFrame(fc, columns=sum_cols)
|
|
1205
|
+
s = sns.clustermap(
|
|
1206
|
+
fc.iloc[plot_specific_neighborhoods, :], vmin=-3, vmax=3, cmap="bwr"
|
|
1207
|
+
)
|
|
1208
|
+
s.savefig(output_dir + "celltypes_perniche_" + "_" + str(k) + ".png", dpi=600)
|
|
1209
|
+
|
|
1210
|
+
|
|
1211
|
+
###############
|
|
1212
|
+
"""
|
|
1213
|
+
This function visualizes the results of Canonical Correlation Analysis (CCA) using a graph.
|
|
1214
|
+
The function takes in several parameters including the CCA results, the save path for the resulting plot, whether or not to save the plot, a p-value threshold, a name for the plot file, and a color palette to use for the nodes.
|
|
1215
|
+
|
|
1216
|
+
The function first creates an empty Petersen graph and then iterates over each pair of cell types in the CCA results.
|
|
1217
|
+
For each pair, it calculates the observed correlation and the correlation for a set of permuted samples.
|
|
1218
|
+
If the p-value for the observed correlation is less than the specified threshold, it adds an edge to the graph between the two cell types, weighted by the p-value.
|
|
1219
|
+
|
|
1220
|
+
The function then uses the graphviz_layout function to position the nodes in the graph and assigns a color to each node based on the specified color palette.
|
|
1221
|
+
It then iterates over each edge in the graph and sets its alpha and linewidth based on the weight of the edge. Finally, it saves the resulting plot to the specified save path if save_fig is True.
|
|
1222
|
+
|
|
1223
|
+
Overall, this function provides a way to visually represent the relationships between cell types in the CCA results, allowing for a better understanding of the underlying patterns and correlations in the data.
|
|
1224
|
+
"""
|
|
1225
|
+
|
|
1226
|
+
|
|
1227
|
+
def pl_Visulize_CCA_results(
|
|
1228
|
+
CCA_results,
|
|
1229
|
+
output_dir,
|
|
1230
|
+
save_fig=False,
|
|
1231
|
+
p_thresh=0.1,
|
|
1232
|
+
save_name="CCA_vis.png",
|
|
1233
|
+
colors=None,
|
|
1234
|
+
):
|
|
1235
|
+
"""
|
|
1236
|
+
Visualize the results of Canonical Correlation Analysis (CCA) using a graph.
|
|
1237
|
+
|
|
1238
|
+
Parameters
|
|
1239
|
+
----------
|
|
1240
|
+
CCA_results : dict
|
|
1241
|
+
Dictionary containing the CCA results, where the keys are cell type pairs and
|
|
1242
|
+
the values are tuples of (observed correlation, permuted correlations).
|
|
1243
|
+
output_dir : str
|
|
1244
|
+
The output directory for saving the plot.
|
|
1245
|
+
save_fig : bool, optional
|
|
1246
|
+
Whether to save the plot. Defaults to False.
|
|
1247
|
+
p_thresh : float, optional
|
|
1248
|
+
The p-value threshold for adding edges to the graph. Defaults to 0.1.
|
|
1249
|
+
save_name : str, optional
|
|
1250
|
+
The name of the plot file. Defaults to "CCA_vis.png".
|
|
1251
|
+
colors : list or None, optional
|
|
1252
|
+
The color palette for the nodes. If None, a default palette will be used.
|
|
1253
|
+
|
|
1254
|
+
Returns
|
|
1255
|
+
-------
|
|
1256
|
+
None
|
|
1257
|
+
"""
|
|
1258
|
+
|
|
1259
|
+
# Visualization of CCA
|
|
1260
|
+
g1 = nx.petersen_graph()
|
|
1261
|
+
for cn_pair, cc in CCA_results.items():
|
|
1262
|
+
s, t = cn_pair
|
|
1263
|
+
obs, perms = cc
|
|
1264
|
+
p = np.mean(obs > perms)
|
|
1265
|
+
if p > p_thresh:
|
|
1266
|
+
g1.add_edge(s, t, weight=p)
|
|
1267
|
+
|
|
1268
|
+
if colors != None:
|
|
1269
|
+
pal = colors
|
|
1270
|
+
else:
|
|
1271
|
+
pal = sns.color_palette("bright", 50)
|
|
1272
|
+
|
|
1273
|
+
pos = nx.nx_agraph.graphviz_layout(g1, prog="neato")
|
|
1274
|
+
for k, v in pos.items():
|
|
1275
|
+
x, y = v
|
|
1276
|
+
plt.scatter([x], [y], c=[pal[k]], s=300, zorder=3)
|
|
1277
|
+
# plt.text(x,y, k, fontsize = 10, zorder = 10,ha = 'center', va = 'center')
|
|
1278
|
+
plt.axis("off")
|
|
1279
|
+
|
|
1280
|
+
for e0, e1 in g1.edges():
|
|
1281
|
+
p = g1.get_edge_data(e0, e1, default=0)
|
|
1282
|
+
if len(p) == 0:
|
|
1283
|
+
p = 0
|
|
1284
|
+
else:
|
|
1285
|
+
p = p["weight"]
|
|
1286
|
+
print(p)
|
|
1287
|
+
|
|
1288
|
+
alpha = 3 * p**1
|
|
1289
|
+
if alpha > 1:
|
|
1290
|
+
alpha = 1
|
|
1291
|
+
|
|
1292
|
+
plt.plot(
|
|
1293
|
+
[pos[e0][0], pos[e1][0]],
|
|
1294
|
+
[pos[e0][1], pos[e1][1]],
|
|
1295
|
+
c="black",
|
|
1296
|
+
alpha=alpha,
|
|
1297
|
+
linewidth=3 * p**3,
|
|
1298
|
+
)
|
|
1299
|
+
if save_fig == True:
|
|
1300
|
+
plt.savefig(
|
|
1301
|
+
output_dir + "/" + save_name,
|
|
1302
|
+
format="png",
|
|
1303
|
+
dpi=300,
|
|
1304
|
+
transparent=True,
|
|
1305
|
+
bbox_inches="tight",
|
|
1306
|
+
)
|
|
1307
|
+
|
|
1308
|
+
|
|
1309
|
+
#######
|
|
1310
|
+
|
|
1311
|
+
|
|
1312
|
+
def pl_plot_modules_heatmap(
|
|
1313
|
+
data, cns, cts, figsize=(20, 5), num_tissue_modules=2, num_cn_modules=5
|
|
1314
|
+
):
|
|
1315
|
+
"""
|
|
1316
|
+
Plot the modules and their loadings using heatmaps.
|
|
1317
|
+
|
|
1318
|
+
Parameters
|
|
1319
|
+
----------
|
|
1320
|
+
data : array-like
|
|
1321
|
+
The input data.
|
|
1322
|
+
cns : list
|
|
1323
|
+
The names of the copy number alterations (CNs).
|
|
1324
|
+
cts : list
|
|
1325
|
+
The names of the cell types.
|
|
1326
|
+
figsize : tuple, optional
|
|
1327
|
+
The figure size. Defaults to (20, 5).
|
|
1328
|
+
num_tissue_modules : int, optional
|
|
1329
|
+
The number of tissue modules. Defaults to 2.
|
|
1330
|
+
num_cn_modules : int, optional
|
|
1331
|
+
The number of CN modules. Defaults to 5.
|
|
1332
|
+
|
|
1333
|
+
Returns
|
|
1334
|
+
-------
|
|
1335
|
+
None
|
|
1336
|
+
"""
|
|
1337
|
+
|
|
1338
|
+
figsize = figsize
|
|
1339
|
+
core, factors = non_negative_tucker(
|
|
1340
|
+
data, rank=[num_tissue_modules, num_cn_modules, num_cn_modules], random_state=32
|
|
1341
|
+
)
|
|
1342
|
+
plt.subplot(1, 2, 1)
|
|
1343
|
+
sns.heatmap(pd.DataFrame(factors[1], index=cns))
|
|
1344
|
+
plt.ylabel("CN")
|
|
1345
|
+
plt.xlabel("CN module")
|
|
1346
|
+
plt.title("Loadings onto CN modules")
|
|
1347
|
+
plt.subplot(1, 2, 2)
|
|
1348
|
+
sns.heatmap(pd.DataFrame(factors[2], index=cts))
|
|
1349
|
+
plt.ylabel("CT")
|
|
1350
|
+
plt.xlabel("CT module")
|
|
1351
|
+
plt.title("Loadings onto CT modules")
|
|
1352
|
+
plt.show()
|
|
1353
|
+
|
|
1354
|
+
figsize = (num_tissue_modules * 3, 3)
|
|
1355
|
+
for p in range(num_tissue_modules):
|
|
1356
|
+
plt.subplot(1, num_tissue_modules, p + 1)
|
|
1357
|
+
sns.heatmap(pd.DataFrame(core[p]))
|
|
1358
|
+
plt.title("tissue module {}, couplings".format(p))
|
|
1359
|
+
plt.ylabel("CN module")
|
|
1360
|
+
plt.ylabel("CT module")
|
|
1361
|
+
plt.show()
|
|
1362
|
+
|
|
1363
|
+
|
|
1364
|
+
#######
|
|
1365
|
+
|
|
1366
|
+
"""
|
|
1367
|
+
This is a Python function that generates a graphical representation of modules discovered in a dataset using non-negative matrix factorization (NMF).
|
|
1368
|
+
The function takes as input a dataset ('dat'), lists of tissue types ('cts') and copy number segments ('cns'), and parameters specifying the number of tissue and copy number modules to identify ('num_tissue_modules' and 'num_cn_modules', respectively).
|
|
1369
|
+
The function then performs NMF on the input dataset and plots a separate graph for each tissue module.
|
|
1370
|
+
|
|
1371
|
+
In each graph, the function displays the copy number segments and tissue types as scatter points, with the color of each point representing the degree to which that segment or type belongs to the corresponding module.
|
|
1372
|
+
The function also draws rectangles and lines to visually separate the different modules and indicate the strength of the relationships between copy number segments and tissue types within each module.
|
|
1373
|
+
The resulting plots can be saved to a specified file path and name using the 'save_path' and 'save_name' arguments.
|
|
1374
|
+
"""
|
|
1375
|
+
|
|
1376
|
+
|
|
1377
|
+
def pl_plot_modules_graphical(
|
|
1378
|
+
data,
|
|
1379
|
+
cts,
|
|
1380
|
+
cns,
|
|
1381
|
+
num_tissue_modules=2,
|
|
1382
|
+
num_cn_modules=4,
|
|
1383
|
+
scale=0.4,
|
|
1384
|
+
color_dic=None,
|
|
1385
|
+
save_name=None,
|
|
1386
|
+
save_path=None,
|
|
1387
|
+
):
|
|
1388
|
+
"""
|
|
1389
|
+
Generate a graphical representation of modules discovered in a dataset using non-negative matrix factorization (NMF).
|
|
1390
|
+
|
|
1391
|
+
Parameters
|
|
1392
|
+
----------
|
|
1393
|
+
data : array-like
|
|
1394
|
+
The input dataset.
|
|
1395
|
+
cts : list
|
|
1396
|
+
The list of tissue types.
|
|
1397
|
+
cns : list
|
|
1398
|
+
The list of copy number segments.
|
|
1399
|
+
num_tissue_modules : int, optional
|
|
1400
|
+
The number of tissue modules to identify. Defaults to 2.
|
|
1401
|
+
num_cn_modules : int, optional
|
|
1402
|
+
The number of copy number modules to identify. Defaults to 4.
|
|
1403
|
+
scale : float, optional
|
|
1404
|
+
The scaling factor for the plot. Defaults to 0.4.
|
|
1405
|
+
color_dic : dict, optional
|
|
1406
|
+
The color palette dictionary. Defaults to None.
|
|
1407
|
+
save_name : str, optional
|
|
1408
|
+
The name for saving the plots. Defaults to None.
|
|
1409
|
+
save_path : str, optional
|
|
1410
|
+
The file path for saving the plots. Defaults to None.
|
|
1411
|
+
|
|
1412
|
+
Returns
|
|
1413
|
+
-------
|
|
1414
|
+
None
|
|
1415
|
+
"""
|
|
1416
|
+
|
|
1417
|
+
core, factors = non_negative_tucker(
|
|
1418
|
+
data, rank=[num_tissue_modules, num_cn_modules, num_cn_modules], random_state=32
|
|
1419
|
+
)
|
|
1420
|
+
|
|
1421
|
+
if color_dic is None:
|
|
1422
|
+
color_dic = sns.color_palette("bright", 10)
|
|
1423
|
+
palg = sns.color_palette("Greys", 10)
|
|
1424
|
+
|
|
1425
|
+
figsize = (3.67 * scale, 2.00 * scale)
|
|
1426
|
+
cn_scatter_size = scale * scale * 45
|
|
1427
|
+
cel_scatter_size = scale * scale * 15
|
|
1428
|
+
|
|
1429
|
+
for p in range(num_tissue_modules):
|
|
1430
|
+
for idx in range(num_cn_modules):
|
|
1431
|
+
an = (
|
|
1432
|
+
float(np.max(core[p][idx, :]) > 0.1)
|
|
1433
|
+
+ (np.max(core[p][idx, :]) <= 0.1) * 0.05
|
|
1434
|
+
)
|
|
1435
|
+
ac = (
|
|
1436
|
+
float(np.max(core[p][:, idx]) > 0.1)
|
|
1437
|
+
+ (np.max(core[p][:, idx]) <= 0.1) * 0.05
|
|
1438
|
+
)
|
|
1439
|
+
|
|
1440
|
+
cn_fac = factors[1][:, idx]
|
|
1441
|
+
cel_fac = factors[2][:, idx]
|
|
1442
|
+
|
|
1443
|
+
cols_alpha = [
|
|
1444
|
+
(*color_dic[cn], an * np.minimum(cn_fac, 1.0)[i])
|
|
1445
|
+
for i, cn in enumerate(cns)
|
|
1446
|
+
]
|
|
1447
|
+
cols = [
|
|
1448
|
+
(*color_dic[cn], np.minimum(cn_fac, 1.0)[i]) for i, cn in enumerate(cns)
|
|
1449
|
+
]
|
|
1450
|
+
cell_cols_alpha = [
|
|
1451
|
+
(0, 0, 0, an * np.minimum(cel_fac, 1.0)[i])
|
|
1452
|
+
for i, _ in enumerate(cel_fac)
|
|
1453
|
+
]
|
|
1454
|
+
cell_cols = [
|
|
1455
|
+
(0, 0, 0, np.minimum(cel_fac, 1.0)[i]) for i, _ in enumerate(cel_fac)
|
|
1456
|
+
]
|
|
1457
|
+
|
|
1458
|
+
plt.scatter(
|
|
1459
|
+
0.5 * np.arange(len(cn_fac)),
|
|
1460
|
+
5 * idx + np.zeros(len(cn_fac)),
|
|
1461
|
+
c=cols_alpha,
|
|
1462
|
+
s=cn_scatter_size,
|
|
1463
|
+
)
|
|
1464
|
+
offset = 9
|
|
1465
|
+
for i, k in enumerate(cns):
|
|
1466
|
+
plt.text(
|
|
1467
|
+
0.5 * i,
|
|
1468
|
+
5 * idx,
|
|
1469
|
+
k,
|
|
1470
|
+
fontsize=scale * 2,
|
|
1471
|
+
ha="center",
|
|
1472
|
+
va="center",
|
|
1473
|
+
alpha=an,
|
|
1474
|
+
)
|
|
1475
|
+
|
|
1476
|
+
plt.scatter(
|
|
1477
|
+
-4.2 + 0.25 * np.arange(len(cel_fac)) + offset,
|
|
1478
|
+
5 * idx + np.zeros(len(cel_fac)),
|
|
1479
|
+
c=cell_cols_alpha,
|
|
1480
|
+
s=0.5 * cel_scatter_size,
|
|
1481
|
+
) # ,vmax = 0.5,edgecolors=len(cell_cols_alpha)*[(0,0,0,min(1.0,max(0.1,2*an)))], linewidths= 0.05)
|
|
1482
|
+
|
|
1483
|
+
rect = plt.Rectangle(
|
|
1484
|
+
(-0.5, 5 * idx - 2),
|
|
1485
|
+
4.5,
|
|
1486
|
+
4,
|
|
1487
|
+
linewidth=scale * scale * 1,
|
|
1488
|
+
edgecolor="black",
|
|
1489
|
+
facecolor="none",
|
|
1490
|
+
zorder=0,
|
|
1491
|
+
alpha=an,
|
|
1492
|
+
linestyle="--",
|
|
1493
|
+
)
|
|
1494
|
+
ax = plt.gca()
|
|
1495
|
+
ax.add_artist(rect)
|
|
1496
|
+
plt.scatter(
|
|
1497
|
+
[offset - 5],
|
|
1498
|
+
[5 * idx],
|
|
1499
|
+
c="black",
|
|
1500
|
+
marker="D",
|
|
1501
|
+
s=scale * scale * 5,
|
|
1502
|
+
zorder=5,
|
|
1503
|
+
alpha=an,
|
|
1504
|
+
)
|
|
1505
|
+
plt.text(
|
|
1506
|
+
offset - 5,
|
|
1507
|
+
5 * idx,
|
|
1508
|
+
idx,
|
|
1509
|
+
color="white",
|
|
1510
|
+
alpha=an,
|
|
1511
|
+
ha="center",
|
|
1512
|
+
va="center",
|
|
1513
|
+
zorder=6,
|
|
1514
|
+
fontsize=4.5,
|
|
1515
|
+
)
|
|
1516
|
+
plt.scatter(
|
|
1517
|
+
[offset - 4.5],
|
|
1518
|
+
[5 * idx],
|
|
1519
|
+
c="black",
|
|
1520
|
+
marker="D",
|
|
1521
|
+
s=scale * scale * 5,
|
|
1522
|
+
zorder=5,
|
|
1523
|
+
alpha=ac,
|
|
1524
|
+
)
|
|
1525
|
+
plt.text(
|
|
1526
|
+
offset - 4.5,
|
|
1527
|
+
5 * idx,
|
|
1528
|
+
idx,
|
|
1529
|
+
color="white",
|
|
1530
|
+
alpha=ac,
|
|
1531
|
+
ha="center",
|
|
1532
|
+
va="center",
|
|
1533
|
+
zorder=6,
|
|
1534
|
+
fontsize=4.5,
|
|
1535
|
+
)
|
|
1536
|
+
|
|
1537
|
+
rect = plt.Rectangle(
|
|
1538
|
+
(offset - 4.5, 5 * idx - 2),
|
|
1539
|
+
4.5,
|
|
1540
|
+
4,
|
|
1541
|
+
linewidth=scale * 1,
|
|
1542
|
+
edgecolor="black",
|
|
1543
|
+
facecolor="none",
|
|
1544
|
+
zorder=0,
|
|
1545
|
+
alpha=ac,
|
|
1546
|
+
linestyle="-.",
|
|
1547
|
+
)
|
|
1548
|
+
ax.add_artist(rect)
|
|
1549
|
+
|
|
1550
|
+
for i, ct in enumerate(cts):
|
|
1551
|
+
plt.text(
|
|
1552
|
+
-4.2 + offset + 0.25 * i,
|
|
1553
|
+
27.5,
|
|
1554
|
+
ct,
|
|
1555
|
+
rotation=45,
|
|
1556
|
+
color="black",
|
|
1557
|
+
ha="left",
|
|
1558
|
+
va="bottom",
|
|
1559
|
+
fontsize=scale * 2,
|
|
1560
|
+
alpha=1,
|
|
1561
|
+
)
|
|
1562
|
+
for cn_i in range(num_cn_modules):
|
|
1563
|
+
for cel_i in range(num_cn_modules):
|
|
1564
|
+
plt.plot(
|
|
1565
|
+
[-3 + offset - 2, -4 + offset - 0.5],
|
|
1566
|
+
[5 * cn_i, 5 * cel_i],
|
|
1567
|
+
color="black",
|
|
1568
|
+
linewidth=2
|
|
1569
|
+
* scale
|
|
1570
|
+
* scale
|
|
1571
|
+
* 1
|
|
1572
|
+
* min(1.0, max(0, -0.00 + core[p][cn_i, cel_i])),
|
|
1573
|
+
alpha=min(1.0, max(0.000, -0.00 + 10 * core[p][cn_i, cel_i])),
|
|
1574
|
+
) # max(an,ac))
|
|
1575
|
+
|
|
1576
|
+
plt.ylim(-5, 30)
|
|
1577
|
+
plt.axis("off")
|
|
1578
|
+
|
|
1579
|
+
if save_name:
|
|
1580
|
+
plt.savefig(
|
|
1581
|
+
save_path + save_name + "_" + str(p) + "_tensor.png",
|
|
1582
|
+
format="png",
|
|
1583
|
+
dpi=300,
|
|
1584
|
+
transparent=True,
|
|
1585
|
+
bbox_inches="tight",
|
|
1586
|
+
)
|
|
1587
|
+
|
|
1588
|
+
plt.show()
|
|
1589
|
+
|
|
1590
|
+
|
|
1591
|
+
#########
|
|
1592
|
+
|
|
1593
|
+
|
|
1594
|
+
def pl_evaluate_ranks(data, num_tissue_modules=2):
|
|
1595
|
+
"""
|
|
1596
|
+
Evaluate the reconstruction error of different ranks in non-negative matrix factorization (NMF).
|
|
1597
|
+
|
|
1598
|
+
Parameters
|
|
1599
|
+
----------
|
|
1600
|
+
data : array-like
|
|
1601
|
+
The input dataset.
|
|
1602
|
+
num_tissue_modules : int, optional
|
|
1603
|
+
The number of tissue modules to evaluate. Defaults to 2.
|
|
1604
|
+
|
|
1605
|
+
Returns
|
|
1606
|
+
-------
|
|
1607
|
+
None
|
|
1608
|
+
"""
|
|
1609
|
+
|
|
1610
|
+
num_tissue_modules = num_tissue_modules + 1
|
|
1611
|
+
pal = sns.color_palette("bright", 10)
|
|
1612
|
+
palg = sns.color_palette("Greys", 10)
|
|
1613
|
+
|
|
1614
|
+
mat1 = np.zeros((num_tissue_modules, 15))
|
|
1615
|
+
for i in range(2, 15):
|
|
1616
|
+
for j in range(1, num_tissue_modules):
|
|
1617
|
+
# we use NNTD as described in the paper
|
|
1618
|
+
facs_overall = non_negative_tucker(data, rank=[j, i, i], random_state=2336)
|
|
1619
|
+
mat1[j, i] = np.mean(
|
|
1620
|
+
(data - tl.tucker_to_tensor((facs_overall[0], facs_overall[1]))) ** 2
|
|
1621
|
+
)
|
|
1622
|
+
for j in range(1, num_tissue_modules):
|
|
1623
|
+
plt.plot(2 + np.arange(13), mat1[j][2:], label="rank = ({},x,x)".format(j))
|
|
1624
|
+
|
|
1625
|
+
plt.xlabel("x")
|
|
1626
|
+
plt.ylabel("reconstruction error")
|
|
1627
|
+
plt.legend()
|
|
1628
|
+
plt.show()
|
|
1629
|
+
|
|
1630
|
+
|
|
1631
|
+
#########
|
|
1632
|
+
|
|
1633
|
+
|
|
1634
|
+
"""
|
|
1635
|
+
data: the input pandas data frame.
|
|
1636
|
+
sub_list2: a list of subcategories to be considered.
|
|
1637
|
+
per_categ: the categorical column in the data frame to be used.
|
|
1638
|
+
group2: the grouping column in the data frame.
|
|
1639
|
+
repl: the replicate column in the data frame.
|
|
1640
|
+
sub_collumn: the subcategory column in the data frame.
|
|
1641
|
+
cell: the cell type column in the data frame.
|
|
1642
|
+
thres (optional): the threshold for the correlation, default is 0.9.
|
|
1643
|
+
normed (optional): if the percentage should be normalized, default is True.
|
|
1644
|
+
cell2 (optional): the second cell type column in the data frame.
|
|
1645
|
+
"""
|
|
1646
|
+
|
|
1647
|
+
|
|
1648
|
+
def pl_corr_cell(
|
|
1649
|
+
data,
|
|
1650
|
+
per_categ,
|
|
1651
|
+
group2,
|
|
1652
|
+
rep,
|
|
1653
|
+
sub_column,
|
|
1654
|
+
cell,
|
|
1655
|
+
output_dir,
|
|
1656
|
+
save_name,
|
|
1657
|
+
thres=0.9,
|
|
1658
|
+
normed=True,
|
|
1659
|
+
cell2=None,
|
|
1660
|
+
sub_list2=None,
|
|
1661
|
+
):
|
|
1662
|
+
"""
|
|
1663
|
+
Perform correlation analysis on a pandas DataFrame.
|
|
1664
|
+
|
|
1665
|
+
Parameters
|
|
1666
|
+
----------
|
|
1667
|
+
data : pandas DataFrame
|
|
1668
|
+
The input DataFrame.
|
|
1669
|
+
per_categ : str
|
|
1670
|
+
The categorical column in the DataFrame to be used.
|
|
1671
|
+
group2 : str
|
|
1672
|
+
The grouping column in the DataFrame.
|
|
1673
|
+
rep : str
|
|
1674
|
+
The replicate column in the DataFrame.
|
|
1675
|
+
sub_column : str
|
|
1676
|
+
The subcategory column in the DataFrame.
|
|
1677
|
+
cell : str
|
|
1678
|
+
The cell type column in the DataFrame.
|
|
1679
|
+
output_dir : str
|
|
1680
|
+
The directory to save the correlation plot.
|
|
1681
|
+
save_name : str
|
|
1682
|
+
The name of the saved correlation plot.
|
|
1683
|
+
thres : float, optional
|
|
1684
|
+
The threshold for correlation. Default is 0.9.
|
|
1685
|
+
normed : bool, optional
|
|
1686
|
+
If the percentage should be normalized. Default is True.
|
|
1687
|
+
cell2 : str, optional
|
|
1688
|
+
The second cell type column in the DataFrame. Default is None.
|
|
1689
|
+
sub_list2 : list, optional
|
|
1690
|
+
A list of subcategories to be considered. Default is None.
|
|
1691
|
+
|
|
1692
|
+
Returns
|
|
1693
|
+
-------
|
|
1694
|
+
all_pairs : list
|
|
1695
|
+
List of all correlated pairs.
|
|
1696
|
+
pair2 : list
|
|
1697
|
+
List of correlated pairs above the threshold.
|
|
1698
|
+
|
|
1699
|
+
"""
|
|
1700
|
+
|
|
1701
|
+
if sub_list2 != None:
|
|
1702
|
+
result = hf_per_only(
|
|
1703
|
+
data=data,
|
|
1704
|
+
per_cat=per_categ,
|
|
1705
|
+
grouping=group2,
|
|
1706
|
+
sub_list=sub_list2,
|
|
1707
|
+
replicate=rep,
|
|
1708
|
+
sub_col=sub_column,
|
|
1709
|
+
norm=normed,
|
|
1710
|
+
)
|
|
1711
|
+
else:
|
|
1712
|
+
sub_list2 = data[per_categ].unique()
|
|
1713
|
+
result = hf_per_only(
|
|
1714
|
+
data=data,
|
|
1715
|
+
per_cat=per_categ,
|
|
1716
|
+
grouping=group2,
|
|
1717
|
+
sub_list=sub_list2,
|
|
1718
|
+
replicate=rep,
|
|
1719
|
+
sub_col=sub_column,
|
|
1720
|
+
norm=normed,
|
|
1721
|
+
)
|
|
1722
|
+
|
|
1723
|
+
# Format for correlation function
|
|
1724
|
+
mp = pd.pivot_table(
|
|
1725
|
+
result, columns=[per_categ], index=[group2, rep], values=["percentage"]
|
|
1726
|
+
)
|
|
1727
|
+
mp.columns = mp.columns.droplevel(0)
|
|
1728
|
+
cc = mp.reset_index()
|
|
1729
|
+
cmat = cc.corr()
|
|
1730
|
+
|
|
1731
|
+
# Plot
|
|
1732
|
+
sl2, pair2, all_pairs = hf_cor_subset(cor_mat=cmat, threshold=thres, cell_type=cell)
|
|
1733
|
+
|
|
1734
|
+
if cell2:
|
|
1735
|
+
sl3 = [cell2, cell]
|
|
1736
|
+
pl_cor_subplot(
|
|
1737
|
+
mp=cc, sub_list=sl3, output_dir=output_dir, save_name=cell + "_" + cell2
|
|
1738
|
+
)
|
|
1739
|
+
else:
|
|
1740
|
+
pl_cor_subplot(mp=cc, sub_list=sl2, output_dir=output_dir, save_name=cell)
|
|
1741
|
+
|
|
1742
|
+
if save_name:
|
|
1743
|
+
plt.savefig(
|
|
1744
|
+
output_dir + save_name + ".png",
|
|
1745
|
+
format="png",
|
|
1746
|
+
dpi=300,
|
|
1747
|
+
transparent=True,
|
|
1748
|
+
bbox_inches="tight",
|
|
1749
|
+
)
|
|
1750
|
+
|
|
1751
|
+
return all_pairs, pair2, cc
|
|
1752
|
+
|
|
1753
|
+
|
|
1754
|
+
###########
|
|
1755
|
+
|
|
1756
|
+
|
|
1757
|
+
"""
|
|
1758
|
+
data: Pandas data frame which is used as input for plotting.
|
|
1759
|
+
|
|
1760
|
+
|
|
1761
|
+
group1: Categorical column in data that will be used as the x-axis in the pairplot.
|
|
1762
|
+
|
|
1763
|
+
per_cat: Categorical column in data that will be used to calculate the correlation between categories in group1.
|
|
1764
|
+
|
|
1765
|
+
sub_col (optional): Categorical column in data that is used to subset the data.
|
|
1766
|
+
|
|
1767
|
+
sub_list (optional): List of values that is used to select a subset of data based on the sub_col.
|
|
1768
|
+
|
|
1769
|
+
norm (optional): Boolean that determines if the data should be normalized or not.
|
|
1770
|
+
|
|
1771
|
+
group2 (optional): Categorical column in data that is used to group the data.
|
|
1772
|
+
|
|
1773
|
+
count (optional): Boolean that determines if the count of each category in per_cat should be used instead of the percentage.
|
|
1774
|
+
|
|
1775
|
+
plot_scatter (optional): Boolean that determines if the scatterplot should be plotted or not.
|
|
1776
|
+
|
|
1777
|
+
cor_mat: Output data frame containing the correlation matrix.
|
|
1778
|
+
|
|
1779
|
+
mp: Output data frame containing the pivot table of the count or percentage of each category in per_cat based on group1.
|
|
1780
|
+
|
|
1781
|
+
|
|
1782
|
+
Returns:
|
|
1783
|
+
cor_mat (pandas dataframe): Correlation matrix.
|
|
1784
|
+
mp (pandas dataframe): Data after pivoting and grouping.
|
|
1785
|
+
"""
|
|
1786
|
+
|
|
1787
|
+
|
|
1788
|
+
def pl_cor_plot(
|
|
1789
|
+
data,
|
|
1790
|
+
group1,
|
|
1791
|
+
per_cat,
|
|
1792
|
+
sub_col=None,
|
|
1793
|
+
sub_list=None,
|
|
1794
|
+
norm=False,
|
|
1795
|
+
group2=None,
|
|
1796
|
+
count=False,
|
|
1797
|
+
plot_scatter=True,
|
|
1798
|
+
):
|
|
1799
|
+
"""
|
|
1800
|
+
Create a correlation plot using a pandas DataFrame.
|
|
1801
|
+
|
|
1802
|
+
Parameters
|
|
1803
|
+
----------
|
|
1804
|
+
data : pandas DataFrame
|
|
1805
|
+
The input DataFrame.
|
|
1806
|
+
group1 : str
|
|
1807
|
+
Categorical column in data that will be used as the x-axis in the pairplot.
|
|
1808
|
+
per_cat : str
|
|
1809
|
+
Categorical column in data that will be used to calculate the correlation between categories in group1.
|
|
1810
|
+
sub_col : str, optional
|
|
1811
|
+
Categorical column in data that is used to subset the data. Default is None.
|
|
1812
|
+
sub_list : list, optional
|
|
1813
|
+
List of values that is used to select a subset of data based on the sub_col. Default is None.
|
|
1814
|
+
norm : bool, optional
|
|
1815
|
+
Boolean that determines if the data should be normalized or not. Default is False.
|
|
1816
|
+
group2 : str, optional
|
|
1817
|
+
Categorical column in data that is used to group the data. Default is None.
|
|
1818
|
+
count : bool, optional
|
|
1819
|
+
Boolean that determines if the count of each category in per_cat should be used instead of the percentage. Default is False.
|
|
1820
|
+
plot_scatter : bool, optional
|
|
1821
|
+
Boolean that determines if the scatterplot should be plotted or not. Default is True.
|
|
1822
|
+
|
|
1823
|
+
Returns
|
|
1824
|
+
-------
|
|
1825
|
+
cor_mat : pandas DataFrame
|
|
1826
|
+
Correlation matrix.
|
|
1827
|
+
mp : pandas DataFrame
|
|
1828
|
+
Data after pivoting and grouping.
|
|
1829
|
+
"""
|
|
1830
|
+
|
|
1831
|
+
if group2:
|
|
1832
|
+
plt.rcParams["legend.markerscale"] = 1
|
|
1833
|
+
tf = (
|
|
1834
|
+
data.groupby([group1, group2])
|
|
1835
|
+
.apply(lambda x: x[per_cat].value_counts(normalize=True, sort=False) * 100)
|
|
1836
|
+
.to_frame()
|
|
1837
|
+
)
|
|
1838
|
+
tf.columns = tf.columns.astype(str)
|
|
1839
|
+
tf.reset_index(inplace=True)
|
|
1840
|
+
mp = pd.pivot_table(
|
|
1841
|
+
tf, columns=["level_2"], index=[group1, group2], values=[per_cat]
|
|
1842
|
+
)
|
|
1843
|
+
mp.columns = mp.columns.droplevel(0)
|
|
1844
|
+
mp.reset_index(inplace=True)
|
|
1845
|
+
mp2 = mp.fillna(0)
|
|
1846
|
+
cor_mat = mp2.corr()
|
|
1847
|
+
mask = np.triu(np.ones_like(cor_mat, dtype=bool))
|
|
1848
|
+
plt.figure(figsize=(len(cor_mat.index), len(cor_mat.columns) * 0.8))
|
|
1849
|
+
sns.heatmap(cor_mat, cmap="coolwarm", center=0, vmin=-1, vmax=1, mask=mask)
|
|
1850
|
+
if plot_scatter:
|
|
1851
|
+
sns.pairplot(
|
|
1852
|
+
mp,
|
|
1853
|
+
diag_kind="kde",
|
|
1854
|
+
plot_kws={"alpha": 0.6, "s": 80, "edgecolor": "k"},
|
|
1855
|
+
size=4,
|
|
1856
|
+
hue=group2,
|
|
1857
|
+
)
|
|
1858
|
+
else:
|
|
1859
|
+
if count:
|
|
1860
|
+
tf = data.groupby([group1, per_cat]).count()["region"].to_frame()
|
|
1861
|
+
tf.reset_index(inplace=True)
|
|
1862
|
+
mp = pd.pivot_table(
|
|
1863
|
+
tf, columns=[per_cat], index=[group1], values=["region"]
|
|
1864
|
+
)
|
|
1865
|
+
mp.columns = mp.columns.droplevel(0)
|
|
1866
|
+
mp.reset_index(inplace=True)
|
|
1867
|
+
mp2 = mp.fillna(0)
|
|
1868
|
+
cor_mat = mp2.corr()
|
|
1869
|
+
mask = np.triu(np.ones_like(cor_mat, dtype=bool))
|
|
1870
|
+
plt.figure(figsize=(len(cor_mat.index), len(cor_mat.columns) * 0.8))
|
|
1871
|
+
sns.heatmap(cor_mat, cmap="coolwarm", center=0, vmin=-1, vmax=1, mask=mask)
|
|
1872
|
+
if plot_scatter:
|
|
1873
|
+
sns.pairplot(
|
|
1874
|
+
mp,
|
|
1875
|
+
diag_kind="kde",
|
|
1876
|
+
plot_kws={"scatter_kws": {"alpha": 0.6, "s": 80, "edgecolor": "k"}},
|
|
1877
|
+
size=4,
|
|
1878
|
+
kind="reg",
|
|
1879
|
+
)
|
|
1880
|
+
else:
|
|
1881
|
+
# Find Percentage of cell type
|
|
1882
|
+
test = data.copy()
|
|
1883
|
+
|
|
1884
|
+
if sub_list == None:
|
|
1885
|
+
sub_list = data[per_cat].unique()
|
|
1886
|
+
|
|
1887
|
+
sub_list1 = sub_list.copy()
|
|
1888
|
+
|
|
1889
|
+
if norm == True:
|
|
1890
|
+
test1 = test.loc[test[sub_col].isin(sub_list1)]
|
|
1891
|
+
immune_list = list(test1[per_cat].unique())
|
|
1892
|
+
else:
|
|
1893
|
+
test1 = test.copy()
|
|
1894
|
+
immune_list = list(
|
|
1895
|
+
test.loc[test[sub_col].isin(sub_list1)][per_cat].unique()
|
|
1896
|
+
)
|
|
1897
|
+
|
|
1898
|
+
test1[per_cat] = test1[per_cat].astype("category")
|
|
1899
|
+
tf = test1.groupby([group1]).apply(
|
|
1900
|
+
lambda x: x[per_cat].value_counts(normalize=True, sort=False) * 100
|
|
1901
|
+
)
|
|
1902
|
+
tf.columns = tf.columns.astype(str)
|
|
1903
|
+
mp = tf[immune_list]
|
|
1904
|
+
mp.reset_index(inplace=True)
|
|
1905
|
+
cor_mat = mp.corr()
|
|
1906
|
+
mask = np.triu(np.ones_like(cor_mat, dtype=bool))
|
|
1907
|
+
plt.figure(figsize=(len(cor_mat.index), len(cor_mat.columns) * 0.8))
|
|
1908
|
+
sns.heatmap(cor_mat, cmap="coolwarm", center=0, vmin=-1, vmax=1, mask=mask)
|
|
1909
|
+
if plot_scatter:
|
|
1910
|
+
sns.pairplot(
|
|
1911
|
+
mp,
|
|
1912
|
+
diag_kind="kde",
|
|
1913
|
+
plot_kws={"scatter_kws": {"alpha": 0.6, "s": 80, "edgecolor": "k"}},
|
|
1914
|
+
size=4,
|
|
1915
|
+
kind="reg",
|
|
1916
|
+
)
|
|
1917
|
+
|
|
1918
|
+
return cor_mat, mp
|
|
1919
|
+
|
|
1920
|
+
|
|
1921
|
+
########
|
|
1922
|
+
|
|
1923
|
+
|
|
1924
|
+
"""
|
|
1925
|
+
mp: A pandas dataframe from which a subset of columns will be selected and plotted.
|
|
1926
|
+
sub_list: A list of column names from the dataframe mp that will be selected and plotted.
|
|
1927
|
+
save_name (optional): A string that specifies the file name for saving the plot.
|
|
1928
|
+
If save_name is not provided, the plot will not be saved.
|
|
1929
|
+
"""
|
|
1930
|
+
|
|
1931
|
+
|
|
1932
|
+
def pl_cor_subplot(mp, sub_list, output_dir, save_name=None):
|
|
1933
|
+
"""
|
|
1934
|
+
Create a subplot of pairwise correlation plots using a subset of columns from a pandas DataFrame.
|
|
1935
|
+
|
|
1936
|
+
Parameters
|
|
1937
|
+
----------
|
|
1938
|
+
mp : pandas DataFrame
|
|
1939
|
+
The input DataFrame from which a subset of columns will be selected and plotted.
|
|
1940
|
+
sub_list : list
|
|
1941
|
+
A list of column names from the dataframe `mp` that will be selected and plotted.
|
|
1942
|
+
output_dir : str
|
|
1943
|
+
The output directory where the plot will be saved.
|
|
1944
|
+
save_name : str, optional
|
|
1945
|
+
A string that specifies the file name for saving the plot. If `save_name` is not provided, the plot will not be saved.
|
|
1946
|
+
"""
|
|
1947
|
+
|
|
1948
|
+
sub_cor = mp[sub_list]
|
|
1949
|
+
sns.pairplot(
|
|
1950
|
+
sub_cor,
|
|
1951
|
+
diag_kind="kde",
|
|
1952
|
+
plot_kws={"scatter_kws": {"alpha": 0.6, "s": 80, "edgecolor": "k"}},
|
|
1953
|
+
size=4,
|
|
1954
|
+
kind="reg",
|
|
1955
|
+
corner=True,
|
|
1956
|
+
)
|
|
1957
|
+
if save_name:
|
|
1958
|
+
plt.savefig(
|
|
1959
|
+
output_dir + save_name + "_corrplot.png",
|
|
1960
|
+
format="png",
|
|
1961
|
+
dpi=300,
|
|
1962
|
+
transparent=True,
|
|
1963
|
+
bbox_inches="tight",
|
|
1964
|
+
)
|
|
1965
|
+
|
|
1966
|
+
|
|
1967
|
+
def annotate(data, names, **kws):
|
|
1968
|
+
r, p = sp.stats.pearsonr(data[names[0]], data[names[1]])
|
|
1969
|
+
ax = plt.gca()
|
|
1970
|
+
ax.text(
|
|
1971
|
+
0.5, 0.8, "r={:.2f}, p={:.2g}".format(r, p), transform=ax.transAxes, fontsize=14
|
|
1972
|
+
)
|
|
1973
|
+
|
|
1974
|
+
|
|
1975
|
+
def pl_cor_subplot_new(mp, sub_list, output_dir, save_name=None):
|
|
1976
|
+
"""
|
|
1977
|
+
Create a subplot of pairwise correlation plots using a subset of columns from a pandas DataFrame.
|
|
1978
|
+
|
|
1979
|
+
Parameters
|
|
1980
|
+
----------
|
|
1981
|
+
mp : pandas DataFrame
|
|
1982
|
+
The input DataFrame from which a subset of columns will be selected and plotted.
|
|
1983
|
+
sub_list : list
|
|
1984
|
+
A list of column names from the dataframe `mp` that will be selected and plotted.
|
|
1985
|
+
output_dir : str
|
|
1986
|
+
The output directory where the plot will be saved.
|
|
1987
|
+
save_name : str, optional
|
|
1988
|
+
A string that specifies the file name for saving the plot. If `save_name` is not provided, the plot will not be saved.
|
|
1989
|
+
"""
|
|
1990
|
+
|
|
1991
|
+
sub_cor = mp[sub_list]
|
|
1992
|
+
|
|
1993
|
+
names = sub_cor.columns.tolist()
|
|
1994
|
+
|
|
1995
|
+
g = sns.lmplot(x=names[0], y=names[1], data=df2, height=5, aspect=1)
|
|
1996
|
+
|
|
1997
|
+
g.map_dataframe(annotate(data=mp, names=names))
|
|
1998
|
+
plt.xlabel(names[0], fontsize=14)
|
|
1999
|
+
plt.ylabel(names[1], fontsize=14)
|
|
2000
|
+
plt.xticks(fontsize=14)
|
|
2001
|
+
plt.yticks(fontsize=14)
|
|
2002
|
+
plt.show()
|
|
2003
|
+
|
|
2004
|
+
if save_name:
|
|
2005
|
+
plt.savefig(
|
|
2006
|
+
output_dir + save_name + "_corrplot.png",
|
|
2007
|
+
format="png",
|
|
2008
|
+
dpi=300,
|
|
2009
|
+
transparent=True,
|
|
2010
|
+
bbox_inches="tight",
|
|
2011
|
+
)
|
|
2012
|
+
|
|
2013
|
+
|
|
2014
|
+
########
|
|
2015
|
+
|
|
2016
|
+
|
|
2017
|
+
def pl_Niche_heatmap(k_centroids, w, n_num, sum_cols):
|
|
2018
|
+
"""
|
|
2019
|
+
Create a heatmap to show the types of cells (ClusterIDs) in different niches.
|
|
2020
|
+
|
|
2021
|
+
Parameters
|
|
2022
|
+
----------
|
|
2023
|
+
k_centroids : numpy array
|
|
2024
|
+
The centroid values for each niche.
|
|
2025
|
+
w : pandas DataFrame
|
|
2026
|
+
The input data containing cluster information.
|
|
2027
|
+
n_num : int
|
|
2028
|
+
The niche number to plot.
|
|
2029
|
+
sum_cols : list
|
|
2030
|
+
The list of columns to sum for the heatmap.
|
|
2031
|
+
"""
|
|
2032
|
+
|
|
2033
|
+
# this plot shows the types of cells (ClusterIDs) in the different niches (0-9)
|
|
2034
|
+
k_to_plot = n_num
|
|
2035
|
+
niche_clusters = k_centroids[k_to_plot]
|
|
2036
|
+
values = w[sum_cols].values
|
|
2037
|
+
tissue_avgs = values.mean(axis=0)
|
|
2038
|
+
fc = np.log2(
|
|
2039
|
+
(
|
|
2040
|
+
(niche_clusters + tissue_avgs)
|
|
2041
|
+
/ (niche_clusters + tissue_avgs).sum(axis=1, keepdims=True)
|
|
2042
|
+
)
|
|
2043
|
+
/ tissue_avgs
|
|
2044
|
+
)
|
|
2045
|
+
fc = pd.DataFrame(fc, columns=sum_cols)
|
|
2046
|
+
s = sns.clustermap(fc, cmap="bwr", vmax=-5)
|
|
2047
|
+
|
|
2048
|
+
|
|
2049
|
+
def pl_Barycentric_coordinate_projection(
|
|
2050
|
+
w,
|
|
2051
|
+
plot_list,
|
|
2052
|
+
threshold,
|
|
2053
|
+
output_dir,
|
|
2054
|
+
save_name,
|
|
2055
|
+
col_dic,
|
|
2056
|
+
l,
|
|
2057
|
+
n_num,
|
|
2058
|
+
cluster_col,
|
|
2059
|
+
SMALL_SIZE=14,
|
|
2060
|
+
MEDIUM_SIZE=16,
|
|
2061
|
+
BIGGER_SIZE=18,
|
|
2062
|
+
figsize=(14, 14),
|
|
2063
|
+
):
|
|
2064
|
+
"""
|
|
2065
|
+
Create a barycentric coordinate projection plot.
|
|
2066
|
+
|
|
2067
|
+
Parameters
|
|
2068
|
+
----------
|
|
2069
|
+
w : pandas DataFrame
|
|
2070
|
+
The input data containing coordinate information.
|
|
2071
|
+
plot_list : list
|
|
2072
|
+
The list of columns to plot.
|
|
2073
|
+
threshold : int
|
|
2074
|
+
The threshold value for data selection.
|
|
2075
|
+
output_dir : str
|
|
2076
|
+
The output directory where the plot will be saved.
|
|
2077
|
+
save_name : str
|
|
2078
|
+
The file name for saving the plot.
|
|
2079
|
+
col_dic : dict
|
|
2080
|
+
A dictionary mapping cluster IDs to colors.
|
|
2081
|
+
l : list
|
|
2082
|
+
A list of cluster IDs.
|
|
2083
|
+
n_num : int
|
|
2084
|
+
The niche number.
|
|
2085
|
+
cluster_col : str
|
|
2086
|
+
The column containing cluster information.
|
|
2087
|
+
SMALL_SIZE : int, optional
|
|
2088
|
+
The font size for small text. Default is 14.
|
|
2089
|
+
MEDIUM_SIZE : int, optional
|
|
2090
|
+
The font size for medium text. Default is 16.
|
|
2091
|
+
BIGGER_SIZE : int, optional
|
|
2092
|
+
The font size for large text. Default is 18.
|
|
2093
|
+
figsize : tuple, optional
|
|
2094
|
+
The figure size. Default is (14, 14).
|
|
2095
|
+
"""
|
|
2096
|
+
|
|
2097
|
+
# Settings for graph
|
|
2098
|
+
plt.rc("font", size=SMALL_SIZE) # controls default text sizes
|
|
2099
|
+
plt.rc("axes", titlesize=SMALL_SIZE) # fontsize of the axes title
|
|
2100
|
+
plt.rc("axes", labelsize=MEDIUM_SIZE) # fontsize of the x and y labels
|
|
2101
|
+
plt.rc("xtick", labelsize=SMALL_SIZE) # fontsize of the tick labels
|
|
2102
|
+
plt.rc("ytick", labelsize=SMALL_SIZE) # fontsize of the tick labels
|
|
2103
|
+
plt.rc("legend", fontsize=SMALL_SIZE) # legend fontsize
|
|
2104
|
+
plt.rc("figure", titlesize=BIGGER_SIZE) # fontsize of the figure title
|
|
2105
|
+
|
|
2106
|
+
lmap = {j: i for i, j in enumerate(l)}
|
|
2107
|
+
palt = col_dic
|
|
2108
|
+
|
|
2109
|
+
wgc = w.loc[w.loc[:, plot_list].sum(axis=1) > threshold, :]
|
|
2110
|
+
idx = wgc.index.values
|
|
2111
|
+
xl = wgc.loc[:, plot_list]
|
|
2112
|
+
proj = np.array([[0, 0], [np.cos(np.pi / 3), np.sin(np.pi / 3)], [1, 0]])
|
|
2113
|
+
coords = np.dot(xl / n_num, proj) #####window size fraction
|
|
2114
|
+
|
|
2115
|
+
plt.figure(figsize=figsize)
|
|
2116
|
+
jit = 0.002
|
|
2117
|
+
cols = [palt[a] for a in wgc[cluster_col]]
|
|
2118
|
+
|
|
2119
|
+
plt.scatter(
|
|
2120
|
+
coords[:, 0] + jit * np.random.randn(len(coords)),
|
|
2121
|
+
coords[:, 1] + jit * np.random.randn(len(coords)),
|
|
2122
|
+
s=15,
|
|
2123
|
+
alpha=0.5,
|
|
2124
|
+
c=cols,
|
|
2125
|
+
)
|
|
2126
|
+
plt.axis("off")
|
|
2127
|
+
plt.show()
|
|
2128
|
+
|
|
2129
|
+
if save_name:
|
|
2130
|
+
plt.savefig(
|
|
2131
|
+
output_dir + save_name + ".png",
|
|
2132
|
+
format="png",
|
|
2133
|
+
dpi=300,
|
|
2134
|
+
transparent=True,
|
|
2135
|
+
bbox_inches="tight",
|
|
2136
|
+
)
|
|
2137
|
+
|
|
2138
|
+
|
|
2139
|
+
########
|
|
2140
|
+
|
|
2141
|
+
|
|
2142
|
+
def pl_get_network(
|
|
2143
|
+
ttl_per_thres,
|
|
2144
|
+
comb_per_thres,
|
|
2145
|
+
color_dic,
|
|
2146
|
+
windows,
|
|
2147
|
+
n_num,
|
|
2148
|
+
l,
|
|
2149
|
+
tissue_col=None,
|
|
2150
|
+
tissue_subset_list=None,
|
|
2151
|
+
sub_col="Tissue Unit",
|
|
2152
|
+
neigh_sub=None,
|
|
2153
|
+
save_name=None,
|
|
2154
|
+
save_path=None,
|
|
2155
|
+
figsize=(20, 10),
|
|
2156
|
+
):
|
|
2157
|
+
"""
|
|
2158
|
+
Generate a network plot based on combination frequencies.
|
|
2159
|
+
|
|
2160
|
+
Parameters
|
|
2161
|
+
----------
|
|
2162
|
+
ttl_per_thres : float
|
|
2163
|
+
The threshold for the total percentage of combinations.
|
|
2164
|
+
comb_per_thres : float
|
|
2165
|
+
The threshold for the combination frequency.
|
|
2166
|
+
color_dic : dict
|
|
2167
|
+
A dictionary mapping cluster IDs to colors.
|
|
2168
|
+
windows : dict
|
|
2169
|
+
A dictionary containing window data.
|
|
2170
|
+
n_num : int
|
|
2171
|
+
The window size.
|
|
2172
|
+
l : list
|
|
2173
|
+
A list of cluster IDs.
|
|
2174
|
+
tissue_col : bool or None, optional
|
|
2175
|
+
Whether to filter data based on tissue columns. Default is None.
|
|
2176
|
+
tissue_subset_list : list or None, optional
|
|
2177
|
+
A list of tissue subsets to consider. Default is None.
|
|
2178
|
+
sub_col : str, optional
|
|
2179
|
+
The name of the column for subsetting. Default is 'Tissue Unit'.
|
|
2180
|
+
neigh_sub : None, optional
|
|
2181
|
+
Subset neighborhoods based on specified values. Default is None.
|
|
2182
|
+
save_name : str or None, optional
|
|
2183
|
+
The name for saving the plot. Default is None.
|
|
2184
|
+
save_path : str or None, optional
|
|
2185
|
+
The path for saving the plot. Default is None.
|
|
2186
|
+
figsize : tuple, optional
|
|
2187
|
+
The figure size. Default is (20, 10).
|
|
2188
|
+
"""
|
|
2189
|
+
|
|
2190
|
+
# Choose the windows size to continue with
|
|
2191
|
+
w = windows[n_num]
|
|
2192
|
+
if tissue_col == True:
|
|
2193
|
+
w = w[w.tissue_col.isin(tissue_subset_list)]
|
|
2194
|
+
if neigh_sub:
|
|
2195
|
+
w = w[w[sub_col].isin(neigh_sub)]
|
|
2196
|
+
xm = w.loc[:, l].values / n_num
|
|
2197
|
+
|
|
2198
|
+
# Get the neighborhood combinations based on the threshold
|
|
2199
|
+
simps = hf_get_thresh_simps(xm, ttl_per_thres)
|
|
2200
|
+
simp_freqs = simps.value_counts(normalize=True)
|
|
2201
|
+
simp_sums = np.cumsum(simp_freqs)
|
|
2202
|
+
|
|
2203
|
+
g = nx.DiGraph()
|
|
2204
|
+
thresh_cumulative = 0.95
|
|
2205
|
+
thresh_freq = comb_per_thres
|
|
2206
|
+
# selected_simps = simp_sums[simp_sums<=thresh_cumulative].index.values
|
|
2207
|
+
selected_simps = simp_freqs[simp_freqs >= thresh_freq].index.values
|
|
2208
|
+
|
|
2209
|
+
# this builds the graph for the CN combination map
|
|
2210
|
+
selected_simps
|
|
2211
|
+
for e0 in selected_simps:
|
|
2212
|
+
for e1 in selected_simps:
|
|
2213
|
+
if (set(list(e0)) < set(list(e1))) and (len(e1) == len(e0) + 1):
|
|
2214
|
+
g.add_edge(e0, e1)
|
|
2215
|
+
|
|
2216
|
+
# this plots the CN combination map
|
|
2217
|
+
|
|
2218
|
+
draw = g
|
|
2219
|
+
pos = nx.drawing.nx_pydot.graphviz_layout(draw, prog="dot")
|
|
2220
|
+
height = 8
|
|
2221
|
+
|
|
2222
|
+
plt.figure(figsize=figsize)
|
|
2223
|
+
for n in draw.nodes():
|
|
2224
|
+
col = "black"
|
|
2225
|
+
if len(draw.in_edges(n)) < len(n):
|
|
2226
|
+
col = "black"
|
|
2227
|
+
plt.scatter(
|
|
2228
|
+
pos[n][0],
|
|
2229
|
+
pos[n][1] - 5,
|
|
2230
|
+
s=simp_freqs[list(simp_freqs.index).index(n)] * 10000,
|
|
2231
|
+
c=col,
|
|
2232
|
+
zorder=-1,
|
|
2233
|
+
)
|
|
2234
|
+
# if n in tops:
|
|
2235
|
+
# plt.text(pos[n][0],pos[n][1]-7, '*', fontsize = 25, color = 'white', ha = 'center', va = 'center',zorder = 20)
|
|
2236
|
+
delta = 8
|
|
2237
|
+
# plot_sim((pos[n][0]+delta, pos[n][1]+delta),n, scale = 20,s = 200,text = True,fontsize = 15)
|
|
2238
|
+
plt.scatter(
|
|
2239
|
+
[pos[n][0]] * len(n),
|
|
2240
|
+
[pos[n][1] + delta * (i + 1) for i in range(len(n))],
|
|
2241
|
+
c=[color_dic[l[i]] for i in n],
|
|
2242
|
+
marker="^",
|
|
2243
|
+
zorder=5,
|
|
2244
|
+
s=400,
|
|
2245
|
+
)
|
|
2246
|
+
|
|
2247
|
+
j = 0
|
|
2248
|
+
for e0, e1 in draw.edges():
|
|
2249
|
+
weight = 0.2
|
|
2250
|
+
alpha = 0.3
|
|
2251
|
+
if len(draw.in_edges(e1)) < len(e1):
|
|
2252
|
+
color = "black"
|
|
2253
|
+
lw = 1
|
|
2254
|
+
weight = 0.4
|
|
2255
|
+
color = "black"
|
|
2256
|
+
plt.plot(
|
|
2257
|
+
[pos[e0][0], pos[e1][0]],
|
|
2258
|
+
[pos[e0][1], pos[e1][1]],
|
|
2259
|
+
color=color,
|
|
2260
|
+
linewidth=weight,
|
|
2261
|
+
alpha=alpha,
|
|
2262
|
+
zorder=-10,
|
|
2263
|
+
)
|
|
2264
|
+
|
|
2265
|
+
plt.axis("off")
|
|
2266
|
+
if save_name is not None:
|
|
2267
|
+
plt.savefig(save_path + save_name + "_spatial_contexts.pdf") #'.png', dpi=300)
|
|
2268
|
+
plt.show()
|
|
2269
|
+
|
|
2270
|
+
|
|
2271
|
+
#########
|
|
2272
|
+
|
|
2273
|
+
|
|
2274
|
+
def pl_spatial_context_stats_vis(
|
|
2275
|
+
neigh_comb,
|
|
2276
|
+
simp_df_tissue1,
|
|
2277
|
+
simp_df_tissue2,
|
|
2278
|
+
pal_tis={"Resection": "blue", "Biopsy": "orange"},
|
|
2279
|
+
plot_order=["Resection", "Biopsy"],
|
|
2280
|
+
figsize=(5, 5),
|
|
2281
|
+
):
|
|
2282
|
+
# Set Neigh and make comparison
|
|
2283
|
+
neigh_comb = (9,)
|
|
2284
|
+
|
|
2285
|
+
df1 = simp_df_tissue1.loc[[neigh_comb]].T
|
|
2286
|
+
df2 = simp_df_tissue2.loc[[neigh_comb]].T
|
|
2287
|
+
print(stats.mannwhitneyu(df1[df1.columns[0]], df2[df2.columns[0]]))
|
|
2288
|
+
|
|
2289
|
+
df1.reset_index(inplace=True)
|
|
2290
|
+
df1[["donor", "tissue"]] = df1["index"].str.split("_", expand=True)
|
|
2291
|
+
df2.reset_index(inplace=True)
|
|
2292
|
+
df2[["donor", "tissue"]] = df2["index"].str.split("_", expand=True)
|
|
2293
|
+
df_m = pd.concat([df1, df2])
|
|
2294
|
+
df_m["combo"] = str(neigh_comb)
|
|
2295
|
+
|
|
2296
|
+
# swarmplot to compare
|
|
2297
|
+
plt.figure(figsize=figsize)
|
|
2298
|
+
|
|
2299
|
+
ax = sns.boxplot(
|
|
2300
|
+
data=df_m,
|
|
2301
|
+
x="combo",
|
|
2302
|
+
y=neigh_comb,
|
|
2303
|
+
hue="tissue",
|
|
2304
|
+
dodge=True,
|
|
2305
|
+
hue_order=plot_order,
|
|
2306
|
+
palette=pal_tis,
|
|
2307
|
+
)
|
|
2308
|
+
ax = sns.swarmplot(
|
|
2309
|
+
data=df_m,
|
|
2310
|
+
x="combo",
|
|
2311
|
+
y=neigh_comb,
|
|
2312
|
+
hue="tissue",
|
|
2313
|
+
dodge=True,
|
|
2314
|
+
hue_order=plot_order,
|
|
2315
|
+
edgecolor="black",
|
|
2316
|
+
linewidth=1,
|
|
2317
|
+
palette=pal_tis,
|
|
2318
|
+
)
|
|
2319
|
+
for patch in ax.artists:
|
|
2320
|
+
r, g, b, a = patch.get_facecolor()
|
|
2321
|
+
patch.set_facecolor((r, g, b, 0.3))
|
|
2322
|
+
# ax.set_yscale(\log\)
|
|
2323
|
+
plt.xlabel("")
|
|
2324
|
+
handles, labels = ax.get_legend_handles_labels()
|
|
2325
|
+
plt.legend(
|
|
2326
|
+
handles[: len(df_m["tissue"].unique())],
|
|
2327
|
+
labels[: len(df_m["tissue"].unique())],
|
|
2328
|
+
bbox_to_anchor=(1.05, 1),
|
|
2329
|
+
loc=2,
|
|
2330
|
+
borderaxespad=0.0,
|
|
2331
|
+
frameon=False,
|
|
2332
|
+
)
|
|
2333
|
+
plt.xticks(rotation=90)
|
|
2334
|
+
sns.despine(trim=True)
|
|
2335
|
+
|
|
2336
|
+
# pt.savefig(save_path+save_name+'_swarm_boxplot.png', format='png', dpi=300, transparent=True, bbox_inches='tight')
|
|
2337
|
+
|
|
2338
|
+
|
|
2339
|
+
##########
|
|
2340
|
+
|
|
2341
|
+
|
|
2342
|
+
def pl_conplot(
|
|
2343
|
+
df,
|
|
2344
|
+
feature,
|
|
2345
|
+
exp="Exp",
|
|
2346
|
+
X="X",
|
|
2347
|
+
Y="Y",
|
|
2348
|
+
invert_y=False,
|
|
2349
|
+
cmap="RdBu",
|
|
2350
|
+
size=5,
|
|
2351
|
+
alpha=1,
|
|
2352
|
+
figsize=10,
|
|
2353
|
+
exps=None,
|
|
2354
|
+
fig=None,
|
|
2355
|
+
**kwargs,
|
|
2356
|
+
):
|
|
2357
|
+
"""
|
|
2358
|
+
Plot continuous variable with a colormap:
|
|
2359
|
+
|
|
2360
|
+
df: dataframe of cells with spatial location and feature to color. Must have columns ['X','Y','Exp',feature]
|
|
2361
|
+
feature: feature in df to color points by
|
|
2362
|
+
cmap: matplotlib colormap
|
|
2363
|
+
size: point size
|
|
2364
|
+
thresh_val: only include points below this value
|
|
2365
|
+
"""
|
|
2366
|
+
if invert_y:
|
|
2367
|
+
y_orig = df[Y].values.copy()
|
|
2368
|
+
df[Y] *= -1
|
|
2369
|
+
|
|
2370
|
+
if exps is None:
|
|
2371
|
+
exps = list(df[exp].unique()) # display all experiments
|
|
2372
|
+
elif type(exps) != list:
|
|
2373
|
+
exps = [exps]
|
|
2374
|
+
|
|
2375
|
+
if fig is None:
|
|
2376
|
+
f, ax = plt.subplots(len(exps), 1, figsize=(figsize, len(exps) * figsize))
|
|
2377
|
+
if len(exps) == 1:
|
|
2378
|
+
ax = [ax]
|
|
2379
|
+
else:
|
|
2380
|
+
f, ax = fig
|
|
2381
|
+
|
|
2382
|
+
for i, name in enumerate(exps):
|
|
2383
|
+
data = df[df[exp] == name]
|
|
2384
|
+
|
|
2385
|
+
ax[i].scatter(
|
|
2386
|
+
data[X], -data[Y], c=data[feature], cmap=cmap, s=size, alpha=alpha, **kwargs
|
|
2387
|
+
)
|
|
2388
|
+
ax[i].set_title(name + "_" + str(feature) + "_" + str(len(data)))
|
|
2389
|
+
ax[i].axis("off")
|
|
2390
|
+
|
|
2391
|
+
if invert_y:
|
|
2392
|
+
df[Y] = y_orig
|
|
2393
|
+
return f, ax
|
|
2394
|
+
|
|
2395
|
+
|
|
2396
|
+
##############
|
|
2397
|
+
|
|
2398
|
+
|
|
2399
|
+
def pl_catplot(
|
|
2400
|
+
df,
|
|
2401
|
+
hue,
|
|
2402
|
+
exp="Exp",
|
|
2403
|
+
X="X",
|
|
2404
|
+
Y="Y",
|
|
2405
|
+
invert_y=False,
|
|
2406
|
+
size=3,
|
|
2407
|
+
legend=True,
|
|
2408
|
+
palette="bright",
|
|
2409
|
+
figsize=5,
|
|
2410
|
+
style="white",
|
|
2411
|
+
exps=None,
|
|
2412
|
+
axis="on",
|
|
2413
|
+
ticks_fontsize=15,
|
|
2414
|
+
scatter_kws={},
|
|
2415
|
+
**kwargs,
|
|
2416
|
+
):
|
|
2417
|
+
"""
|
|
2418
|
+
Plots cells in tissue section color coded by either cell type or node allocation.
|
|
2419
|
+
df: dataframe with cell information
|
|
2420
|
+
size: size of point to plot for each cell.
|
|
2421
|
+
hue: color by "Clusterid" or "Node" respectively.
|
|
2422
|
+
legend: to include legend in plot.
|
|
2423
|
+
"""
|
|
2424
|
+
scatter_kws_ = {"s": size, "alpha": 1}
|
|
2425
|
+
scatter_kws_.update(scatter_kws)
|
|
2426
|
+
|
|
2427
|
+
figures = []
|
|
2428
|
+
df = df.rename(columns=lambda x: str(x))
|
|
2429
|
+
|
|
2430
|
+
df[hue] = df[hue].astype("category")
|
|
2431
|
+
if invert_y:
|
|
2432
|
+
y_orig = df[Y].values.copy()
|
|
2433
|
+
df[Y] *= -1
|
|
2434
|
+
|
|
2435
|
+
style = {"axes.facecolor": style}
|
|
2436
|
+
sns.set_style(style)
|
|
2437
|
+
if exps == None:
|
|
2438
|
+
exps = list(df[exp].unique()) # display all experiments
|
|
2439
|
+
elif type(exps) != list:
|
|
2440
|
+
exps = [exps]
|
|
2441
|
+
|
|
2442
|
+
for name in exps:
|
|
2443
|
+
data = df[df[exp] == name]
|
|
2444
|
+
|
|
2445
|
+
data[X] = data[X] - data[X].min()
|
|
2446
|
+
data[Y] = data[Y] - data[Y].min()
|
|
2447
|
+
|
|
2448
|
+
print(name)
|
|
2449
|
+
xrange = data[X].max() - data[X].min()
|
|
2450
|
+
yrange = data[Y].max() - data[Y].min()
|
|
2451
|
+
# if 'aspect' not in kwargs:
|
|
2452
|
+
# kwargs['aspect'] = xrange/yrange
|
|
2453
|
+
f = sns.lmplot(
|
|
2454
|
+
x=X,
|
|
2455
|
+
y=Y,
|
|
2456
|
+
data=data,
|
|
2457
|
+
hue=hue,
|
|
2458
|
+
legend=legend,
|
|
2459
|
+
fit_reg=False,
|
|
2460
|
+
markers=".",
|
|
2461
|
+
height=yrange / 400,
|
|
2462
|
+
palette=palette,
|
|
2463
|
+
scatter=True,
|
|
2464
|
+
scatter_kws=scatter_kws_,
|
|
2465
|
+
aspect=xrange / yrange,
|
|
2466
|
+
**kwargs,
|
|
2467
|
+
)
|
|
2468
|
+
|
|
2469
|
+
if axis == "off":
|
|
2470
|
+
sns.despine(top=True, right=True, left=True, bottom=True)
|
|
2471
|
+
f = f.set(xticks=[], yticks=[]).set_xlabels("").set_ylabels("")
|
|
2472
|
+
# plt.legend(frameon=True)
|
|
2473
|
+
|
|
2474
|
+
plt.title(name)
|
|
2475
|
+
|
|
2476
|
+
plt.xticks(fontsize=ticks_fontsize) # Increase x-axis label size
|
|
2477
|
+
plt.yticks(fontsize=ticks_fontsize) # Increase y-axis label size
|
|
2478
|
+
|
|
2479
|
+
plt.show()
|
|
2480
|
+
figures += [f]
|
|
2481
|
+
|
|
2482
|
+
if invert_y:
|
|
2483
|
+
df[Y] = y_orig
|
|
2484
|
+
|
|
2485
|
+
return figures
|
|
2486
|
+
|
|
2487
|
+
|
|
2488
|
+
##########
|
|
2489
|
+
|
|
2490
|
+
|
|
2491
|
+
def pl_comb_num_freq(data_list, plot_order=None, pal_tis=None, figsize=(5, 5)):
|
|
2492
|
+
df_new = []
|
|
2493
|
+
for df in data_list:
|
|
2494
|
+
df.reset_index(inplace=True)
|
|
2495
|
+
df.rename(columns={"merge": "combination"}, inplace=True)
|
|
2496
|
+
df["count"] = df["combination"].apply(len)
|
|
2497
|
+
sum_df = df.groupby("count").sum()
|
|
2498
|
+
|
|
2499
|
+
tbt = sum_df.reset_index()
|
|
2500
|
+
ttt = tbt.melt(id_vars=["count"])
|
|
2501
|
+
ttt.rename(
|
|
2502
|
+
columns={"variable": "unique_cond", "value": "fraction"}, inplace=True
|
|
2503
|
+
)
|
|
2504
|
+
df_new.append(ttt)
|
|
2505
|
+
df_exp = pd.concat(df_new)
|
|
2506
|
+
|
|
2507
|
+
df_exp[["donor", "tissue"]] = df_exp["unique_cond"].str.split("_", expand=True)
|
|
2508
|
+
|
|
2509
|
+
# swarmplot to compare
|
|
2510
|
+
plt.figure(figsize=figsize)
|
|
2511
|
+
|
|
2512
|
+
ax = sns.boxplot(
|
|
2513
|
+
data=df_exp,
|
|
2514
|
+
x="count",
|
|
2515
|
+
y="fraction",
|
|
2516
|
+
hue="tissue",
|
|
2517
|
+
dodge=True,
|
|
2518
|
+
hue_order=plot_order,
|
|
2519
|
+
palette=pal_tis,
|
|
2520
|
+
)
|
|
2521
|
+
ax = sns.swarmplot(
|
|
2522
|
+
data=df_exp,
|
|
2523
|
+
x="count",
|
|
2524
|
+
y="fraction",
|
|
2525
|
+
hue="tissue",
|
|
2526
|
+
dodge=True,
|
|
2527
|
+
hue_order=plot_order,
|
|
2528
|
+
edgecolor="black",
|
|
2529
|
+
linewidth=1,
|
|
2530
|
+
palette=pal_tis,
|
|
2531
|
+
)
|
|
2532
|
+
for patch in ax.artists:
|
|
2533
|
+
r, g, b, a = patch.get_facecolor()
|
|
2534
|
+
patch.set_facecolor((r, g, b, 0.3))
|
|
2535
|
+
# ax.set_yscale(\log\)
|
|
2536
|
+
plt.xlabel("")
|
|
2537
|
+
handles, labels = ax.get_legend_handles_labels()
|
|
2538
|
+
plt.legend(
|
|
2539
|
+
handles[: len(df_exp["tissue"].unique())],
|
|
2540
|
+
labels[: len(df_exp["tissue"].unique())],
|
|
2541
|
+
bbox_to_anchor=(1.05, 1),
|
|
2542
|
+
loc=2,
|
|
2543
|
+
borderaxespad=0.0,
|
|
2544
|
+
frameon=False,
|
|
2545
|
+
)
|
|
2546
|
+
plt.xticks(rotation=90)
|
|
2547
|
+
sns.despine(trim=True)
|
|
2548
|
+
|
|
2549
|
+
return df_exp
|
|
2550
|
+
|
|
2551
|
+
|
|
2552
|
+
##########
|
|
2553
|
+
# this function helps to determine what threshold to use for remove noises
|
|
2554
|
+
# default cut off is top 1%
|
|
2555
|
+
def zcount_thres(
|
|
2556
|
+
dfz, col_num, cut_off=0.01, count_bin=50, zsum_bin=50, figsize=(10, 5)
|
|
2557
|
+
):
|
|
2558
|
+
"""
|
|
2559
|
+
Determines the threshold to use for removing noises. The default cut off is the top 1%.
|
|
2560
|
+
|
|
2561
|
+
Parameters
|
|
2562
|
+
----------
|
|
2563
|
+
dfz : DataFrame
|
|
2564
|
+
The input data from which the threshold is to be determined.
|
|
2565
|
+
col_num : int
|
|
2566
|
+
The column number up to which the operation is performed.
|
|
2567
|
+
cut_off : float, optional
|
|
2568
|
+
The cut off percentage for the threshold. By default, it is 0.01 (1%).
|
|
2569
|
+
count_bin : int, optional
|
|
2570
|
+
The number of bins for the count histogram. By default, it is 50.
|
|
2571
|
+
zsum_bin : int, optional
|
|
2572
|
+
The number of bins for the z-score sum histogram. By default, it is 50.
|
|
2573
|
+
figsize : tuple, optional
|
|
2574
|
+
The size of the figure to be plotted. By default, it is (10, 5).
|
|
2575
|
+
|
|
2576
|
+
Returns
|
|
2577
|
+
-------
|
|
2578
|
+
None
|
|
2579
|
+
This function doesn't return anything. It plots two histograms for 'Count' and 'Zscore sum' with the cut off line.
|
|
2580
|
+
"""
|
|
2581
|
+
dfz_copy = dfz
|
|
2582
|
+
dfz_copy["Count"] = dfz.iloc[:, : col_num + 1].ge(0).sum(axis=1)
|
|
2583
|
+
dfz_copy["z_sum"] = dfz.iloc[:, : col_num + 1].sum(axis=1)
|
|
2584
|
+
fig, axes = plt.subplots(1, 2, constrained_layout=True, figsize=figsize)
|
|
2585
|
+
axes[0].hist(dfz_copy["Count"], bins=count_bin)
|
|
2586
|
+
axes[0].set_title("Count")
|
|
2587
|
+
axes[0].axvline(
|
|
2588
|
+
dfz_copy["Count"].quantile(1 - cut_off),
|
|
2589
|
+
color="k",
|
|
2590
|
+
linestyle="dashed",
|
|
2591
|
+
linewidth=1,
|
|
2592
|
+
)
|
|
2593
|
+
axes[0].text(
|
|
2594
|
+
0.75,
|
|
2595
|
+
0.75,
|
|
2596
|
+
"Cut off: {:.2f}".format(dfz_copy["Count"].quantile(1 - cut_off)),
|
|
2597
|
+
ha="right",
|
|
2598
|
+
va="bottom",
|
|
2599
|
+
transform=axes[0].transAxes,
|
|
2600
|
+
)
|
|
2601
|
+
axes[1].hist(dfz_copy["z_sum"], bins=zsum_bin)
|
|
2602
|
+
axes[1].title.set_text("Zscore sum")
|
|
2603
|
+
axes[1].axvline(
|
|
2604
|
+
dfz_copy["z_sum"].quantile(1 - cut_off),
|
|
2605
|
+
color="k",
|
|
2606
|
+
linestyle="dashed",
|
|
2607
|
+
linewidth=1,
|
|
2608
|
+
)
|
|
2609
|
+
axes[1].text(
|
|
2610
|
+
0.75,
|
|
2611
|
+
0.75,
|
|
2612
|
+
"Cut off: {:.2f}".format(dfz_copy["z_sum"].quantile(1 - cut_off)),
|
|
2613
|
+
ha="right",
|
|
2614
|
+
va="bottom",
|
|
2615
|
+
transform=axes[1].transAxes,
|
|
2616
|
+
)
|
|
2617
|
+
|
|
2618
|
+
|
|
2619
|
+
##########
|
|
2620
|
+
|
|
2621
|
+
|
|
2622
|
+
def pl_mono_cluster_spatial(
|
|
2623
|
+
df,
|
|
2624
|
+
sample_col="Sample",
|
|
2625
|
+
cluster_col="Cell Type",
|
|
2626
|
+
x="x",
|
|
2627
|
+
y="y",
|
|
2628
|
+
color_dict=None,
|
|
2629
|
+
s=3,
|
|
2630
|
+
alpha=0.5,
|
|
2631
|
+
figsize=(15, 12),
|
|
2632
|
+
):
|
|
2633
|
+
for i in df[sample_col].unique():
|
|
2634
|
+
df_sub = df[df[sample_col] == i]
|
|
2635
|
+
print(i)
|
|
2636
|
+
celltype = list(df_sub[cluster_col].unique())
|
|
2637
|
+
ncols = 4
|
|
2638
|
+
nrows = len(celltype) // ncols + (len(celltype) % ncols > 0)
|
|
2639
|
+
fig, axs = plt.subplots(nrows, ncols, figsize=figsize)
|
|
2640
|
+
plt.subplots_adjust(hspace=0.5)
|
|
2641
|
+
for ct, ax in zip(celltype, axs.ravel()):
|
|
2642
|
+
df_tmp = df_sub[df_sub[cluster_col] == ct]
|
|
2643
|
+
if color_dict == None:
|
|
2644
|
+
sns.scatterplot(
|
|
2645
|
+
x=x, y=y, data=df_tmp, hue=cluster_col, s=s, alpha=alpha, ax=ax
|
|
2646
|
+
)
|
|
2647
|
+
else:
|
|
2648
|
+
sns.scatterplot(
|
|
2649
|
+
x=x,
|
|
2650
|
+
y=y,
|
|
2651
|
+
data=df_tmp,
|
|
2652
|
+
hue=cluster_col,
|
|
2653
|
+
s=s,
|
|
2654
|
+
alpha=alpha,
|
|
2655
|
+
ax=ax,
|
|
2656
|
+
palette=color_dict,
|
|
2657
|
+
)
|
|
2658
|
+
ax.set_title(ct.upper())
|
|
2659
|
+
ax.invert_yaxis()
|
|
2660
|
+
ax.get_legend().remove()
|
|
2661
|
+
ax.set_xlabel("")
|
|
2662
|
+
plt.show()
|
|
2663
|
+
|
|
2664
|
+
|
|
2665
|
+
#########
|
|
2666
|
+
|
|
2667
|
+
|
|
2668
|
+
def pl_visualize_2D_density_plot(
|
|
2669
|
+
df,
|
|
2670
|
+
region_column,
|
|
2671
|
+
selected_region,
|
|
2672
|
+
subsetting_column,
|
|
2673
|
+
values_list,
|
|
2674
|
+
x_column,
|
|
2675
|
+
y_column,
|
|
2676
|
+
):
|
|
2677
|
+
# Subset the DataFrame based on region_column and selected_region
|
|
2678
|
+
subset_df1 = df[df[region_column] == selected_region]
|
|
2679
|
+
|
|
2680
|
+
# Subset the DataFrame based on subsetting_column and values_list
|
|
2681
|
+
subset_df2 = subset_df1[subset_df[subsetting_column].isin(values_list)]
|
|
2682
|
+
|
|
2683
|
+
# Create a 2D density plot
|
|
2684
|
+
sns.kdeplot(data=subset_df2, x=x_column, y=y_column, fill=True)
|
|
2685
|
+
|
|
2686
|
+
# Overlay the individual data points as a scatter plot
|
|
2687
|
+
sns.scatterplot(
|
|
2688
|
+
data=subset_df1, x=x_column, y=y_column, color="lightgrey", alpha=0.5
|
|
2689
|
+
)
|
|
2690
|
+
|
|
2691
|
+
# Add labels and title to the plot
|
|
2692
|
+
plt.xlabel(x_column)
|
|
2693
|
+
plt.ylabel(y_column)
|
|
2694
|
+
plt.title("2D Density Plot with Overlay")
|
|
2695
|
+
|
|
2696
|
+
# Display the plot
|
|
2697
|
+
plt.show()
|
|
2698
|
+
|
|
2699
|
+
|
|
2700
|
+
#######
|
|
2701
|
+
|
|
2702
|
+
|
|
2703
|
+
def pl_create_cluster_celltype_heatmap(dataframe, cluster_column, celltype_column):
|
|
2704
|
+
# Create a frequency table using pandas crosstab
|
|
2705
|
+
frequency_table = pd.crosstab(dataframe[cluster_column], dataframe[celltype_column])
|
|
2706
|
+
|
|
2707
|
+
# Create the heatmap using seaborn
|
|
2708
|
+
plt.figure(figsize=(20, 6)) # Set the size of the heatmap (adjust as needed)
|
|
2709
|
+
sns.heatmap(
|
|
2710
|
+
frequency_table, cmap="YlGnBu", annot=True, fmt="d"
|
|
2711
|
+
) # cmap sets the color palette
|
|
2712
|
+
|
|
2713
|
+
plt.title("Cluster-Cell Type Heatmap")
|
|
2714
|
+
plt.xlabel("Cell Types")
|
|
2715
|
+
plt.ylabel("Cluster IDs")
|
|
2716
|
+
plt.show()
|
|
2717
|
+
|
|
2718
|
+
|
|
2719
|
+
import matplotlib.pyplot as plt
|
|
2720
|
+
import pandas as pd
|
|
2721
|
+
import seaborn as sns
|
|
2722
|
+
|
|
2723
|
+
|
|
2724
|
+
def catplot(
|
|
2725
|
+
adata,
|
|
2726
|
+
color,
|
|
2727
|
+
unique_region,
|
|
2728
|
+
subset=None,
|
|
2729
|
+
X="x",
|
|
2730
|
+
Y="y",
|
|
2731
|
+
invert_y=False,
|
|
2732
|
+
size=6,
|
|
2733
|
+
alpha=1,
|
|
2734
|
+
palette=None, # default is None which means the color comes from the anndata object
|
|
2735
|
+
savefig=False,
|
|
2736
|
+
output_dir="./",
|
|
2737
|
+
output_fname="",
|
|
2738
|
+
figsize=5,
|
|
2739
|
+
style="white",
|
|
2740
|
+
axis="on",
|
|
2741
|
+
scatter_kws={},
|
|
2742
|
+
n_columns=4,
|
|
2743
|
+
legend_padding=0.2,
|
|
2744
|
+
rand_seed=1,
|
|
2745
|
+
):
|
|
2746
|
+
"""
|
|
2747
|
+
Plots cells in tissue section color coded by either cell type or node allocation.
|
|
2748
|
+
|
|
2749
|
+
Parameters
|
|
2750
|
+
----------
|
|
2751
|
+
adata : AnnData
|
|
2752
|
+
Annotated data matrix.
|
|
2753
|
+
color : str
|
|
2754
|
+
Color by "Clusterid" or "Node" respectively.
|
|
2755
|
+
unique_region : str
|
|
2756
|
+
Each region is one independent CODEX image.
|
|
2757
|
+
subset : str, optional
|
|
2758
|
+
Subset of data to plot. If None, all data is plotted.
|
|
2759
|
+
X : str, optional
|
|
2760
|
+
Column name for x-axis in the DataFrame.
|
|
2761
|
+
Y : str, optional
|
|
2762
|
+
Column name for y-axis in the DataFrame.
|
|
2763
|
+
invert_y : bool, optional
|
|
2764
|
+
If True, invert y-axis.
|
|
2765
|
+
size : int, optional
|
|
2766
|
+
Size of point to plot for each cell.
|
|
2767
|
+
alpha : float, optional
|
|
2768
|
+
Transparency of points.
|
|
2769
|
+
palette : dict, optional
|
|
2770
|
+
Colors to use for different levels of the `hue` variable. Should be something that can be interpreted by `color_palette()`, or a dictionary mapping hue levels to matplotlib colors.
|
|
2771
|
+
savefig : bool, optional
|
|
2772
|
+
If True, save figure.
|
|
2773
|
+
output_dir : str, optional
|
|
2774
|
+
Directory to save figure.
|
|
2775
|
+
output_fname : str, optional
|
|
2776
|
+
Filename to save figure.
|
|
2777
|
+
figsize : int, optional
|
|
2778
|
+
Size of the figure.
|
|
2779
|
+
style : str, optional
|
|
2780
|
+
Style of the plot.
|
|
2781
|
+
axis : str, optional
|
|
2782
|
+
If "off", axis is not displayed.
|
|
2783
|
+
scatter_kws : dict, optional
|
|
2784
|
+
Additional keyword arguments to pass to `scatterplot()`.
|
|
2785
|
+
n_columns : int, optional
|
|
2786
|
+
Number of columns in the figure.
|
|
2787
|
+
legend_padding : float, optional
|
|
2788
|
+
Padding around the legend.
|
|
2789
|
+
rand_seed : int, optional
|
|
2790
|
+
Seed for random number generator.
|
|
2791
|
+
|
|
2792
|
+
Returns
|
|
2793
|
+
-------
|
|
2794
|
+
None
|
|
2795
|
+
This function doesn't return anything. It plots a scatterplot with the specified parameters.
|
|
2796
|
+
"""
|
|
2797
|
+
scatter_kws_ = {"s": size, "alpha": alpha}
|
|
2798
|
+
scatter_kws_.update(scatter_kws)
|
|
2799
|
+
|
|
2800
|
+
df = pd.DataFrame(adata.obs[[X, Y, color, unique_region]])
|
|
2801
|
+
|
|
2802
|
+
df[color] = df[color].astype("category")
|
|
2803
|
+
if invert_y:
|
|
2804
|
+
y_orig = df[Y].values.copy()
|
|
2805
|
+
df[Y] *= -1
|
|
2806
|
+
|
|
2807
|
+
if palette is None:
|
|
2808
|
+
if color + "_colors" not in adata.uns.keys():
|
|
2809
|
+
ct_colors = hf_generate_random_colors(
|
|
2810
|
+
len(adata.obs[color].unique()), rand_seed=rand_seed
|
|
2811
|
+
)
|
|
2812
|
+
palette = dict(zip(np.sort(adata.obs[color].unique()), ct_colors))
|
|
2813
|
+
adata.uns[color + "_colors"] = ct_colors
|
|
2814
|
+
else:
|
|
2815
|
+
palette = dict(
|
|
2816
|
+
zip(np.sort(adata.obs[color].unique()), adata.uns[color + "_colors"])
|
|
2817
|
+
)
|
|
2818
|
+
|
|
2819
|
+
style = {"axes.facecolor": style}
|
|
2820
|
+
sns.set_style(style)
|
|
2821
|
+
if subset is None:
|
|
2822
|
+
region_list = list(
|
|
2823
|
+
df[unique_region].unique().sort_values()
|
|
2824
|
+
) # display all experiments
|
|
2825
|
+
else:
|
|
2826
|
+
if subset not in list(df[unique_region].unique().sort_values()):
|
|
2827
|
+
print(subset + " is not in unique_region!")
|
|
2828
|
+
return
|
|
2829
|
+
else:
|
|
2830
|
+
region_list = [subset]
|
|
2831
|
+
|
|
2832
|
+
n_rows = int(np.ceil(len(region_list) / n_columns))
|
|
2833
|
+
fig, axes = plt.subplots(
|
|
2834
|
+
n_rows,
|
|
2835
|
+
n_columns,
|
|
2836
|
+
figsize=(figsize * n_columns, figsize * n_rows),
|
|
2837
|
+
squeeze=False,
|
|
2838
|
+
gridspec_kw={"wspace": 0.5, "hspace": 0.4},
|
|
2839
|
+
)
|
|
2840
|
+
|
|
2841
|
+
for i_ax, (name, ax) in enumerate(zip(region_list, axes.flatten())):
|
|
2842
|
+
data = df[df[unique_region] == name]
|
|
2843
|
+
# print(name)
|
|
2844
|
+
sns.scatterplot(
|
|
2845
|
+
x=X, y=Y, data=data, hue=color, palette=palette, ax=ax, s=size, alpha=alpha
|
|
2846
|
+
)
|
|
2847
|
+
ax.grid(False)
|
|
2848
|
+
if axis == "off":
|
|
2849
|
+
ax.axis("off")
|
|
2850
|
+
|
|
2851
|
+
ax.set_title(name)
|
|
2852
|
+
ax.set_aspect("equal")
|
|
2853
|
+
|
|
2854
|
+
# Add padding to the legend
|
|
2855
|
+
ax.legend(loc="upper left", bbox_to_anchor=(1, 1))
|
|
2856
|
+
# frame = legend.get_frame()
|
|
2857
|
+
# frame.set_facecolor('white') # Adjust the legend background color
|
|
2858
|
+
|
|
2859
|
+
for i in range(i_ax + 1, n_rows * n_columns):
|
|
2860
|
+
axes.flatten()[i].axis("off")
|
|
2861
|
+
|
|
2862
|
+
# fig.tight_layout(pad = 0.5)
|
|
2863
|
+
|
|
2864
|
+
if savefig:
|
|
2865
|
+
fig.savefig(
|
|
2866
|
+
output_dir + output_fname + "_spatial_plot.pdf", bbox_inches="tight"
|
|
2867
|
+
)
|
|
2868
|
+
|
|
2869
|
+
|
|
2870
|
+
def pl_generate_CN_comb_map(
|
|
2871
|
+
graph,
|
|
2872
|
+
tops,
|
|
2873
|
+
e0,
|
|
2874
|
+
e1,
|
|
2875
|
+
simp_freqs,
|
|
2876
|
+
palette,
|
|
2877
|
+
figsize=(40, 20),
|
|
2878
|
+
savefig=False,
|
|
2879
|
+
output_dir="./",
|
|
2880
|
+
):
|
|
2881
|
+
draw = graph
|
|
2882
|
+
pos = nx.drawing.nx_pydot.graphviz_layout(draw, prog="dot")
|
|
2883
|
+
height = 8
|
|
2884
|
+
|
|
2885
|
+
plt.figure(figsize=figsize)
|
|
2886
|
+
for n in draw.nodes():
|
|
2887
|
+
col = "black"
|
|
2888
|
+
if len(draw.in_edges(n)) < len(n):
|
|
2889
|
+
col = "black"
|
|
2890
|
+
plt.scatter(
|
|
2891
|
+
pos[n][0],
|
|
2892
|
+
pos[n][1] - 5,
|
|
2893
|
+
s=simp_freqs[list(simp_freqs.index).index(n)] * 10000,
|
|
2894
|
+
c=col,
|
|
2895
|
+
zorder=-1,
|
|
2896
|
+
)
|
|
2897
|
+
if n in tops:
|
|
2898
|
+
plt.text(
|
|
2899
|
+
pos[n][0],
|
|
2900
|
+
pos[n][1] - 7,
|
|
2901
|
+
"*",
|
|
2902
|
+
fontsize=25,
|
|
2903
|
+
color="white",
|
|
2904
|
+
ha="center",
|
|
2905
|
+
va="center",
|
|
2906
|
+
zorder=20,
|
|
2907
|
+
)
|
|
2908
|
+
delta = 8
|
|
2909
|
+
|
|
2910
|
+
# l is just the color keys
|
|
2911
|
+
l = list(palette.keys())
|
|
2912
|
+
plt.scatter(
|
|
2913
|
+
[pos[n][0]] * len(n),
|
|
2914
|
+
[pos[n][1] + delta * (i + 1) for i in range(len(n))],
|
|
2915
|
+
c=[palette[l[i]] for i in n],
|
|
2916
|
+
marker="s",
|
|
2917
|
+
zorder=5,
|
|
2918
|
+
s=400,
|
|
2919
|
+
)
|
|
2920
|
+
|
|
2921
|
+
j = 0
|
|
2922
|
+
for e0, e1 in draw.edges():
|
|
2923
|
+
weight = 0.2
|
|
2924
|
+
alpha = 0.3
|
|
2925
|
+
color = "black"
|
|
2926
|
+
if len(draw.in_edges(e1)) < len(e1):
|
|
2927
|
+
color = "black"
|
|
2928
|
+
lw = 1
|
|
2929
|
+
weight = 0.4
|
|
2930
|
+
|
|
2931
|
+
plt.plot(
|
|
2932
|
+
[pos[e0][0], pos[e1][0]],
|
|
2933
|
+
[pos[e0][1], pos[e1][1]],
|
|
2934
|
+
color=color,
|
|
2935
|
+
linewidth=weight,
|
|
2936
|
+
alpha=alpha,
|
|
2937
|
+
zorder=-10,
|
|
2938
|
+
)
|
|
2939
|
+
|
|
2940
|
+
plt.axis("off")
|
|
2941
|
+
|
|
2942
|
+
if savefig:
|
|
2943
|
+
plt.savefig(output_dir + "_CNMap.pdf", bbox_inches="tight")
|
|
2944
|
+
else:
|
|
2945
|
+
plt.show()
|
|
2946
|
+
|
|
2947
|
+
|
|
2948
|
+
def stacked_bar_plot(
|
|
2949
|
+
adata,
|
|
2950
|
+
color,
|
|
2951
|
+
grouping,
|
|
2952
|
+
cell_list,
|
|
2953
|
+
output_dir,
|
|
2954
|
+
norm=True,
|
|
2955
|
+
savefig=False, # new
|
|
2956
|
+
output_fname="", # new
|
|
2957
|
+
col_order=None,
|
|
2958
|
+
sub_col=None,
|
|
2959
|
+
name_cat="celltype",
|
|
2960
|
+
fig_sizing=(8, 4),
|
|
2961
|
+
plot_order=None,
|
|
2962
|
+
palette=None,
|
|
2963
|
+
remove_leg=False,
|
|
2964
|
+
rand_seed=1,
|
|
2965
|
+
):
|
|
2966
|
+
"""
|
|
2967
|
+
Plot a stacked bar plot based on the given data.
|
|
2968
|
+
|
|
2969
|
+
Parameters
|
|
2970
|
+
----------
|
|
2971
|
+
data : pandas.DataFrame
|
|
2972
|
+
The input data containing the necessary information for plotting.
|
|
2973
|
+
color : str
|
|
2974
|
+
The column name representing the categories.
|
|
2975
|
+
grouping : str
|
|
2976
|
+
The column name representing the grouping.
|
|
2977
|
+
cell_list : list
|
|
2978
|
+
The list of cell types to include in the plot.
|
|
2979
|
+
output_dir : str
|
|
2980
|
+
The output directory for saving the plot.
|
|
2981
|
+
norm : bool, optional
|
|
2982
|
+
Flag indicating whether to normalize the values. Defaults to True.
|
|
2983
|
+
save_name : str, optional
|
|
2984
|
+
The name to use when saving the plot. Defaults to None.
|
|
2985
|
+
col_order : list, optional
|
|
2986
|
+
The order of columns/categories for plotting. Defaults to None.
|
|
2987
|
+
sub_col : str, optional
|
|
2988
|
+
The column name representing sub-categories. Defaults to None.
|
|
2989
|
+
name_cat : str, optional
|
|
2990
|
+
The name for the category column in the plot. Defaults to 'celltype'.
|
|
2991
|
+
fig_sizing : tuple, optional
|
|
2992
|
+
The size of the figure (width, height) in inches. Defaults to (8, 4).
|
|
2993
|
+
plot_order : list, optional
|
|
2994
|
+
The order of categories for plotting. Defaults to None.
|
|
2995
|
+
palette : dict, optional
|
|
2996
|
+
A dictionary mapping categories to colors for custom colorization. Defaults to None.
|
|
2997
|
+
remove_leg : bool, optional
|
|
2998
|
+
Flag indicating whether to remove the legend. Defaults to False.
|
|
2999
|
+
|
|
3000
|
+
Returns
|
|
3001
|
+
-------
|
|
3002
|
+
pandas.DataFrame
|
|
3003
|
+
The pivoted data used for plotting.
|
|
3004
|
+
list
|
|
3005
|
+
The order of categories used for plotting.
|
|
3006
|
+
"""
|
|
3007
|
+
|
|
3008
|
+
data = adata.obs
|
|
3009
|
+
|
|
3010
|
+
# Find Percentage of cell type
|
|
3011
|
+
if norm == True:
|
|
3012
|
+
if sub_col is None:
|
|
3013
|
+
test1 = data.loc[data[color].isin(cell_list)]
|
|
3014
|
+
sub_cell_list = list(test1[color].unique())
|
|
3015
|
+
else:
|
|
3016
|
+
test1 = data.loc[data[sub_col].isin(cell_list)]
|
|
3017
|
+
sub_cell_list = list(test1[color].unique())
|
|
3018
|
+
else:
|
|
3019
|
+
if sub_col is None:
|
|
3020
|
+
test1 = data.copy()
|
|
3021
|
+
sub_cell_list = list(data.loc[data[color].isin(cell_list)][color].unique())
|
|
3022
|
+
else:
|
|
3023
|
+
test1 = data.copy()
|
|
3024
|
+
sub_cell_list = list(
|
|
3025
|
+
data.loc[data[sub_col].isin(cell_list)][color].unique()
|
|
3026
|
+
)
|
|
3027
|
+
if palette is None:
|
|
3028
|
+
if color + "_colors" not in adata.uns.keys():
|
|
3029
|
+
ct_colors = hf_generate_random_colors(
|
|
3030
|
+
len(adata.obs[color].unique()), rand_seed=rand_seed
|
|
3031
|
+
)
|
|
3032
|
+
palette = dict(zip(np.sort(adata.obs[color].unique()), ct_colors))
|
|
3033
|
+
adata.uns[color + "_colors"] = ct_colors
|
|
3034
|
+
else:
|
|
3035
|
+
palette = dict(
|
|
3036
|
+
zip(np.sort(adata.obs[color].unique()), adata.uns[color + "_colors"])
|
|
3037
|
+
)
|
|
3038
|
+
|
|
3039
|
+
test1[color] = test1[color].astype("category")
|
|
3040
|
+
test_freq = test1.groupby(grouping).apply(
|
|
3041
|
+
lambda x: x[color].value_counts(normalize=True, sort=False) * 100
|
|
3042
|
+
)
|
|
3043
|
+
test_freq.columns = test_freq.columns.astype(str)
|
|
3044
|
+
|
|
3045
|
+
##### Can subset it here if I do not want normalized per the group
|
|
3046
|
+
test_freq.reset_index(inplace=True)
|
|
3047
|
+
sub_cell_list.append(grouping)
|
|
3048
|
+
test_freq = test_freq[sub_cell_list]
|
|
3049
|
+
melt_test = pd.melt(
|
|
3050
|
+
test_freq, id_vars=[grouping]
|
|
3051
|
+
) # , value_vars=test_freq.columns)
|
|
3052
|
+
# melt_test.rename(columns={per_cat: name_cat, "value": "percent"}, inplace=True)
|
|
3053
|
+
melt_test.rename(columns={"value": "percent"}, inplace=True)
|
|
3054
|
+
|
|
3055
|
+
if norm == True:
|
|
3056
|
+
if col_order is None:
|
|
3057
|
+
bb = melt_test.groupby([grouping, color]).sum().reset_index()
|
|
3058
|
+
col_order = (
|
|
3059
|
+
bb.loc[bb[color] == bb[color][0]]
|
|
3060
|
+
.sort_values(by="percent")[grouping]
|
|
3061
|
+
.to_list()
|
|
3062
|
+
)
|
|
3063
|
+
else:
|
|
3064
|
+
if col_order is None:
|
|
3065
|
+
col_order = (
|
|
3066
|
+
melt_test.groupby(grouping)
|
|
3067
|
+
.sum()
|
|
3068
|
+
.reset_index()
|
|
3069
|
+
.sort_values(by="percent")[grouping]
|
|
3070
|
+
.to_list()
|
|
3071
|
+
)
|
|
3072
|
+
|
|
3073
|
+
if plot_order is None:
|
|
3074
|
+
plot_order = list(melt_test[color].unique())
|
|
3075
|
+
|
|
3076
|
+
# Set up for plotting
|
|
3077
|
+
melt_test_piv = pd.pivot_table(
|
|
3078
|
+
melt_test, columns=[color], index=[grouping], values=["percent"]
|
|
3079
|
+
)
|
|
3080
|
+
melt_test_piv.columns = melt_test_piv.columns.droplevel(0)
|
|
3081
|
+
melt_test_piv.reset_index(inplace=True)
|
|
3082
|
+
melt_test_piv.set_index(grouping, inplace=True)
|
|
3083
|
+
melt_test_piv = melt_test_piv.reindex(col_order)
|
|
3084
|
+
melt_test_piv = melt_test_piv[plot_order]
|
|
3085
|
+
|
|
3086
|
+
# Get color dictionary
|
|
3087
|
+
ax1 = melt_test_piv.plot.bar(
|
|
3088
|
+
alpha=0.8,
|
|
3089
|
+
linewidth=1,
|
|
3090
|
+
color=[palette.get(x) for x in melt_test_piv.columns],
|
|
3091
|
+
figsize=fig_sizing,
|
|
3092
|
+
rot=90,
|
|
3093
|
+
stacked=True,
|
|
3094
|
+
edgecolor="black",
|
|
3095
|
+
)
|
|
3096
|
+
|
|
3097
|
+
for line in ax1.lines:
|
|
3098
|
+
line.set_color("black")
|
|
3099
|
+
ax1.spines["top"].set_visible(False)
|
|
3100
|
+
ax1.spines["right"].set_visible(False)
|
|
3101
|
+
if remove_leg == True:
|
|
3102
|
+
ax1.set_ylabel("")
|
|
3103
|
+
ax1.set_xlabel("")
|
|
3104
|
+
else:
|
|
3105
|
+
ax1.set_ylabel("percent")
|
|
3106
|
+
# ax1.spines['left'].set_position(('data', 1.0))
|
|
3107
|
+
# ax1.set_xticks(np.arange(1,melt_test.day.max()+1,1))
|
|
3108
|
+
# ax1.set_ylim([0, int(ceil(max(max(melt_test_piv.sum(axis=1)), max(tm_piv.sum(axis=1)))))])
|
|
3109
|
+
plt.xticks(
|
|
3110
|
+
list(range(len(list(melt_test_piv.index)))),
|
|
3111
|
+
list(melt_test_piv.index),
|
|
3112
|
+
rotation=90,
|
|
3113
|
+
)
|
|
3114
|
+
lgd2 = ax1.legend(
|
|
3115
|
+
loc="center left", bbox_to_anchor=(1.0, 0.5), ncol=1, frameon=False
|
|
3116
|
+
)
|
|
3117
|
+
if savefig:
|
|
3118
|
+
plt.savefig(
|
|
3119
|
+
output_dir + output_fname + ".pdf",
|
|
3120
|
+
format="pdf",
|
|
3121
|
+
dpi=300,
|
|
3122
|
+
transparent=True,
|
|
3123
|
+
bbox_inches="tight",
|
|
3124
|
+
)
|
|
3125
|
+
else:
|
|
3126
|
+
plt.show()
|
|
3127
|
+
return melt_test_piv, plot_order
|
|
3128
|
+
|
|
3129
|
+
|
|
3130
|
+
def pl_swarm_box_ad(
|
|
3131
|
+
adata,
|
|
3132
|
+
grouping,
|
|
3133
|
+
per_cat,
|
|
3134
|
+
replicate,
|
|
3135
|
+
sub_col,
|
|
3136
|
+
sub_list,
|
|
3137
|
+
output_dir,
|
|
3138
|
+
norm=True,
|
|
3139
|
+
figure_sizing=(10, 5),
|
|
3140
|
+
save_name=None,
|
|
3141
|
+
plot_order=None,
|
|
3142
|
+
col_in=None,
|
|
3143
|
+
color_dic=None,
|
|
3144
|
+
flip=False,
|
|
3145
|
+
):
|
|
3146
|
+
# extract information form adata
|
|
3147
|
+
data = adata.obs
|
|
3148
|
+
|
|
3149
|
+
# Find Percentage of cell type
|
|
3150
|
+
test = data.copy()
|
|
3151
|
+
sub_list1 = sub_list.copy()
|
|
3152
|
+
|
|
3153
|
+
if norm == True:
|
|
3154
|
+
test1 = test.loc[test[sub_col].isin(sub_list1)]
|
|
3155
|
+
immune_list = list(test1[per_cat].unique())
|
|
3156
|
+
else:
|
|
3157
|
+
test1 = test.copy()
|
|
3158
|
+
immune_list = list(test.loc[test[sub_col].isin(sub_list1)][per_cat].unique())
|
|
3159
|
+
|
|
3160
|
+
test1[per_cat] = test1[per_cat].astype("category")
|
|
3161
|
+
test_freq = test1.groupby([grouping, replicate]).apply(
|
|
3162
|
+
lambda x: x[per_cat].value_counts(normalize=True, sort=False) * 100
|
|
3163
|
+
)
|
|
3164
|
+
test_freq.columns = test_freq.columns.astype(str)
|
|
3165
|
+
test_freq.reset_index(inplace=True)
|
|
3166
|
+
immune_list.extend([grouping, replicate])
|
|
3167
|
+
test_freq1 = test_freq[immune_list]
|
|
3168
|
+
|
|
3169
|
+
melt_per_plot = pd.melt(
|
|
3170
|
+
test_freq1,
|
|
3171
|
+
id_vars=[
|
|
3172
|
+
grouping,
|
|
3173
|
+
replicate,
|
|
3174
|
+
],
|
|
3175
|
+
) # ,value_vars=immune_list)
|
|
3176
|
+
melt_per_plot.rename(columns={"value": "percentage"}, inplace=True)
|
|
3177
|
+
|
|
3178
|
+
if col_in:
|
|
3179
|
+
melt_per_plot = melt_per_plot.loc[melt_per_plot[per_cat].isin(col_in)]
|
|
3180
|
+
else:
|
|
3181
|
+
melt_per_plot = melt_per_plot
|
|
3182
|
+
|
|
3183
|
+
if plot_order is None:
|
|
3184
|
+
plot_order = list(melt_per_plot[grouping].unique())
|
|
3185
|
+
else:
|
|
3186
|
+
# Order by average
|
|
3187
|
+
plot_order = (
|
|
3188
|
+
melt_per_plot.groupby(per_cat)
|
|
3189
|
+
.mean()
|
|
3190
|
+
.reset_index()
|
|
3191
|
+
.sort_values(by="percentage")[per_cat]
|
|
3192
|
+
.to_list()
|
|
3193
|
+
)
|
|
3194
|
+
|
|
3195
|
+
# swarmplot to compare clustering
|
|
3196
|
+
plt.figure(figsize=figure_sizing)
|
|
3197
|
+
if flip == True:
|
|
3198
|
+
plt.figure(figsize=figure_sizing)
|
|
3199
|
+
if color_dic is None:
|
|
3200
|
+
ax = sns.boxplot(
|
|
3201
|
+
data=melt_per_plot,
|
|
3202
|
+
x=grouping,
|
|
3203
|
+
y="percentage",
|
|
3204
|
+
dodge=True,
|
|
3205
|
+
order=plot_order,
|
|
3206
|
+
)
|
|
3207
|
+
ax = sns.swarmplot(
|
|
3208
|
+
data=melt_per_plot,
|
|
3209
|
+
x=grouping,
|
|
3210
|
+
y="percentage",
|
|
3211
|
+
dodge=True,
|
|
3212
|
+
order=plot_order,
|
|
3213
|
+
edgecolor="black",
|
|
3214
|
+
linewidth=1,
|
|
3215
|
+
color="white",
|
|
3216
|
+
palette=color_dic,
|
|
3217
|
+
)
|
|
3218
|
+
else:
|
|
3219
|
+
ax = sns.boxplot(
|
|
3220
|
+
data=melt_per_plot,
|
|
3221
|
+
x=grouping,
|
|
3222
|
+
y="percentage",
|
|
3223
|
+
dodge=True,
|
|
3224
|
+
order=plot_order,
|
|
3225
|
+
palette=color_dic,
|
|
3226
|
+
)
|
|
3227
|
+
ax = sns.swarmplot(
|
|
3228
|
+
data=melt_per_plot,
|
|
3229
|
+
x=grouping,
|
|
3230
|
+
y="percentage",
|
|
3231
|
+
dodge=True,
|
|
3232
|
+
order=plot_order,
|
|
3233
|
+
edgecolor="black",
|
|
3234
|
+
linewidth=1,
|
|
3235
|
+
palette=color_dic,
|
|
3236
|
+
)
|
|
3237
|
+
|
|
3238
|
+
for patch in ax.artists:
|
|
3239
|
+
r, g, b, a = patch.get_facecolor()
|
|
3240
|
+
patch.set_facecolor((r, g, b, 0.3))
|
|
3241
|
+
plt.xticks(rotation=90)
|
|
3242
|
+
plt.xlabel("")
|
|
3243
|
+
plt.ylabel("")
|
|
3244
|
+
plt.title(sub_list[0])
|
|
3245
|
+
sns.despine()
|
|
3246
|
+
|
|
3247
|
+
else:
|
|
3248
|
+
if color_dic is None:
|
|
3249
|
+
ax = sns.boxplot(
|
|
3250
|
+
data=melt_per_plot,
|
|
3251
|
+
x=grouping,
|
|
3252
|
+
y="percentage",
|
|
3253
|
+
dodge=True,
|
|
3254
|
+
order=plot_order,
|
|
3255
|
+
)
|
|
3256
|
+
ax = sns.swarmplot(
|
|
3257
|
+
data=melt_per_plot,
|
|
3258
|
+
x=grouping,
|
|
3259
|
+
y="percentage",
|
|
3260
|
+
dodge=True,
|
|
3261
|
+
order=plot_order,
|
|
3262
|
+
edgecolor="black",
|
|
3263
|
+
linewidth=1,
|
|
3264
|
+
color="white",
|
|
3265
|
+
)
|
|
3266
|
+
else:
|
|
3267
|
+
ax = sns.boxplot(
|
|
3268
|
+
data=melt_per_plot,
|
|
3269
|
+
x=grouping,
|
|
3270
|
+
y="percentage",
|
|
3271
|
+
dodge=True,
|
|
3272
|
+
order=plot_order,
|
|
3273
|
+
palette=color_dic,
|
|
3274
|
+
)
|
|
3275
|
+
ax = sns.swarmplot(
|
|
3276
|
+
data=melt_per_plot,
|
|
3277
|
+
x=grouping,
|
|
3278
|
+
y="percentage",
|
|
3279
|
+
dodge=True,
|
|
3280
|
+
order=plot_order,
|
|
3281
|
+
edgecolor="black",
|
|
3282
|
+
linewidth=1,
|
|
3283
|
+
palette=color_dic,
|
|
3284
|
+
)
|
|
3285
|
+
for patch in ax.artists:
|
|
3286
|
+
r, g, b, a = patch.get_facecolor()
|
|
3287
|
+
patch.set_facecolor((r, g, b, 0.3))
|
|
3288
|
+
# ax.set_yscale(\log\)
|
|
3289
|
+
plt.xlabel("")
|
|
3290
|
+
handles, labels = ax.get_legend_handles_labels()
|
|
3291
|
+
plt.legend(
|
|
3292
|
+
handles[: len(melt_per_plot[grouping].unique())],
|
|
3293
|
+
labels[: len(melt_per_plot[grouping].unique())],
|
|
3294
|
+
bbox_to_anchor=(1.05, 1),
|
|
3295
|
+
loc=2,
|
|
3296
|
+
borderaxespad=0.0,
|
|
3297
|
+
frameon=False,
|
|
3298
|
+
)
|
|
3299
|
+
plt.xticks(rotation=90)
|
|
3300
|
+
|
|
3301
|
+
ax.set(ylim=(0, melt_per_plot["percentage"].max() + 1))
|
|
3302
|
+
sns.despine()
|
|
3303
|
+
|
|
3304
|
+
if output_dir:
|
|
3305
|
+
if save_name:
|
|
3306
|
+
plt.savefig(
|
|
3307
|
+
output_dir + save_name + "_swarm_boxplot.png",
|
|
3308
|
+
format="png",
|
|
3309
|
+
dpi=300,
|
|
3310
|
+
transparent=True,
|
|
3311
|
+
bbox_inches="tight",
|
|
3312
|
+
)
|
|
3313
|
+
else:
|
|
3314
|
+
print("define save_name")
|
|
3315
|
+
else:
|
|
3316
|
+
print("plot was not saved - to save the plot specify an output directory")
|
|
3317
|
+
return melt_per_plot
|
|
3318
|
+
|
|
3319
|
+
|
|
3320
|
+
def create_pie_charts(
|
|
3321
|
+
adata,
|
|
3322
|
+
color,
|
|
3323
|
+
grouping,
|
|
3324
|
+
plot_order=None,
|
|
3325
|
+
show_percentages=True,
|
|
3326
|
+
palette=None,
|
|
3327
|
+
savefig=False,
|
|
3328
|
+
output_fname="",
|
|
3329
|
+
output_dir="./",
|
|
3330
|
+
rand_seed=1,
|
|
3331
|
+
):
|
|
3332
|
+
"""
|
|
3333
|
+
Create pie charts for each group based on a grouping column, showing the percentage of total rows based on a
|
|
3334
|
+
count column.
|
|
3335
|
+
|
|
3336
|
+
Parameters
|
|
3337
|
+
----------
|
|
3338
|
+
adata : pd.DataFrame
|
|
3339
|
+
The input DataFrame.
|
|
3340
|
+
color : str
|
|
3341
|
+
The column name used for counting occurrences.
|
|
3342
|
+
grouping : str
|
|
3343
|
+
The column name for grouping the data.
|
|
3344
|
+
plot_order : list, optional
|
|
3345
|
+
The order of groups for plotting. Defaults to None.
|
|
3346
|
+
show_percentages : bool, optional
|
|
3347
|
+
Whether to show the percentage numbers on the pie charts. Defaults to True.
|
|
3348
|
+
palette : dict, optional
|
|
3349
|
+
A dictionary to manually set colors for neighborhoods. Defaults to None.
|
|
3350
|
+
savefig : bool, optional
|
|
3351
|
+
Whether to save the figure or not. Defaults to False.
|
|
3352
|
+
output_fname : str, optional
|
|
3353
|
+
The output file name. Defaults to "".
|
|
3354
|
+
output_dir : str, optional
|
|
3355
|
+
The output directory. Defaults to "./".
|
|
3356
|
+
rand_seed : int, optional
|
|
3357
|
+
The random seed for color generation. Defaults to 1.
|
|
3358
|
+
|
|
3359
|
+
Returns
|
|
3360
|
+
-------
|
|
3361
|
+
None
|
|
3362
|
+
"""
|
|
3363
|
+
data = adata.obs
|
|
3364
|
+
|
|
3365
|
+
# Group the data by the grouping column
|
|
3366
|
+
grouped_data = data.groupby(grouping)
|
|
3367
|
+
|
|
3368
|
+
# Sort the groups based on the plot_order if provided
|
|
3369
|
+
if plot_order:
|
|
3370
|
+
grouped_data = sorted(grouped_data, key=lambda x: plot_order.index(x[0]))
|
|
3371
|
+
|
|
3372
|
+
# Calculate the number of rows and columns for subplots
|
|
3373
|
+
num_groups = len(grouped_data)
|
|
3374
|
+
num_cols = 3 # Number of columns for subplots
|
|
3375
|
+
num_rows = (num_groups - 1) // num_cols + 1
|
|
3376
|
+
|
|
3377
|
+
# Create subplots
|
|
3378
|
+
fig, axes = plt.subplots(num_rows, num_cols, figsize=(15, 5 * num_rows))
|
|
3379
|
+
axes = axes.flatten() # Flatten the subplots array
|
|
3380
|
+
|
|
3381
|
+
# Create a color dictionary if not provided
|
|
3382
|
+
if palette is None:
|
|
3383
|
+
if color + "_colors" not in adata.uns.keys():
|
|
3384
|
+
ct_colors = hf_generate_random_colors(
|
|
3385
|
+
len(adata.obs[color].unique()), rand_seed=rand_seed
|
|
3386
|
+
)
|
|
3387
|
+
palette = dict(zip(np.sort(adata.obs[color].unique()), ct_colors))
|
|
3388
|
+
adata.uns[color + "_colors"] = ct_colors
|
|
3389
|
+
else:
|
|
3390
|
+
palette = dict(
|
|
3391
|
+
zip(np.sort(adata.obs[color].unique()), adata.uns[color + "_colors"])
|
|
3392
|
+
)
|
|
3393
|
+
|
|
3394
|
+
# Iterate over each group and create a pie chart
|
|
3395
|
+
for i, (group, group_df) in enumerate(grouped_data):
|
|
3396
|
+
# Count the occurrences of each neighborhood within the group
|
|
3397
|
+
neighborhood_counts = group_df[color].value_counts()
|
|
3398
|
+
|
|
3399
|
+
# Calculate the percentage of total rows for each neighborhood
|
|
3400
|
+
percentages = neighborhood_counts / group_df.shape[0] * 100
|
|
3401
|
+
|
|
3402
|
+
# Create a color list for neighborhoods in the count column
|
|
3403
|
+
colors = [
|
|
3404
|
+
palette.get(neighborhood, "gray") for neighborhood in percentages.index
|
|
3405
|
+
]
|
|
3406
|
+
|
|
3407
|
+
if show_percentages:
|
|
3408
|
+
wedges, texts, autotexts = axes[i].pie(
|
|
3409
|
+
percentages, labels=percentages.index, autopct="%1.1f%%", colors=colors
|
|
3410
|
+
)
|
|
3411
|
+
axes[i].set_title(f"Group: {group}")
|
|
3412
|
+
else:
|
|
3413
|
+
wedges, texts = axes[i].pie(
|
|
3414
|
+
percentages, labels=percentages.index, colors=colors
|
|
3415
|
+
)
|
|
3416
|
+
axes[i].set_title(f"Group: {group}")
|
|
3417
|
+
|
|
3418
|
+
# Remove unused subplots
|
|
3419
|
+
for j in range(num_groups, num_rows * num_cols):
|
|
3420
|
+
fig.delaxes(axes[j])
|
|
3421
|
+
|
|
3422
|
+
# Adjust spacing between subplots
|
|
3423
|
+
fig.tight_layout()
|
|
3424
|
+
if savefig:
|
|
3425
|
+
plt.savefig(
|
|
3426
|
+
output_dir + output_fname + "_piechart.pdf",
|
|
3427
|
+
format="pdf",
|
|
3428
|
+
dpi=300,
|
|
3429
|
+
transparent=True,
|
|
3430
|
+
bbox_inches="tight",
|
|
3431
|
+
)
|
|
3432
|
+
else:
|
|
3433
|
+
# Show the plot
|
|
3434
|
+
plt.show()
|
|
3435
|
+
|
|
3436
|
+
|
|
3437
|
+
def cn_exp_heatmap(
|
|
3438
|
+
adata,
|
|
3439
|
+
cluster_col,
|
|
3440
|
+
cn_col,
|
|
3441
|
+
palette=None,
|
|
3442
|
+
savefig=False,
|
|
3443
|
+
output_fname="",
|
|
3444
|
+
output_dir="./",
|
|
3445
|
+
row_clus=True,
|
|
3446
|
+
col_clus=True,
|
|
3447
|
+
rand_seed=1,
|
|
3448
|
+
):
|
|
3449
|
+
"""
|
|
3450
|
+
Create a heatmap of expression data, clustered by rows and columns.
|
|
3451
|
+
|
|
3452
|
+
Parameters
|
|
3453
|
+
----------
|
|
3454
|
+
adata : AnnData
|
|
3455
|
+
Annotated data matrix.
|
|
3456
|
+
cluster_col : str
|
|
3457
|
+
The column name for clustering the data.
|
|
3458
|
+
cn_col : str
|
|
3459
|
+
The column name for the color selection.
|
|
3460
|
+
palette : dict, optional
|
|
3461
|
+
A dictionary to manually set colors for neighborhoods. Defaults to None.
|
|
3462
|
+
figsize : tuple, optional
|
|
3463
|
+
The size of the figure. Defaults to (18, 12).
|
|
3464
|
+
savefig : bool, optional
|
|
3465
|
+
Whether to save the figure or not. Defaults to False.
|
|
3466
|
+
output_fname : str, optional
|
|
3467
|
+
The output file name. Defaults to "".
|
|
3468
|
+
output_dir : str, optional
|
|
3469
|
+
The output directory. Defaults to "./".
|
|
3470
|
+
row_clus : bool, optional
|
|
3471
|
+
Whether to cluster the rows or not. Defaults to True.
|
|
3472
|
+
col_clus : bool, optional
|
|
3473
|
+
Whether to cluster the columns or not. Defaults to True.
|
|
3474
|
+
rand_seed : int, optional
|
|
3475
|
+
The random seed for color generation. Defaults to 1.
|
|
3476
|
+
|
|
3477
|
+
Returns
|
|
3478
|
+
-------
|
|
3479
|
+
None
|
|
3480
|
+
"""
|
|
3481
|
+
data = adata.obs
|
|
3482
|
+
output_dir = pathlib.Path(output_dir)
|
|
3483
|
+
|
|
3484
|
+
if palette is None:
|
|
3485
|
+
if cn_col + "_colors" not in adata.uns.keys():
|
|
3486
|
+
# Create a color dictionary if not provided
|
|
3487
|
+
cn_colors = hf_generate_random_colors(
|
|
3488
|
+
len(adata.obs[cn_col].unique()), rand_seed=rand_seed
|
|
3489
|
+
)
|
|
3490
|
+
palette = dict(zip(np.sort(adata.obs[cn_col].unique()), cn_colors))
|
|
3491
|
+
adata.uns[cn_col + "_colors"] = cn_colors
|
|
3492
|
+
else:
|
|
3493
|
+
palette = dict(
|
|
3494
|
+
zip(np.sort(adata.obs[cn_col].unique()), adata.uns[cn_col + "_colors"])
|
|
3495
|
+
)
|
|
3496
|
+
|
|
3497
|
+
neigh_data = pd.DataFrame(
|
|
3498
|
+
{cn_col: list(palette.keys()), "color": list(palette.values())}
|
|
3499
|
+
)
|
|
3500
|
+
neigh_data.set_index(keys=cn_col, inplace=True)
|
|
3501
|
+
|
|
3502
|
+
df3 = pd.concat([data, pd.get_dummies(data[cluster_col])], axis=1)
|
|
3503
|
+
sum_cols2 = df3[cluster_col].unique()
|
|
3504
|
+
values2 = df3[sum_cols2].values
|
|
3505
|
+
cell_list = sum_cols2.copy()
|
|
3506
|
+
cell_list = cell_list.tolist()
|
|
3507
|
+
cell_list.append(cn_col)
|
|
3508
|
+
|
|
3509
|
+
subset = df3[cell_list]
|
|
3510
|
+
niche_sub = subset.groupby(cn_col).sum()
|
|
3511
|
+
niche_df = niche_sub.apply(lambda x: x / x.sum() * 10, axis=1)
|
|
3512
|
+
neigh_clusters = niche_df.to_numpy()
|
|
3513
|
+
|
|
3514
|
+
tissue_avgs = values2.mean(axis=0)
|
|
3515
|
+
|
|
3516
|
+
fc_2 = np.log2(
|
|
3517
|
+
(
|
|
3518
|
+
(neigh_clusters + tissue_avgs)
|
|
3519
|
+
/ (neigh_clusters + tissue_avgs).sum(axis=1, keepdims=True)
|
|
3520
|
+
)
|
|
3521
|
+
/ tissue_avgs
|
|
3522
|
+
)
|
|
3523
|
+
fc_2 = pd.DataFrame(fc_2, columns=sum_cols2)
|
|
3524
|
+
fc_2.set_index(niche_df.index, inplace=True)
|
|
3525
|
+
s = sns.clustermap(
|
|
3526
|
+
fc_2,
|
|
3527
|
+
vmin=-3,
|
|
3528
|
+
vmax=3,
|
|
3529
|
+
cmap="bwr",
|
|
3530
|
+
figsize=(10, 5),
|
|
3531
|
+
row_colors=[neigh_data.reindex(fc_2.index)["color"]],
|
|
3532
|
+
cbar_pos=(0.03, 0.06, 0.03, 0.1),
|
|
3533
|
+
)
|
|
3534
|
+
|
|
3535
|
+
s.ax_row_dendrogram.set_visible(row_clus)
|
|
3536
|
+
s.ax_col_dendrogram.set_visible(col_clus)
|
|
3537
|
+
s.ax_heatmap.set_ylabel("", labelpad=25)
|
|
3538
|
+
s.ax_heatmap.tick_params(axis="y", pad=42)
|
|
3539
|
+
s.ax_heatmap.yaxis.set_ticks_position("right")
|
|
3540
|
+
|
|
3541
|
+
# add text to bottom left corner of the plot
|
|
3542
|
+
s.ax_heatmap.text(
|
|
3543
|
+
-0.25,
|
|
3544
|
+
-0.85,
|
|
3545
|
+
"log2 fold change \nover tissue average",
|
|
3546
|
+
transform=s.ax_heatmap.transAxes,
|
|
3547
|
+
fontsize=12,
|
|
3548
|
+
verticalalignment="bottom",
|
|
3549
|
+
horizontalalignment="center",
|
|
3550
|
+
)
|
|
3551
|
+
|
|
3552
|
+
if savefig:
|
|
3553
|
+
s.figure.savefig(output_dir / (output_fname + ".pdf"), bbox_inches="tight")
|
|
3554
|
+
|
|
3555
|
+
|
|
3556
|
+
def pl_area_nuc_cutoff(
|
|
3557
|
+
df,
|
|
3558
|
+
cutoff_area,
|
|
3559
|
+
cutoff_nuc,
|
|
3560
|
+
cellsize_column="area",
|
|
3561
|
+
nuc_marker_column="Hoechst1",
|
|
3562
|
+
color_by="unique_label",
|
|
3563
|
+
palette="Paired",
|
|
3564
|
+
alpha=0.8,
|
|
3565
|
+
size=0.4,
|
|
3566
|
+
log_scale=True,
|
|
3567
|
+
):
|
|
3568
|
+
# Custom the inside plot: options are: “scatter” | “reg” | “resid” | “kde” | “hex”
|
|
3569
|
+
g = sns.jointplot(
|
|
3570
|
+
x=df[nuc_marker_column],
|
|
3571
|
+
y=df[cellsize_column],
|
|
3572
|
+
hue=df[color_by],
|
|
3573
|
+
palette=palette,
|
|
3574
|
+
alpha=alpha,
|
|
3575
|
+
)
|
|
3576
|
+
|
|
3577
|
+
if log_scale == True:
|
|
3578
|
+
# log scale joint plot
|
|
3579
|
+
g.ax_joint.set_xscale("log")
|
|
3580
|
+
g.ax_joint.set_yscale("log")
|
|
3581
|
+
|
|
3582
|
+
# add horizontal and vertical lines
|
|
3583
|
+
g.ax_joint.axhline(cutoff_area, color="k", linestyle="dashed", linewidth=1)
|
|
3584
|
+
g.ax_joint.axvline(cutoff_nuc, color="k", linestyle="dashed", linewidth=1)
|
|
3585
|
+
|
|
3586
|
+
# place legend outside
|
|
3587
|
+
g.ax_joint.legend(bbox_to_anchor=(1.2, 1), loc="upper left", borderaxespad=0)
|
|
3588
|
+
|
|
3589
|
+
# show plot
|
|
3590
|
+
plt.show()
|
|
3591
|
+
|
|
3592
|
+
|
|
3593
|
+
def pl_plot_scatter_correlation(data, x, y, xlabel=None, ylabel=None, save_path=None):
|
|
3594
|
+
g = sns.lmplot(x=x, y=y, data=data, height=5, aspect=1)
|
|
3595
|
+
g.map_dataframe(hf_annotate_cor_plot, x=x, y=y, data=data)
|
|
3596
|
+
|
|
3597
|
+
if xlabel:
|
|
3598
|
+
plt.xlabel(xlabel, fontsize=14)
|
|
3599
|
+
if ylabel:
|
|
3600
|
+
plt.ylabel(ylabel, fontsize=14)
|
|
3601
|
+
|
|
3602
|
+
plt.xticks(fontsize=14)
|
|
3603
|
+
plt.yticks(fontsize=14)
|
|
3604
|
+
|
|
3605
|
+
if save_path:
|
|
3606
|
+
plt.savefig(
|
|
3607
|
+
save_path + "_corrplot.pdf", transparent=True, dpi=600, bbox_inches="tight"
|
|
3608
|
+
)
|
|
3609
|
+
plt.show()
|
|
3610
|
+
|
|
3611
|
+
|
|
3612
|
+
def pl_plot_scatter_correlation_ad(
|
|
3613
|
+
adata, x, y, xlabel=None, ylabel=None, save_path=None
|
|
3614
|
+
):
|
|
3615
|
+
data = adata.obs
|
|
3616
|
+
|
|
3617
|
+
g = sns.lmplot(x=x, y=y, data=data, height=5, aspect=1)
|
|
3618
|
+
g.map_dataframe(hf_annotate_cor_plot, x=x, y=y, data=data)
|
|
3619
|
+
|
|
3620
|
+
if xlabel:
|
|
3621
|
+
plt.xlabel(xlabel, fontsize=14)
|
|
3622
|
+
if ylabel:
|
|
3623
|
+
plt.ylabel(ylabel, fontsize=14)
|
|
3624
|
+
|
|
3625
|
+
plt.xticks(fontsize=14)
|
|
3626
|
+
plt.yticks(fontsize=14)
|
|
3627
|
+
|
|
3628
|
+
if save_path:
|
|
3629
|
+
plt.savefig(
|
|
3630
|
+
save_path + "_corrplot.pdf", transparent=True, dpi=600, bbox_inches="tight"
|
|
3631
|
+
)
|
|
3632
|
+
plt.show()
|
|
3633
|
+
|
|
3634
|
+
|
|
3635
|
+
########
|
|
3636
|
+
|
|
3637
|
+
|
|
3638
|
+
def pl_plot_correlation_matrix(cmat):
|
|
3639
|
+
# plot correlation matrix as heatmap
|
|
3640
|
+
# Create a mask to hide the upper triangle
|
|
3641
|
+
mask = np.triu(np.ones_like(cmat, dtype=bool))
|
|
3642
|
+
|
|
3643
|
+
fig, ax = plt.subplots(figsize=(20, 20))
|
|
3644
|
+
sns.heatmap(
|
|
3645
|
+
cmat, annot=True, fmt=".2f", cmap="coolwarm", square=True, mask=mask, ax=ax
|
|
3646
|
+
)
|
|
3647
|
+
plt.show()
|
|
3648
|
+
|
|
3649
|
+
|
|
3650
|
+
def dumbbell(
|
|
3651
|
+
data,
|
|
3652
|
+
figsize=(10, 10),
|
|
3653
|
+
colors=["#DB444B", "#006BA2"],
|
|
3654
|
+
savefig=False,
|
|
3655
|
+
output_fname="",
|
|
3656
|
+
output_dir="./",
|
|
3657
|
+
):
|
|
3658
|
+
"""
|
|
3659
|
+
Create a dumbbell plot.
|
|
3660
|
+
|
|
3661
|
+
Parameters
|
|
3662
|
+
----------
|
|
3663
|
+
data : pd.DataFrame
|
|
3664
|
+
The input DataFrame. The DataFrame should have two columns representing two different conditions.
|
|
3665
|
+
figsize : tuple, optional
|
|
3666
|
+
The size of the figure. Defaults to (10, 10).
|
|
3667
|
+
colors : list, optional
|
|
3668
|
+
The colors to use for the two conditions. Defaults to ["#DB444B", "#006BA2"].
|
|
3669
|
+
|
|
3670
|
+
Returns
|
|
3671
|
+
-------
|
|
3672
|
+
None
|
|
3673
|
+
"""
|
|
3674
|
+
fig, ax = plt.subplots(figsize=figsize, facecolor="white")
|
|
3675
|
+
# plot each country one at a time
|
|
3676
|
+
|
|
3677
|
+
# Create grid
|
|
3678
|
+
# Zorder tells it which layer to put it on. We are setting this to 1 and our data to 2 so the grid is behind the data.
|
|
3679
|
+
ax.grid(which="major", axis="both", color="#758D99", alpha=0.6, zorder=1)
|
|
3680
|
+
|
|
3681
|
+
# Remove splines. Can be done one at a time or can slice with a list.
|
|
3682
|
+
ax.spines[["top", "right", "bottom"]].set_visible(False)
|
|
3683
|
+
|
|
3684
|
+
# Plot data
|
|
3685
|
+
comp_cat = data.columns
|
|
3686
|
+
|
|
3687
|
+
# Plot horizontal lines first
|
|
3688
|
+
ax.hlines(
|
|
3689
|
+
y=data.index,
|
|
3690
|
+
xmin=data[comp_cat[0]],
|
|
3691
|
+
xmax=data[comp_cat[1]],
|
|
3692
|
+
color="#758D99",
|
|
3693
|
+
zorder=2,
|
|
3694
|
+
linewidth=2,
|
|
3695
|
+
label="_nolegend_",
|
|
3696
|
+
alpha=0.8,
|
|
3697
|
+
)
|
|
3698
|
+
# Plot bubbles next
|
|
3699
|
+
ax.scatter(
|
|
3700
|
+
data[comp_cat[0]], data.index, label="2014", s=60, color=colors[0], zorder=3
|
|
3701
|
+
)
|
|
3702
|
+
ax.scatter(
|
|
3703
|
+
data[comp_cat[1]], data.index, label="2018", s=60, color=colors[1], zorder=3
|
|
3704
|
+
)
|
|
3705
|
+
|
|
3706
|
+
# Set xlim
|
|
3707
|
+
# ax.set_xlim(-3, 3)
|
|
3708
|
+
|
|
3709
|
+
# Reformat x-axis tick labels
|
|
3710
|
+
|
|
3711
|
+
ax.xaxis.set_tick_params(
|
|
3712
|
+
labeltop=True, # Put x-axis labels on top
|
|
3713
|
+
labelbottom=False, # Set no x-axis labels on bottom
|
|
3714
|
+
bottom=False, # Set no ticks on bottom
|
|
3715
|
+
labelsize=11, # Set tick label size
|
|
3716
|
+
pad=-1,
|
|
3717
|
+
) # Lower tick labels a bit
|
|
3718
|
+
|
|
3719
|
+
ax.axvline(x=0, color="k", linestyle="--")
|
|
3720
|
+
|
|
3721
|
+
# Set Legend
|
|
3722
|
+
ax.legend(
|
|
3723
|
+
data.columns,
|
|
3724
|
+
loc=(0, 1.076),
|
|
3725
|
+
ncol=2,
|
|
3726
|
+
frameon=False,
|
|
3727
|
+
handletextpad=0.4,
|
|
3728
|
+
handleheight=1,
|
|
3729
|
+
)
|
|
3730
|
+
|
|
3731
|
+
if savefig == True:
|
|
3732
|
+
plt.savefig(output_dir + output_fname + ".pdf", bbox_inches="tight")
|
|
3733
|
+
|
|
3734
|
+
|
|
3735
|
+
def plot_top_n_distances(
|
|
3736
|
+
dist_table_filt,
|
|
3737
|
+
dist_data_filt,
|
|
3738
|
+
n=5,
|
|
3739
|
+
colors=None,
|
|
3740
|
+
dodge=False,
|
|
3741
|
+
savefig=False,
|
|
3742
|
+
output_fname="",
|
|
3743
|
+
output_dir="./",
|
|
3744
|
+
figsize=(5, 5),
|
|
3745
|
+
unit="px",
|
|
3746
|
+
errorbars=True,
|
|
3747
|
+
):
|
|
3748
|
+
# Calculate the aspect ratio based on the desired figure size
|
|
3749
|
+
aspect = figsize[0] / figsize[1]
|
|
3750
|
+
|
|
3751
|
+
# calculate abs distance
|
|
3752
|
+
dist_table_filt["abs_dist"] = abs(
|
|
3753
|
+
dist_table_filt.iloc[:, 0] - dist_table_filt.iloc[:, 1]
|
|
3754
|
+
)
|
|
3755
|
+
|
|
3756
|
+
# replace with the number of combinations you want
|
|
3757
|
+
top_n_combinations = dist_table_filt.nlargest(n, "abs_dist")
|
|
3758
|
+
|
|
3759
|
+
print(top_n_combinations)
|
|
3760
|
+
|
|
3761
|
+
# Convert index of top_n_combinations to a set
|
|
3762
|
+
top_pairs = set(top_n_combinations.index)
|
|
3763
|
+
|
|
3764
|
+
# Filter dist_data_filt
|
|
3765
|
+
top_dist_data_filt = dist_data_filt[dist_data_filt["pairs"].isin(top_pairs)]
|
|
3766
|
+
|
|
3767
|
+
exploded_df = top_dist_data_filt.explode("observed")
|
|
3768
|
+
|
|
3769
|
+
# Draw a pointplot to show pulse as a function of three categorical factors
|
|
3770
|
+
if errorbars == True:
|
|
3771
|
+
g = sns.catplot(
|
|
3772
|
+
data=exploded_df,
|
|
3773
|
+
x="condition",
|
|
3774
|
+
y="observed",
|
|
3775
|
+
hue="interaction",
|
|
3776
|
+
capsize=0.2,
|
|
3777
|
+
palette=colors,
|
|
3778
|
+
errorbar="se",
|
|
3779
|
+
kind="point",
|
|
3780
|
+
height=figsize[1],
|
|
3781
|
+
aspect=aspect,
|
|
3782
|
+
dodge=dodge,
|
|
3783
|
+
)
|
|
3784
|
+
else:
|
|
3785
|
+
g = sns.catplot(
|
|
3786
|
+
data=exploded_df,
|
|
3787
|
+
x="condition",
|
|
3788
|
+
y="observed",
|
|
3789
|
+
hue="interaction",
|
|
3790
|
+
capsize=0.2,
|
|
3791
|
+
palette=colors,
|
|
3792
|
+
kind="point",
|
|
3793
|
+
height=figsize[1],
|
|
3794
|
+
aspect=aspect,
|
|
3795
|
+
dodge=dodge,
|
|
3796
|
+
ci=None,
|
|
3797
|
+
)
|
|
3798
|
+
|
|
3799
|
+
# change y axis name to "observed distance"
|
|
3800
|
+
g.set_axis_labels("Condition", "Observed distance in " + unit)
|
|
3801
|
+
|
|
3802
|
+
g.despine(left=True)
|
|
3803
|
+
|
|
3804
|
+
if savefig == True:
|
|
3805
|
+
plt.savefig(output_dir + output_fname + ".pdf", bbox_inches="tight")
|
|
3806
|
+
|
|
3807
|
+
|
|
3808
|
+
def cn_map(
|
|
3809
|
+
adata,
|
|
3810
|
+
cnmap_dict,
|
|
3811
|
+
cn_col,
|
|
3812
|
+
palette=None,
|
|
3813
|
+
figsize=(40, 20),
|
|
3814
|
+
savefig=False,
|
|
3815
|
+
output_fname="",
|
|
3816
|
+
output_dir="./",
|
|
3817
|
+
rand_seed=1,
|
|
3818
|
+
):
|
|
3819
|
+
"""
|
|
3820
|
+
Generates a CNMap plot using the provided data and parameters.
|
|
3821
|
+
|
|
3822
|
+
Parameters
|
|
3823
|
+
----------
|
|
3824
|
+
adata : anndata.AnnData
|
|
3825
|
+
Annotated data matrix.
|
|
3826
|
+
cnmap_dict : dict
|
|
3827
|
+
Dictionary containing graph, tops, e0, e1, and simp_freqs.
|
|
3828
|
+
cn_col : str
|
|
3829
|
+
Column name in adata to be used for color coding.
|
|
3830
|
+
palette : dict, optional
|
|
3831
|
+
Color palette to use for the plot. If None, a random color palette is generated.
|
|
3832
|
+
figsize : tuple, optional
|
|
3833
|
+
Size of the figure. Defaults to (40, 20).
|
|
3834
|
+
savefig : bool, optional
|
|
3835
|
+
Whether to save the figure or not. Defaults to False.
|
|
3836
|
+
output_fname : str, optional
|
|
3837
|
+
The filename for the saved figure. Required if savefig is True. Defaults to "".
|
|
3838
|
+
output_dir : str, optional
|
|
3839
|
+
The directory where the figure will be saved. Defaults to "./".
|
|
3840
|
+
rand_seed : int, optional
|
|
3841
|
+
Seed for random number generator. Defaults to 1.
|
|
3842
|
+
|
|
3843
|
+
Returns
|
|
3844
|
+
-------
|
|
3845
|
+
None
|
|
3846
|
+
"""
|
|
3847
|
+
graph = cnmap_dict["g"]
|
|
3848
|
+
tops = cnmap_dict["tops"]
|
|
3849
|
+
e0 = cnmap_dict["e0"]
|
|
3850
|
+
e1 = cnmap_dict["e1"]
|
|
3851
|
+
simp_freqs = cnmap_dict["simp_freqs"]
|
|
3852
|
+
draw = graph
|
|
3853
|
+
pos = nx.drawing.nx_pydot.graphviz_layout(draw, prog="dot")
|
|
3854
|
+
height = 8
|
|
3855
|
+
|
|
3856
|
+
# generate color
|
|
3857
|
+
cn_colors = hf_generate_random_colors(
|
|
3858
|
+
len(adata.obs[cn_col].unique()), rand_seed=rand_seed
|
|
3859
|
+
)
|
|
3860
|
+
if palette is None:
|
|
3861
|
+
if cn_col + "_colors" not in adata.uns.keys():
|
|
3862
|
+
palette = dict(zip(np.sort(adata.obs[cn_col].unique()), cn_colors))
|
|
3863
|
+
adata.uns[cn_col + "_colors"] = cn_colors
|
|
3864
|
+
else:
|
|
3865
|
+
palette = dict(
|
|
3866
|
+
zip(np.sort(adata.obs[cn_col].unique()), adata.uns[cn_col + "_colors"])
|
|
3867
|
+
)
|
|
3868
|
+
|
|
3869
|
+
plt.figure(figsize=figsize)
|
|
3870
|
+
# Sort the nodes
|
|
3871
|
+
sorted_nodes = sorted(draw.nodes())
|
|
3872
|
+
|
|
3873
|
+
# Iterate over the sorted nodes
|
|
3874
|
+
for n in sorted_nodes:
|
|
3875
|
+
col = "black"
|
|
3876
|
+
if len(draw.in_edges(n)) < len(n):
|
|
3877
|
+
col = "black"
|
|
3878
|
+
plt.scatter(
|
|
3879
|
+
pos[n][0],
|
|
3880
|
+
pos[n][1] - 5,
|
|
3881
|
+
s=simp_freqs[list(simp_freqs.index).index(n)] * 10000,
|
|
3882
|
+
c=col,
|
|
3883
|
+
zorder=-1,
|
|
3884
|
+
)
|
|
3885
|
+
# Dummy scatter plots for legend
|
|
3886
|
+
freqs = simp_freqs * 10000
|
|
3887
|
+
max_size = max(freqs)
|
|
3888
|
+
sizes = [
|
|
3889
|
+
round(max_size) / 4,
|
|
3890
|
+
round(max_size) / 2,
|
|
3891
|
+
round(max_size),
|
|
3892
|
+
] # Replace with the sizes you want in the legend
|
|
3893
|
+
labels = [
|
|
3894
|
+
str(round(max_size / 100) / 4) + "%",
|
|
3895
|
+
str(round(max_size / 100) / 2) + "%",
|
|
3896
|
+
str(round(max_size / 100)) + "%",
|
|
3897
|
+
] # Replace with the labels you want in the legend
|
|
3898
|
+
|
|
3899
|
+
# Add legend
|
|
3900
|
+
legend_elements = [
|
|
3901
|
+
plt.Line2D(
|
|
3902
|
+
[0],
|
|
3903
|
+
[0],
|
|
3904
|
+
marker="o",
|
|
3905
|
+
color="w",
|
|
3906
|
+
label=label,
|
|
3907
|
+
markerfacecolor="black",
|
|
3908
|
+
markersize=size**0.5,
|
|
3909
|
+
)
|
|
3910
|
+
for size, label in zip(sizes, labels)
|
|
3911
|
+
]
|
|
3912
|
+
|
|
3913
|
+
# Add first legend
|
|
3914
|
+
legend1 = plt.legend(
|
|
3915
|
+
handles=legend_elements,
|
|
3916
|
+
loc="lower right",
|
|
3917
|
+
title="Total frequency",
|
|
3918
|
+
title_fontsize=30,
|
|
3919
|
+
fontsize=30,
|
|
3920
|
+
handlelength=6,
|
|
3921
|
+
handletextpad=1,
|
|
3922
|
+
bbox_to_anchor=(0.0, -0.15, 1.0, 0.102),
|
|
3923
|
+
)
|
|
3924
|
+
|
|
3925
|
+
if n in tops:
|
|
3926
|
+
plt.text(
|
|
3927
|
+
pos[n][0],
|
|
3928
|
+
pos[n][1] - 7,
|
|
3929
|
+
"*",
|
|
3930
|
+
fontsize=25,
|
|
3931
|
+
color="white",
|
|
3932
|
+
ha="center",
|
|
3933
|
+
va="center",
|
|
3934
|
+
zorder=20,
|
|
3935
|
+
)
|
|
3936
|
+
delta = 8
|
|
3937
|
+
|
|
3938
|
+
# l is just the color keys
|
|
3939
|
+
l = list(palette.keys())
|
|
3940
|
+
plt.scatter(
|
|
3941
|
+
[pos[n][0]] * len(n),
|
|
3942
|
+
[pos[n][1] + delta * (i + 1) for i in range(len(n))],
|
|
3943
|
+
c=[palette[l[i]] for i in n],
|
|
3944
|
+
marker="s",
|
|
3945
|
+
zorder=5,
|
|
3946
|
+
s=1000,
|
|
3947
|
+
)
|
|
3948
|
+
|
|
3949
|
+
j = 0
|
|
3950
|
+
for e0, e1 in draw.edges():
|
|
3951
|
+
weight = 2
|
|
3952
|
+
alpha = 0.3
|
|
3953
|
+
color = "black"
|
|
3954
|
+
if len(draw.in_edges(e1)) < len(e1):
|
|
3955
|
+
color = "black"
|
|
3956
|
+
lw = 1
|
|
3957
|
+
weight = 3
|
|
3958
|
+
|
|
3959
|
+
plt.plot(
|
|
3960
|
+
[pos[e0][0], pos[e1][0]],
|
|
3961
|
+
[pos[e0][1], pos[e1][1]],
|
|
3962
|
+
color=color,
|
|
3963
|
+
linewidth=weight,
|
|
3964
|
+
alpha=alpha,
|
|
3965
|
+
zorder=-10,
|
|
3966
|
+
)
|
|
3967
|
+
|
|
3968
|
+
# Create a list of Patch objects, one for each unique color in your palette
|
|
3969
|
+
legend_patches = [
|
|
3970
|
+
mpatches.Patch(color=color, label=label) for label, color in palette.items()
|
|
3971
|
+
]
|
|
3972
|
+
|
|
3973
|
+
# Add legend to bottom of plot
|
|
3974
|
+
plt.gca().add_artist(legend1)
|
|
3975
|
+
plt.legend(
|
|
3976
|
+
handles=legend_patches,
|
|
3977
|
+
bbox_to_anchor=(0.0, -0.15, 1.0, 0.102),
|
|
3978
|
+
loc="lower left",
|
|
3979
|
+
ncol=3,
|
|
3980
|
+
borderaxespad=0.0,
|
|
3981
|
+
fontsize=35,
|
|
3982
|
+
)
|
|
3983
|
+
|
|
3984
|
+
plt.axis("off")
|
|
3985
|
+
|
|
3986
|
+
if savefig:
|
|
3987
|
+
plt.savefig(output_dir + output_fname + "_CNMap.pdf", bbox_inches="tight")
|
|
3988
|
+
else:
|
|
3989
|
+
plt.show()
|
|
3990
|
+
|
|
3991
|
+
|
|
3992
|
+
def coordinates_on_image(
|
|
3993
|
+
df,
|
|
3994
|
+
overlay_data,
|
|
3995
|
+
color=None,
|
|
3996
|
+
x="x",
|
|
3997
|
+
y="y",
|
|
3998
|
+
fig_width=20,
|
|
3999
|
+
fig_height=20,
|
|
4000
|
+
dot_size=10,
|
|
4001
|
+
convert_to_grey=True,
|
|
4002
|
+
scale=False,
|
|
4003
|
+
cmap="inferno",
|
|
4004
|
+
savefig=False,
|
|
4005
|
+
output_dir="./",
|
|
4006
|
+
output_fname="",
|
|
4007
|
+
):
|
|
4008
|
+
"""
|
|
4009
|
+
Plot coordinates on an image.
|
|
4010
|
+
|
|
4011
|
+
Parameters
|
|
4012
|
+
----------
|
|
4013
|
+
df : pd.DataFrame
|
|
4014
|
+
The input DataFrame. The DataFrame should have columns 'x' and 'y' representing the coordinates.
|
|
4015
|
+
overlay_data : ndarray
|
|
4016
|
+
The image data to overlay the coordinates on.
|
|
4017
|
+
color : str, optional
|
|
4018
|
+
The column name in df for the color variable. Defaults to None.
|
|
4019
|
+
x : str, optional
|
|
4020
|
+
The column name in df for the x-coordinate. Defaults to "x".
|
|
4021
|
+
y : str, optional
|
|
4022
|
+
The column name in df for the y-coordinate. Defaults to "y".
|
|
4023
|
+
fig_width : int, optional
|
|
4024
|
+
The width of the figure. Defaults to 20.
|
|
4025
|
+
fig_height : int, optional
|
|
4026
|
+
The height of the figure. Defaults to 20.
|
|
4027
|
+
dot_size : int, optional
|
|
4028
|
+
The size of the dots representing the coordinates. Defaults to 10.
|
|
4029
|
+
convert_to_grey : bool, optional
|
|
4030
|
+
Whether to convert the image to grayscale. Defaults to True.
|
|
4031
|
+
scale : bool, optional
|
|
4032
|
+
Whether to scale the color variable. Defaults to False.
|
|
4033
|
+
cmap : str, optional
|
|
4034
|
+
The colormap to use. Defaults to "inferno".
|
|
4035
|
+
savefig : bool, optional
|
|
4036
|
+
Whether to save the figure or not. Defaults to False.
|
|
4037
|
+
output_dir : str, optional
|
|
4038
|
+
The output directory. Defaults to "./".
|
|
4039
|
+
output_fname : str, optional
|
|
4040
|
+
The output file name. Defaults to "".
|
|
4041
|
+
|
|
4042
|
+
Returns
|
|
4043
|
+
-------
|
|
4044
|
+
None
|
|
4045
|
+
"""
|
|
4046
|
+
# Create a new figure with increased size
|
|
4047
|
+
plt.figure(figsize=(fig_width, fig_height))
|
|
4048
|
+
|
|
4049
|
+
if convert_to_grey:
|
|
4050
|
+
# Convert the image to grayscale
|
|
4051
|
+
overlay_data = skimage.color.rgb2gray(overlay_data)
|
|
4052
|
+
plt.imshow(overlay_data, cmap="gray")
|
|
4053
|
+
|
|
4054
|
+
else:
|
|
4055
|
+
plt.imshow(overlay_data)
|
|
4056
|
+
|
|
4057
|
+
image_width, image_height = overlay_data.shape[1], overlay_data.shape[0]
|
|
4058
|
+
|
|
4059
|
+
# Plot the coordinates on top of the image
|
|
4060
|
+
# colorscale by area
|
|
4061
|
+
|
|
4062
|
+
if color != None:
|
|
4063
|
+
if scale:
|
|
4064
|
+
# minmax scale the variable
|
|
4065
|
+
df[color] = (df[color] - df[color].min()) / (
|
|
4066
|
+
df[color].max() - df[color].min()
|
|
4067
|
+
)
|
|
4068
|
+
# change dot size based on variable
|
|
4069
|
+
plt.scatter(df[x], df[y], s=df[color] * 30, c=df[color], cmap=cmap)
|
|
4070
|
+
else:
|
|
4071
|
+
plt.scatter(df[x], df[y], c=df[color], s=dot_size, cmap=cmap)
|
|
4072
|
+
|
|
4073
|
+
else:
|
|
4074
|
+
plt.scatter(df[x], df["y"], s=dot_size)
|
|
4075
|
+
|
|
4076
|
+
# add colorbar
|
|
4077
|
+
plt.colorbar()
|
|
4078
|
+
|
|
4079
|
+
# set axis limits
|
|
4080
|
+
plt.xlim(0, image_width)
|
|
4081
|
+
plt.ylim(image_height, 0)
|
|
4082
|
+
|
|
4083
|
+
# Show the plot
|
|
4084
|
+
if savefig:
|
|
4085
|
+
plt.savefig(
|
|
4086
|
+
output_dir + output_fname + "_seg_masks_overlay.pdf", bbox_inches="tight"
|
|
4087
|
+
)
|
|
4088
|
+
else:
|
|
4089
|
+
plt.show()
|
|
4090
|
+
|
|
4091
|
+
|
|
4092
|
+
def count_patch_proximity_res(
|
|
4093
|
+
adata,
|
|
4094
|
+
x,
|
|
4095
|
+
hue,
|
|
4096
|
+
palette="Set3",
|
|
4097
|
+
order=True,
|
|
4098
|
+
key_name="ppa_result",
|
|
4099
|
+
savefig=False,
|
|
4100
|
+
output_dir="./",
|
|
4101
|
+
output_fname="",
|
|
4102
|
+
):
|
|
4103
|
+
"""
|
|
4104
|
+
Create a count plot for patch proximity results.
|
|
4105
|
+
|
|
4106
|
+
Parameters
|
|
4107
|
+
----------
|
|
4108
|
+
adata : AnnData
|
|
4109
|
+
Annotated data matrix.
|
|
4110
|
+
x : str
|
|
4111
|
+
The column name in the DataFrame for the x-axis variable.
|
|
4112
|
+
hue : str
|
|
4113
|
+
The column name in the DataFrame for the hue variable.
|
|
4114
|
+
palette : str, optional
|
|
4115
|
+
The palette to use for the plot. Defaults to "Set3".
|
|
4116
|
+
order : bool, optional
|
|
4117
|
+
Whether to order the count plot. Defaults to True.
|
|
4118
|
+
key_name : str, optional
|
|
4119
|
+
The key name for the patch proximity results in adata.uns. Defaults to "ppa_result".
|
|
4120
|
+
savefig : bool, optional
|
|
4121
|
+
Whether to save the figure or not. Defaults to False.
|
|
4122
|
+
output_dir : str, optional
|
|
4123
|
+
The output directory. Defaults to "./".
|
|
4124
|
+
output_fname : str, optional
|
|
4125
|
+
The output file name. Defaults to "".
|
|
4126
|
+
|
|
4127
|
+
Returns
|
|
4128
|
+
-------
|
|
4129
|
+
None
|
|
4130
|
+
"""
|
|
4131
|
+
region_results = adata.uns[key_name]
|
|
4132
|
+
ax = sns.countplot(
|
|
4133
|
+
x=x,
|
|
4134
|
+
hue=hue,
|
|
4135
|
+
data=region_results,
|
|
4136
|
+
palette=palette,
|
|
4137
|
+
order=region_results[x].value_counts().index,
|
|
4138
|
+
)
|
|
4139
|
+
|
|
4140
|
+
tick_positions = range(len(region_results[x].value_counts()))
|
|
4141
|
+
tick_labels = region_results[x].value_counts().index
|
|
4142
|
+
ax.set_xticks(tick_positions)
|
|
4143
|
+
ax.set_xticklabels(tick_labels, rotation=90)
|
|
4144
|
+
if savefig:
|
|
4145
|
+
plt.savefig(
|
|
4146
|
+
output_dir + output_fname + "_count_ppa_result.pdf", bbox_inches="tight"
|
|
4147
|
+
)
|
|
4148
|
+
else:
|
|
4149
|
+
plt.show()
|
|
4150
|
+
|
|
4151
|
+
|
|
4152
|
+
def BC_projection(
|
|
4153
|
+
adata,
|
|
4154
|
+
cnmap_dict,
|
|
4155
|
+
cn_col,
|
|
4156
|
+
plot_list, # list of 3 elements from cn_col
|
|
4157
|
+
cn_col_annt=None,
|
|
4158
|
+
palette=None,
|
|
4159
|
+
figsize=(7, 7),
|
|
4160
|
+
rand_seed=1,
|
|
4161
|
+
SMALL_SIZE=14,
|
|
4162
|
+
MEDIUM_SIZE=16,
|
|
4163
|
+
BIGGER_SIZE=18,
|
|
4164
|
+
n_num=None,
|
|
4165
|
+
threshold=None,
|
|
4166
|
+
savefig=False,
|
|
4167
|
+
output_fname="",
|
|
4168
|
+
output_dir="", # output directory
|
|
4169
|
+
dpi=300,
|
|
4170
|
+
):
|
|
4171
|
+
"""
|
|
4172
|
+
Plot barycentric projection.
|
|
4173
|
+
|
|
4174
|
+
Parameters
|
|
4175
|
+
----------
|
|
4176
|
+
adata : AnnData
|
|
4177
|
+
Annotated data object.
|
|
4178
|
+
cnmap_dict : dict
|
|
4179
|
+
Dictionary containing keys 'w', 'l', 'k', and 'threshold'.
|
|
4180
|
+
cn_col : str
|
|
4181
|
+
Column name in adata.obs containing copy number information.
|
|
4182
|
+
plot_list : list
|
|
4183
|
+
List of 3 elements from cn_col.
|
|
4184
|
+
cn_col_annt : str, optional
|
|
4185
|
+
Annotated column name, by default None.
|
|
4186
|
+
palette : dict, optional
|
|
4187
|
+
Color palette, by default None.
|
|
4188
|
+
figsize : tuple, optional
|
|
4189
|
+
Figure size, by default (7, 7).
|
|
4190
|
+
rand_seed : int, optional
|
|
4191
|
+
Random seed, by default 1.
|
|
4192
|
+
SMALL_SIZE : int, optional
|
|
4193
|
+
Font size for small text, by default 14.
|
|
4194
|
+
MEDIUM_SIZE : int, optional
|
|
4195
|
+
Font size for medium text, by default 16.
|
|
4196
|
+
BIGGER_SIZE : int, optional
|
|
4197
|
+
Font size for large text, by default 18.
|
|
4198
|
+
n_num : int, optional
|
|
4199
|
+
Number, by default None.
|
|
4200
|
+
threshold : float, optional
|
|
4201
|
+
Threshold, by default None.
|
|
4202
|
+
savefig : bool, optional
|
|
4203
|
+
Whether to save the figure, by default False.
|
|
4204
|
+
output_fname : str, optional
|
|
4205
|
+
Output file name, by default "".
|
|
4206
|
+
output_dir : str, optional
|
|
4207
|
+
Output directory, by default "".
|
|
4208
|
+
dpi : int, optional
|
|
4209
|
+
Dots per inch, by default 300.
|
|
4210
|
+
"""
|
|
4211
|
+
if cn_col_annt is None:
|
|
4212
|
+
plot_list_annot = plot_list
|
|
4213
|
+
all_list = list(adata.obs[cn_col].unique())
|
|
4214
|
+
if all(x in all_list for x in plot_list):
|
|
4215
|
+
pass
|
|
4216
|
+
else:
|
|
4217
|
+
print(
|
|
4218
|
+
"Please provide a valid list of plot_list from cn_col or specify cn_col_annt!"
|
|
4219
|
+
)
|
|
4220
|
+
return
|
|
4221
|
+
else:
|
|
4222
|
+
if cn_col == cn_col_annt:
|
|
4223
|
+
plot_list_annot = plot_list
|
|
4224
|
+
else:
|
|
4225
|
+
annt_map = dict(
|
|
4226
|
+
zip(adata.obs[cn_col].unique(), adata.obs[cn_col_annt].unique())
|
|
4227
|
+
)
|
|
4228
|
+
plot_list_annot = [annt_map[i] for i in plot_list]
|
|
4229
|
+
|
|
4230
|
+
# Settings for graph
|
|
4231
|
+
plt.rc("font", size=SMALL_SIZE) # controls default text sizes
|
|
4232
|
+
plt.rc("axes", titlesize=SMALL_SIZE) # fontsize of the axes title
|
|
4233
|
+
plt.rc("axes", labelsize=MEDIUM_SIZE) # fontsize of the x and y labels
|
|
4234
|
+
plt.rc("xtick", labelsize=SMALL_SIZE) # fontsize of the tick labels
|
|
4235
|
+
plt.rc("ytick", labelsize=SMALL_SIZE) # fontsize of the tick labels
|
|
4236
|
+
plt.rc("legend", fontsize=SMALL_SIZE) # legend fontsize
|
|
4237
|
+
plt.rc("figure", titlesize=BIGGER_SIZE) # fontsize of the figure title
|
|
4238
|
+
|
|
4239
|
+
# generate color
|
|
4240
|
+
if palette is None:
|
|
4241
|
+
cn_colors = hf_generate_random_colors(
|
|
4242
|
+
len(adata.obs[cn_col].unique()), rand_seed=rand_seed
|
|
4243
|
+
)
|
|
4244
|
+
if cn_col_annt + "_colors" not in adata.uns.keys():
|
|
4245
|
+
palette = dict(zip(np.sort(adata.obs[cn_col].unique()), cn_colors))
|
|
4246
|
+
adata.uns[cn_col + "_colors"] = cn_colors
|
|
4247
|
+
else:
|
|
4248
|
+
palette = dict(
|
|
4249
|
+
zip(np.sort(adata.obs[cn_col].unique()), adata.uns[cn_col + "_colors"])
|
|
4250
|
+
)
|
|
4251
|
+
|
|
4252
|
+
w = cnmap_dict["w"]
|
|
4253
|
+
l = cnmap_dict["l"]
|
|
4254
|
+
if n_num is None:
|
|
4255
|
+
n_num = cnmap_dict["k"]
|
|
4256
|
+
else:
|
|
4257
|
+
n_num = n_num
|
|
4258
|
+
|
|
4259
|
+
if threshold is None:
|
|
4260
|
+
threshold = cnmap_dict["threshold"]
|
|
4261
|
+
threshold = threshold * 100
|
|
4262
|
+
else:
|
|
4263
|
+
threshold = threshold * 100
|
|
4264
|
+
|
|
4265
|
+
# lmap = {j: i for i, j in enumerate(l)}
|
|
4266
|
+
|
|
4267
|
+
wgc = w.loc[w.loc[:, plot_list].sum(axis=1) > threshold, :]
|
|
4268
|
+
# idx = wgc.index.values
|
|
4269
|
+
xl = wgc.loc[:, plot_list]
|
|
4270
|
+
proj = np.array([[0, 0], [np.cos(np.pi / 3), np.sin(np.pi / 3)], [1, 0]])
|
|
4271
|
+
coords = np.dot(xl / n_num, proj) #####window size fraction
|
|
4272
|
+
|
|
4273
|
+
plt.figure(figsize=figsize)
|
|
4274
|
+
jit = 0.002
|
|
4275
|
+
|
|
4276
|
+
cols = [palette[a] for a in wgc[cn_col]]
|
|
4277
|
+
|
|
4278
|
+
plt.scatter(
|
|
4279
|
+
coords[:, 0] + jit * np.random.randn(len(coords)),
|
|
4280
|
+
coords[:, 1] + jit * np.random.randn(len(coords)),
|
|
4281
|
+
s=15,
|
|
4282
|
+
alpha=0.5,
|
|
4283
|
+
c=cols,
|
|
4284
|
+
)
|
|
4285
|
+
|
|
4286
|
+
# add label to corners of the triangle
|
|
4287
|
+
plt.text(-0.15, -0.05, plot_list_annot[0], fontsize=10)
|
|
4288
|
+
plt.text(0.65, -0.05, plot_list_annot[2], fontsize=10)
|
|
4289
|
+
plt.text(
|
|
4290
|
+
np.cos(np.pi / 3),
|
|
4291
|
+
np.sin(np.pi / 3) + 0.035,
|
|
4292
|
+
plot_list_annot[1],
|
|
4293
|
+
fontsize=10,
|
|
4294
|
+
horizontalalignment="center",
|
|
4295
|
+
verticalalignment="center",
|
|
4296
|
+
)
|
|
4297
|
+
|
|
4298
|
+
# Create a list of Patch objects, one for each unique color in your palette
|
|
4299
|
+
legend_patches = [
|
|
4300
|
+
mpatches.Patch(color=color, label=label) for label, color in palette.items()
|
|
4301
|
+
]
|
|
4302
|
+
|
|
4303
|
+
# Add legend to bottom of plot
|
|
4304
|
+
plt.legend(
|
|
4305
|
+
handles=legend_patches,
|
|
4306
|
+
bbox_to_anchor=(0.0, -0.15, 1.0, 0.102),
|
|
4307
|
+
loc="lower center",
|
|
4308
|
+
ncol=3,
|
|
4309
|
+
borderaxespad=0.0,
|
|
4310
|
+
fontsize=10,
|
|
4311
|
+
)
|
|
4312
|
+
|
|
4313
|
+
plt.axis("off")
|
|
4314
|
+
|
|
4315
|
+
if savefig:
|
|
4316
|
+
plt.savefig(
|
|
4317
|
+
output_dir + output_fname + "_bc_proj.pdf",
|
|
4318
|
+
dpi=dpi,
|
|
4319
|
+
transparent=True,
|
|
4320
|
+
bbox_inches="tight",
|
|
4321
|
+
)
|
|
4322
|
+
else:
|
|
4323
|
+
plt.show()
|
|
4324
|
+
|
|
4325
|
+
|
|
4326
|
+
def ppa_res_donut(
|
|
4327
|
+
adata,
|
|
4328
|
+
cat_col,
|
|
4329
|
+
palette=None,
|
|
4330
|
+
key_names="ppa_result",
|
|
4331
|
+
radii=[1, 2, 3, 4, 5],
|
|
4332
|
+
unit="µm",
|
|
4333
|
+
figsize=(10, 10),
|
|
4334
|
+
add_guides=True,
|
|
4335
|
+
text="example CN",
|
|
4336
|
+
label_color="black",
|
|
4337
|
+
rand_seed=1,
|
|
4338
|
+
subset_column=None,
|
|
4339
|
+
subset_condition=None,
|
|
4340
|
+
title="Title",
|
|
4341
|
+
savefig=False,
|
|
4342
|
+
output_fname="",
|
|
4343
|
+
output_dir="./",
|
|
4344
|
+
):
|
|
4345
|
+
# plotting
|
|
4346
|
+
key_names = key_names[::-1]
|
|
4347
|
+
plt.figure(figsize=figsize)
|
|
4348
|
+
|
|
4349
|
+
if add_guides == True:
|
|
4350
|
+
# add grid lines
|
|
4351
|
+
plt.plot([0, 0], [1.05, -1.05], color="black", alpha=0.3, zorder=-1)
|
|
4352
|
+
plt.plot([1.05, -1.05], [0, 0], color="black", alpha=0.3, zorder=-1)
|
|
4353
|
+
# add diagonal lines
|
|
4354
|
+
for angle in [45, -45]:
|
|
4355
|
+
x_new = 1.05 * np.cos(np.radians(angle))
|
|
4356
|
+
y_new = 1.05 * np.sin(np.radians(angle))
|
|
4357
|
+
plt.plot(
|
|
4358
|
+
[-x_new, x_new], [-y_new, y_new], color="black", alpha=0.3, zorder=-1
|
|
4359
|
+
)
|
|
4360
|
+
|
|
4361
|
+
# generate reproducable colors if no palette is provided
|
|
4362
|
+
if palette is None:
|
|
4363
|
+
if cat_col + "_colors" not in adata.uns.keys():
|
|
4364
|
+
ct_colors = hf_generate_random_colors(
|
|
4365
|
+
len(adata.obs[cat_col].unique()), rand_seed=rand_seed
|
|
4366
|
+
)
|
|
4367
|
+
palette = dict(zip(np.sort(adata.obs[cat_col].unique()), ct_colors))
|
|
4368
|
+
adata.uns[cat_col + "_colors"] = ct_colors
|
|
4369
|
+
else:
|
|
4370
|
+
palette = dict(
|
|
4371
|
+
zip(
|
|
4372
|
+
np.sort(adata.obs[cat_col].unique()), adata.uns[cat_col + "_colors"]
|
|
4373
|
+
)
|
|
4374
|
+
)
|
|
4375
|
+
|
|
4376
|
+
for i, key_name in enumerate(key_names):
|
|
4377
|
+
print(f"Key {i}: {key_name}")
|
|
4378
|
+
# extract key from adata
|
|
4379
|
+
region_results = adata.uns[key_name]
|
|
4380
|
+
|
|
4381
|
+
# test if region_results is empty
|
|
4382
|
+
if region_results.shape[0] == 0:
|
|
4383
|
+
print(f"Key {i} is empty.")
|
|
4384
|
+
continue
|
|
4385
|
+
else:
|
|
4386
|
+
print(f"Key {i} has {region_results.shape[0]} rows.")
|
|
4387
|
+
|
|
4388
|
+
# subset by condition
|
|
4389
|
+
if subset_column != None:
|
|
4390
|
+
if subset_column not in region_results.columns:
|
|
4391
|
+
raise ValueError(
|
|
4392
|
+
f"Column '{subset_column}' does not exist in the DataFrame."
|
|
4393
|
+
)
|
|
4394
|
+
elif subset_condition not in region_results[subset_column].unique():
|
|
4395
|
+
raise ValueError(
|
|
4396
|
+
f"Value '{subset_condition}' does not exist in the column '{subset_column}'."
|
|
4397
|
+
)
|
|
4398
|
+
else:
|
|
4399
|
+
region_results = region_results[
|
|
4400
|
+
region_results[subset_column] == subset_condition
|
|
4401
|
+
]
|
|
4402
|
+
|
|
4403
|
+
# calculate percentages of categories
|
|
4404
|
+
percentage_list = region_results[cat_col].value_counts(normalize=True) * 100
|
|
4405
|
+
|
|
4406
|
+
# Check if all categories have a color in the palette
|
|
4407
|
+
for category in percentage_list.index:
|
|
4408
|
+
if category not in palette:
|
|
4409
|
+
raise ValueError(
|
|
4410
|
+
f"No color provided for category {category} in the palette"
|
|
4411
|
+
)
|
|
4412
|
+
|
|
4413
|
+
# Get the colors for the current categories from the palette
|
|
4414
|
+
category_colors = [palette[category] for category in percentage_list.index]
|
|
4415
|
+
|
|
4416
|
+
rsed_index = len(radii) - 1 - i
|
|
4417
|
+
plt.pie(
|
|
4418
|
+
percentage_list, radius=(0.6 + 0.1 * rsed_index), colors=category_colors
|
|
4419
|
+
)
|
|
4420
|
+
|
|
4421
|
+
# add labels for each distance
|
|
4422
|
+
for j, percentage_list in enumerate(radii):
|
|
4423
|
+
rsed_index = len(radii) - 1 - j
|
|
4424
|
+
plt.text(
|
|
4425
|
+
0,
|
|
4426
|
+
(0.53 + 0.1 * rsed_index),
|
|
4427
|
+
str(radii[rsed_index]) + unit,
|
|
4428
|
+
horizontalalignment="center",
|
|
4429
|
+
fontweight="bold",
|
|
4430
|
+
color=label_color,
|
|
4431
|
+
)
|
|
4432
|
+
|
|
4433
|
+
# add a circle at the center to transform it in a donut chart
|
|
4434
|
+
my_circle = plt.Circle((0, 0), 0.5, color="white")
|
|
4435
|
+
p = plt.gcf()
|
|
4436
|
+
p.gca().add_artist(my_circle)
|
|
4437
|
+
|
|
4438
|
+
# add a legend based on the colors and keys in palette
|
|
4439
|
+
handles = [plt.Rectangle((0, 0), 1, 1, color=palette[key]) for key in palette]
|
|
4440
|
+
plt.legend(
|
|
4441
|
+
handles,
|
|
4442
|
+
palette.keys(),
|
|
4443
|
+
bbox_to_anchor=(0.94, 0.925),
|
|
4444
|
+
loc="upper left",
|
|
4445
|
+
prop={"size": 15},
|
|
4446
|
+
)
|
|
4447
|
+
|
|
4448
|
+
# Define the maximum length of a line
|
|
4449
|
+
max_line_length = 20
|
|
4450
|
+
|
|
4451
|
+
# Split the text into multiple lines if it's too long
|
|
4452
|
+
wrapped_text = textwrap.fill(text, max_line_length)
|
|
4453
|
+
|
|
4454
|
+
# Add a title in the middle of the white circle
|
|
4455
|
+
plt.text(
|
|
4456
|
+
0,
|
|
4457
|
+
0,
|
|
4458
|
+
wrapped_text,
|
|
4459
|
+
horizontalalignment="center",
|
|
4460
|
+
verticalalignment="center",
|
|
4461
|
+
fontsize=18,
|
|
4462
|
+
)
|
|
4463
|
+
|
|
4464
|
+
plt.title(title, size=24, y=0.96)
|
|
4465
|
+
|
|
4466
|
+
if savefig:
|
|
4467
|
+
plt.savefig(output_dir + output_fname + ".pdf", bbox_inches="tight")
|
|
4468
|
+
else:
|
|
4469
|
+
plt.show()
|
|
4470
|
+
|
|
4471
|
+
|
|
4472
|
+
def distance_graph(
|
|
4473
|
+
dist_table,
|
|
4474
|
+
distance_pvals,
|
|
4475
|
+
palette=None,
|
|
4476
|
+
condition_pair=None,
|
|
4477
|
+
interaction_col="interaction",
|
|
4478
|
+
condition_col="condition",
|
|
4479
|
+
logfold_group_col="logfold_group",
|
|
4480
|
+
celltype1_col="celltype1",
|
|
4481
|
+
celltype2_col="celltype2",
|
|
4482
|
+
pair_col="pairs",
|
|
4483
|
+
with_labels=True,
|
|
4484
|
+
node_size=910,
|
|
4485
|
+
font_size=7,
|
|
4486
|
+
multiplication_factor=10,
|
|
4487
|
+
savefig=False,
|
|
4488
|
+
output_fname="",
|
|
4489
|
+
output_dir="", # output directory
|
|
4490
|
+
dpi=300,
|
|
4491
|
+
color_seed=0,
|
|
4492
|
+
):
|
|
4493
|
+
"""
|
|
4494
|
+
Generates a distance graph from a dataframe.
|
|
4495
|
+
|
|
4496
|
+
Parameters:
|
|
4497
|
+
df (DataFrame): The input dataframe.
|
|
4498
|
+
palette (dict, optional): A dictionary mapping nodes to colors. If None, nodes are colored 'lightgrey'.
|
|
4499
|
+
condition_pair (list, optional): A list of two conditions to compare. If None, uses unique conditions from the dataframe.
|
|
4500
|
+
interaction_col (str, optional): The name of the interaction column in the dataframe. Defaults to 'interaction'.
|
|
4501
|
+
condition_col (str, optional): The name of the condition column in the dataframe. Defaults to 'condition'.
|
|
4502
|
+
logfold_group_col (str, optional): The name of the logfold group column in the dataframe. Defaults to 'logfold_group'.
|
|
4503
|
+
celltype1_col (str, optional): The name of the first cell type column in the dataframe. Defaults to 'celltype1'.
|
|
4504
|
+
celltype2_col (str, optional): The name of the second cell type column in the dataframe. Defaults to 'celltype2'.
|
|
4505
|
+
with_labels (bool, optional): Whether to draw labels on the nodes. Defaults to True.
|
|
4506
|
+
node_size (int, optional): The size of the nodes. Defaults to 910.
|
|
4507
|
+
font_size (int, optional): The font size for the labels. Defaults to 7.
|
|
4508
|
+
|
|
4509
|
+
Returns:
|
|
4510
|
+
None: The function generates a plot and does not return anything.
|
|
4511
|
+
"""
|
|
4512
|
+
|
|
4513
|
+
# Generate df for graph
|
|
4514
|
+
# this is to restrict to the pairs that were filtered
|
|
4515
|
+
pairs = dist_table[pair_col].unique()
|
|
4516
|
+
distance_pvals[pair_col] = (
|
|
4517
|
+
distance_pvals[celltype1_col] + "_" + distance_pvals[celltype2_col]
|
|
4518
|
+
)
|
|
4519
|
+
distance_pvals = distance_pvals[distance_pvals[pair_col].isin(pairs)]
|
|
4520
|
+
print(distance_pvals.shape)
|
|
4521
|
+
pairs = distance_pvals[interaction_col].unique()
|
|
4522
|
+
distance_pvals_grouped = distance_pvals.groupby([celltype1_col, celltype2_col])
|
|
4523
|
+
|
|
4524
|
+
result_list = {}
|
|
4525
|
+
|
|
4526
|
+
if condition_pair == None:
|
|
4527
|
+
conditions = distance_pvals[condition_col].unique()
|
|
4528
|
+
else:
|
|
4529
|
+
conditions = condition_pair
|
|
4530
|
+
|
|
4531
|
+
for p in pairs:
|
|
4532
|
+
distance_pvals_c1 = distance_pvals[
|
|
4533
|
+
(distance_pvals[interaction_col] == p)
|
|
4534
|
+
& (distance_pvals[condition_col] == conditions[0])
|
|
4535
|
+
]
|
|
4536
|
+
distance_pvals_c2 = distance_pvals[
|
|
4537
|
+
(distance_pvals[interaction_col] == p)
|
|
4538
|
+
& (distance_pvals[condition_col] == conditions[1])
|
|
4539
|
+
]
|
|
4540
|
+
|
|
4541
|
+
difference = abs(
|
|
4542
|
+
distance_pvals_c2[logfold_group_col].values[0]
|
|
4543
|
+
- distance_pvals_c1[logfold_group_col].values[0]
|
|
4544
|
+
)
|
|
4545
|
+
|
|
4546
|
+
if (
|
|
4547
|
+
0
|
|
4548
|
+
> (
|
|
4549
|
+
distance_pvals_c2[logfold_group_col].values[0]
|
|
4550
|
+
- distance_pvals_c1[logfold_group_col]
|
|
4551
|
+
).values[0]
|
|
4552
|
+
):
|
|
4553
|
+
direction = "#3976AC"
|
|
4554
|
+
else:
|
|
4555
|
+
direction = "#C63D30"
|
|
4556
|
+
|
|
4557
|
+
df_res = pd.DataFrame(
|
|
4558
|
+
{
|
|
4559
|
+
celltype1_col: distance_pvals_c2[celltype1_col],
|
|
4560
|
+
celltype2_col: distance_pvals_c2[celltype2_col],
|
|
4561
|
+
"difference": difference,
|
|
4562
|
+
"direction": direction,
|
|
4563
|
+
}
|
|
4564
|
+
)
|
|
4565
|
+
|
|
4566
|
+
result_list[p] = df_res
|
|
4567
|
+
|
|
4568
|
+
graph_df = pd.concat(result_list.values())
|
|
4569
|
+
graph_df = graph_df.drop_duplicates(
|
|
4570
|
+
subset=[celltype1_col, celltype2_col], keep="first"
|
|
4571
|
+
)
|
|
4572
|
+
|
|
4573
|
+
## remove nan values
|
|
4574
|
+
graph_df = graph_df[graph_df["difference"].notna()]
|
|
4575
|
+
|
|
4576
|
+
# Generate graph
|
|
4577
|
+
G = nx.from_pandas_edgelist(
|
|
4578
|
+
graph_df,
|
|
4579
|
+
source=celltype1_col,
|
|
4580
|
+
target=celltype2_col,
|
|
4581
|
+
edge_attr=["difference", "direction"],
|
|
4582
|
+
)
|
|
4583
|
+
|
|
4584
|
+
for u, v, d in G.edges(data=True):
|
|
4585
|
+
d["weight"] = (
|
|
4586
|
+
1e-100
|
|
4587
|
+
if d["difference"] == 0
|
|
4588
|
+
else abs(d["difference"] * multiplication_factor)
|
|
4589
|
+
)
|
|
4590
|
+
|
|
4591
|
+
# Generate plot
|
|
4592
|
+
weights = [G[u][v]["weight"] for u, v in G.edges()]
|
|
4593
|
+
|
|
4594
|
+
pos = nx.circular_layout(G)
|
|
4595
|
+
|
|
4596
|
+
edge_colors = [d["direction"] for u, v, d in G.edges(data=True)]
|
|
4597
|
+
|
|
4598
|
+
if palette is None:
|
|
4599
|
+
combined_list = (
|
|
4600
|
+
distance_pvals[celltype1_col].tolist()
|
|
4601
|
+
+ distance_pvals[celltype2_col].tolist()
|
|
4602
|
+
)
|
|
4603
|
+
unique_values = set(combined_list)
|
|
4604
|
+
ct_colors = hf_generate_random_colors(len(unique_values), rand_seed=color_seed)
|
|
4605
|
+
# map colors to cell types
|
|
4606
|
+
palette = {value: ct_colors[i] for i, value in enumerate(unique_values)}
|
|
4607
|
+
node_colors = [palette[node] for node in G.nodes()]
|
|
4608
|
+
else:
|
|
4609
|
+
node_colors = [palette[node] for node in G.nodes()]
|
|
4610
|
+
|
|
4611
|
+
nx.draw(
|
|
4612
|
+
G,
|
|
4613
|
+
pos,
|
|
4614
|
+
node_color=node_colors,
|
|
4615
|
+
with_labels=False, # Don't draw labels here
|
|
4616
|
+
edge_color=edge_colors,
|
|
4617
|
+
node_size=node_size,
|
|
4618
|
+
width=weights,
|
|
4619
|
+
)
|
|
4620
|
+
|
|
4621
|
+
for node, (x, y) in pos.items():
|
|
4622
|
+
wrapped_node = textwrap.fill(node, 10) # Split long names into multiple lines
|
|
4623
|
+
plt.text(
|
|
4624
|
+
x,
|
|
4625
|
+
y,
|
|
4626
|
+
wrapped_node,
|
|
4627
|
+
fontsize=font_size,
|
|
4628
|
+
color="white" if is_dark(palette.get(node, "lightgrey")) else "black",
|
|
4629
|
+
ha="center",
|
|
4630
|
+
va="center",
|
|
4631
|
+
)
|
|
4632
|
+
|
|
4633
|
+
# add legend
|
|
4634
|
+
plt.plot(
|
|
4635
|
+
[],
|
|
4636
|
+
[],
|
|
4637
|
+
color="#3976AC",
|
|
4638
|
+
label="More distant in " + conditions[0] + " than " + conditions[1],
|
|
4639
|
+
)
|
|
4640
|
+
plt.plot(
|
|
4641
|
+
[],
|
|
4642
|
+
[],
|
|
4643
|
+
color="#C63D30",
|
|
4644
|
+
label="Closer in " + conditions[0] + " than " + conditions[1],
|
|
4645
|
+
)
|
|
4646
|
+
|
|
4647
|
+
# add width legend
|
|
4648
|
+
plt.plot(
|
|
4649
|
+
[],
|
|
4650
|
+
[],
|
|
4651
|
+
color="k",
|
|
4652
|
+
label="edge width = absolute difference * " + str(multiplication_factor),
|
|
4653
|
+
)
|
|
4654
|
+
|
|
4655
|
+
# position legend at bottom middle
|
|
4656
|
+
plt.legend(bbox_to_anchor=(0.5, -0.2), loc="lower center", ncol=2)
|
|
4657
|
+
|
|
4658
|
+
if savefig:
|
|
4659
|
+
plt.savefig(
|
|
4660
|
+
output_dir + output_fname + "_dist_graph.pdf",
|
|
4661
|
+
dpi=dpi,
|
|
4662
|
+
bbox_inches="tight",
|
|
4663
|
+
)
|
|
4664
|
+
else:
|
|
4665
|
+
plt.show()
|