RDeF654875678597657 commited on
Commit
93be085
·
1 Parent(s): b5cece0
Data/joined_sub.csv ADDED
@@ -0,0 +1,3 @@
 
 
 
 
1
+ version https://git-lfs.github.com/spec/v1
2
+ oid sha256:8d608ac1d058c967e3b20b1410106f5251ec118c3b12f6f1f6e585e1ac69ffd0
3
+ size 782758323
Data/joined_with_membership_sub.csv ADDED
@@ -0,0 +1,3 @@
 
 
 
 
1
+ version https://git-lfs.github.com/spec/v1
2
+ oid sha256:c4d4c71e8646c0905abf514973f92c958b303370edb0604b9e0ea5d8dddcc2a9
3
+ size 1586292007
Data/selected_genes_MERFISH.csv ADDED
@@ -0,0 +1,10 @@
 
 
 
 
 
 
 
 
 
 
 
1
+ gene_identifier,gene_symbol,name,mapped_ncbi_identifier
2
+ ENSMUSG00000024798,Htr7,5-hydroxytryptamine (serotonin) receptor 7,NCBIGene:15566
3
+ ENSMUSG00000050783,Htr1f,5-hydroxytryptamine (serotonin) receptor 1F,NCBIGene:15557
4
+ ENSMUSG00000070687,Htr1d,5-hydroxytryptamine (serotonin) receptor 1D,NCBIGene:15552
5
+ ENSMUSG00000026322,Htr4,5 hydroxytryptamine (serotonin) receptor 4,NCBIGene:15562
6
+ ENSMUSG00000049511,Htr1b,5-hydroxytryptamine (serotonin) receptor 1B,NCBIGene:15551
7
+ ENSMUSG00000034997,Htr2a,5-hydroxytryptamine (serotonin) receptor 2A,NCBIGene:15558
8
+ ENSMUSG00000021721,Htr1a,5-hydroxytryptamine (serotonin) receptor 1A,NCBIGene:15550
9
+ ENSMUSG00000041380,Htr2c,5-hydroxytryptamine (serotonin) receptor 2C,NCBIGene:15560
10
+ ENSMUSG00000032269,Htr3a,5-hydroxytryptamine (serotonin) receptor 3A,NCBIGene:15561
Data/selected_genes_RNAseq.csv ADDED
@@ -0,0 +1,15 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ gene_identifier,gene_symbol
2
+ ENSMUSG00000026228,Htr2b
3
+ ENSMUSG00000050534,Htr5b
4
+ ENSMUSG00000070687,Htr1d
5
+ ENSMUSG00000028747,Htr6
6
+ ENSMUSG00000039106,Htr5a
7
+ ENSMUSG00000032269,Htr3a
8
+ ENSMUSG00000008590,Htr3b
9
+ ENSMUSG00000049511,Htr1b
10
+ ENSMUSG00000021721,Htr1a
11
+ ENSMUSG00000034997,Htr2a
12
+ ENSMUSG00000050783,Htr1f
13
+ ENSMUSG00000026322,Htr4
14
+ ENSMUSG00000024798,Htr7
15
+ ENSMUSG00000041380,Htr2c
Data/sub_cell_expression.pickle ADDED
@@ -0,0 +1,3 @@
 
 
 
 
1
+ version https://git-lfs.github.com/spec/v1
2
+ oid sha256:1f28cf01bf169c243040cdedc37a24c12d24eb3a53f76987ae49cf77a47120f8
3
+ size 705215247
app.py CHANGED
@@ -13,7 +13,6 @@ import matplotlib.colors as mcolors
13
  import matplotlib.colors as plt_colors
14
  import pickle
15
 
16
-
17
  genes_families = {
18
  'Htr1': ['Htr1a', 'Htr1b', 'Htr1d', 'Htr1f'],
19
  'Htr2': ['Htr2a', 'Htr2b', 'Htr2c'],
@@ -70,438 +69,436 @@ dataset = datasets[0]
70
 
71
  print(joined_sub.columns)
72
 
73
- df_pane = pn.pane.DataFrame(joined_sub, width=400)
74
-
75
- df_pane
76
- #
77
- # classification_cmap = joined_sub.drop_duplicates(subset='subclass').set_index('subclass')['subclass_color'].to_dict()
78
- # classification_cmap.update(joined_sub.drop_duplicates(subset='supertype').set_index('supertype')['subclass_color'].to_dict())
79
- # classification_cmap.update(joined_sub.drop_duplicates(subset='cluster').set_index('cluster')['subclass_color'].to_dict())
80
- # classification_cmap.update(joined_sub.drop_duplicates(subset='class').set_index('class')['class_color'].to_dict())
81
- #
82
- #
83
- # class MERFISH_viz(param.Parameterized):
84
- # dataset_selector = param.Selector(objects=datasets)
85
- # brain_section_index = param.Integer(default=0, bounds=(
86
- # 0, sub_cell_expression[datasets[0]]["brain_section_label"].unique().shape[0]))
87
- # gene_selector = param.ObjectSelector(default=selected_genes[0], objects=selected_genes.tolist())
88
- # class_selector = param.ListSelector(default=sorted(sub_cell_expression[dataset]['class'].unique()),
89
- # objects=sorted(sub_cell_expression[dataset]['class'].unique()))
90
- # subclass_selector = param.ListSelector(default=sorted(sub_cell_expression[dataset]['subclass'].unique()),
91
- # objects=sorted(sub_cell_expression[dataset]['subclass'].unique()))
92
- #
93
- # # Naming the keyword arguments `**params` is purely a convention.
94
- # def __init__(self, sub_cell_expression, sel_dataset, sel_class, sel_subclass, brain_section_index, **params):
95
- # super().__init__(**params)
96
- # self.sub_cell_expression = sub_cell_expression
97
- # self.current_data = self.sub_cell_expression[sel_dataset]
98
- # self.filtered_data = self.current_data[
99
- # self.current_data['class'].isin(sel_class) & self.current_data['subclass'].isin(sel_subclass)]
100
- #
101
- # brain_section = self.current_data['brain_section_label'].unique()[brain_section_index]
102
- # section = self.filtered_data[self.filtered_data['brain_section_label'] == brain_section]
103
- #
104
- # self.section = section[section['parcellation_division'] != "unassigned"]
105
- #
106
- # self.control_panel = pn.Row(
107
- # pn.Param(self.param['dataset_selector']),
108
- # pn.Param(self.param['brain_section_index']),
109
- # pn.Param(self.param['gene_selector']),
110
- # pn.Param(self.param['class_selector']),
111
- # pn.Param(self.param['subclass_selector'])
112
- # )
113
- #
114
- # @param.depends('dataset_selector', 'brain_section_index', 'gene_selector', 'class_selector', 'subclass_selector')
115
- # def view(self):
116
- # return pn.Column(
117
- # f'Selected dataset: {self.dataset_selector}',
118
- # f'Brain Section Index: {self.brain_section_index}',
119
- # f'Selected Gene: {self.gene_selector}',
120
- # f'Selected Classes: {self.class_selector}, {self.subclass_selector}')
121
- #
122
- # @pn.depends("filter_by_class_subclass", "gene_selector", "brain_section_index")
123
- # def plot_expr_across_slices(self):
124
- # curve_data = self.filtered_data[self.filtered_data[self.gene_selector] > 0].groupby('brain_section_label')[
125
- # self.gene_selector].mean()
126
- # curve_data.rename(f"Expression {self.gene_selector}", inplace=True)
127
- # curve = hv.Curve(curve_data, label=f'Log(CPM) {self.gene_selector}').opts(xaxis=None, height=140,
128
- # responsive=True, active_tools=[])
129
- #
130
- # grouped_data = self.filtered_data.groupby('brain_section_label')[self.gene_selector].apply(
131
- # percentage_above_threshold_MER).reset_index()
132
- # grouped_data.rename(columns={self.gene_selector: f"% expressing {self.gene_selector}"}, inplace=True)
133
- # percentage_curve = hv.Curve(grouped_data, 'brain_section_label', f"% expressing {self.gene_selector}",
134
- # label=f'Percentage expressing {self.gene_selector}').opts(xaxis=None,
135
- # height=140,
136
- # responsive=True,
137
- # active_tools=[])
138
- #
139
- # vline = hv.VLine(self.brain_section_index).opts(line_color='red', line_width=2)
140
- # percentage_of_all_cells = ((self.filtered_data.groupby(
141
- # 'brain_section_label').size() / self.current_data.groupby('brain_section_label').size()) * 100).fillna(0)
142
- # percentage_of_all_cells.name = "% of all cells"
143
- # ratio_cells = hv.Curve(percentage_of_all_cells, 'brain_section_label', "% of all cells",
144
- # label='Percentage of all cells').opts(xaxis=None,
145
- # height=100,
146
- # responsive=True,
147
- # active_tools=[])
148
- #
149
- # return hv.Layout([(ratio_cells * vline), (curve * vline), (percentage_curve * vline)]).cols(1)
150
- #
151
- # @pn.depends("filter_by_class_subclass", "gene_selector", "brain_section_index")
152
- # def plot_bar(self):
153
- # color_map = self.section.groupby('parcellation_structure')['parcellation_structure_color'].first().to_dict()
154
- #
155
- # hv_ds = hv.Dataset(self.section.groupby(['parcellation_structure'])[self.gene_selector].apply(
156
- # percentage_above_threshold_MER).sort_values(ascending=False).head(20).reset_index(),
157
- # kdims=['parcellation_structure'], vdims=[self.gene_selector])
158
- #
159
- # # Create the vertical Bar chart with rotated xticklabels
160
- # bar_plot = hv.Bars(hv_ds).opts(
161
- # color=dim('parcellation_structure').categorize(color_map, 'gray'),
162
- # active_tools=[],
163
- # tools=["hover"],
164
- # responsive=True,
165
- # frame_height=100,
166
- # invert_axes=False,
167
- # xrotation=90 # Rotate xticklabels by 90 degrees
168
- # )
169
- #
170
- # grouped_data = self.section.groupby(['parcellation_structure'])[self.gene_selector].apply(
171
- # percentage_above_threshold_MER).sort_values(
172
- # ascending=False).head(30).reset_index()
173
- # counts = self.section['parcellation_structure'].value_counts().reindex(
174
- # grouped_data['parcellation_structure']).fillna(0)
175
- #
176
- # labels = hv.Labels({'x': grouped_data['parcellation_structure'], 'y': grouped_data[self.gene_selector], 'text': counts},
177
- # ['x', 'y'], 'text').opts(text_font_size='8pt', text_color="black", yoffset=-5)
178
- #
179
- # return bar_plot * labels
180
- #
181
- # @pn.depends("filter_by_class_subclass", "gene_selector", "get_section")
182
- # def plot_section(self):
183
- # plot1 = hv.Points(data=self.section, kdims=['x', 'y'],
184
- # vdims=[self.gene_selector, 'parcellation_structure', 'parcellation_substructure']).opts(
185
- # width=550, colorbar=True, cmap='rocket_r', size=2, color=self.gene_selector)
186
- # plot2 = hv.NdOverlay({division: hv.Points(self.section[self.section['parcellation_division'] == division],
187
- # ['x', 'y'], ['parcellation_division_color', 'parcellation_structure',
188
- # 'parcellation_substructure']).opts(
189
- # color='parcellation_division_color', size=2) for division in
190
- # self.section[self.section['parcellation_category'] == "grey"][
191
- # 'parcellation_division'].unique()}, kdims='parcellation_division').opts(
192
- # legend_position='right', width=650, show_legend=True)
193
- #
194
- # common_opts = opts.Points(height=500, invert_yaxis=True, xaxis=None, yaxis=None, show_grid=False,
195
- # active_tools=[], tools=["hover"])
196
- #
197
- # return (plot1 + plot2).opts(common_opts)
198
- #
199
- # @param.depends("brain_section_index", watch=True)
200
- # def get_section(self):
201
- # brain_section = self.current_data['brain_section_label'].unique()[self.brain_section_index]
202
- # section = self.filtered_data[self.filtered_data['brain_section_label'] == brain_section]
203
- # self.section = section[section['parcellation_division'] != "unassigned"]
204
- #
205
- # @param.depends('dataset_selector', watch=True)
206
- # def update_current_data(self):
207
- # self.current_data = self.sub_cell_expression[self.dataset_selector]
208
- # self.brain_section_index = 0
209
- # self.brain_section_index.bounds = (0, self.current_data["brain_section_label"].unique().shape[0])
210
- #
211
- # @param.depends("update_current_data", 'class_selector', 'subclass_selector', watch=True)
212
- # def filter_by_class_subclass(self):
213
- # self.filtered_data = self.current_data[
214
- # self.current_data['class'].isin(self.class_selector) & self.current_data['subclass'].isin(
215
- # self.subclass_selector)]
216
- #
217
- # @param.depends("update_current_data", 'class_selector', watch=True)
218
- # def update_subclasses(self):
219
- # self.param.subclass_selector.objects = sorted(
220
- # self.current_data[self.current_data['class'].isin(self.class_selector)]['subclass'].unique())
221
- # self.subclass_selector = sorted(
222
- # self.current_data[(self.current_data['class'].isin(self.class_selector))]['subclass'].unique())
223
- #
224
- #
225
- # viz = MERFISH_viz(sub_cell_expression, datasets[0], sub_cell_expression[datasets[0]]["class"].unique(),
226
- # sub_cell_expression[dataset]["subclass"].unique(), 0)
227
- #
228
- # # Title of the paper and authors
229
- # # Custom HTML for the title
230
- # custom_title_html = """
231
- # <div style="text-align: center; max-width: 1200px; margin: 20px auto;">
232
- # <h1 style="font-weight: 900; font-size: 3rem; margin: 0rem">
233
- # Transcriptomic Mapping of the 5-HT Receptor Landscape
234
- # </h1>
235
- # <h2 style="font-weight: 450; font-size: 1rem; margin: 0rem">
236
- # Roberto De Filippo<sup>#</sup>, Dietmar Schmitz
237
- # </h2>
238
- # <h2 style="font-weight: 450; font-size: 1rem; margin: 0rem">
239
- # <sup>#</sup>Corresponding author
240
- # </h2>
241
- # <h2 style="font-weight: 450; font-size: 1rem; margin: 0rem">
242
- # [<a href="https://github.com/RobertoDF/5-HT2A-MERFISH" style="color:blue;">Article</a>]
243
- # [<a href="https://github.com/RobertoDF/5-HT2A-MERFISH" style="color:blue;">Github</a>]
244
- # </h2>
245
- # <h2 style="font-weight: 450; font-size: 1rem;">
246
- # Custom visualizer for MERFISH dataset provided by [<a href="https://www.nature.com/articles/s41586-023-06808-9" style="color:blue;">Zhang et al., 2023</a>] </h2>
247
- # <h2 style="font-weight: 450; font-size: 1rem;">
248
- # By <b>Roberto De Filippo</b>
249
- # </h2>
250
- # </div>
251
- # """
252
- #
253
- # # Create a Panel HTML pane with the custom title
254
- # custom_title_pane = pn.pane.HTML(custom_title_html, sizing_mode='stretch_width')
255
- #
256
- # dashboard_spatial = pn.Column(custom_title_pane, viz.control_panel, viz.plot_expr_across_slices, viz.plot_bar, viz.plot_section)
257
- #
258
- #
259
- # def plot_class_expression_split_by_categories(subfig, cls, df_subset, gene):
260
- # axs = subfig.subplots(4, 1)
261
- # subfig.subplots_adjust(left=0.05, right=.95)
262
- #
263
- # sns.violinplot(data=df_subset, y=f'{gene} prevalence (%)', x='subclass', hue='subclass', ax=axs[0],
264
- # palette=classification_cmap, fill=False)
265
- #
266
- # # Set the title with desired modifications
267
- # title = axs[0].set_title(cls, color=classification_cmap[cls], fontweight='bold', fontsize=20)
268
- # title.set_path_effects([path_effects.withStroke(linewidth=3, foreground='black')])
269
- #
270
- # subfig.set_facecolor(mcolors.to_rgba(classification_cmap[cls], alpha=0.15))
271
- #
272
- # axs[0].set_ylim(0, 100) # Set y-axis limit to 1
273
- # axs[0].xaxis.set_ticks_position('top')
274
- # axs[0].tick_params(axis='x', length=0)
275
- #
276
- # sns.violinplot(data=df_subset, y=f'{gene} prevalence (%)', x='supertype', hue='supertype', ax=axs[1],
277
- # palette=classification_cmap, fill=False)
278
- # axs[1].set_title(cls)
279
- # axs[1].set_ylim(0, 100) # Set y-axis limit to 1
280
- #
281
- # sns.barplot(data=df_subset, y=f'{gene} prevalence (%)', x='cluster', hue='cluster', ax=axs[2],
282
- # palette=classification_cmap)
283
- # axs[2].set_title(cls)
284
- # axs[2].set_ylim(0, 100) # Set y-axis limit to 1
285
- #
286
- # axs[2].set(ylabel='')
287
- # axs[0].set(ylabel='')
288
- # axs[2].set(xticks=[], xlabel='')
289
- # axs[1].set(xticks=[], xlabel='')
290
- # axs[0].set(xticks=[], xlabel='')
291
- # axs[0].set(xlabel='')
292
- # axs[2].set(xticks=[], xlabel='')
293
- # axs[2].set(xticks=[], xlabel='')
294
- # axs[1].set_title('')
295
- # axs[2].set_title('')
296
- # plt.draw()
297
- # for tick in axs[0].get_xticklabels():
298
- # tick.set_color(classification_cmap[tick.get_text()])
299
- #
300
- # # Identify positions for subclass delimiters in the cluster graph
301
- # subclass_ends = df_subset.groupby('subclass').size().cumsum()
302
- # subclass_positions = subclass_ends - 1
303
- #
304
- # # For the third plot (clusters):
305
- # for pos in subclass_positions[:-1]:
306
- # axs[2].axvline(pos + 0.5, color='gray', linestyle='--')
307
- #
308
- # # For the first plot (subclass), simply draw lines between unique subclasses
309
- # for i in range(1, len(df_subset['subclass'].unique())):
310
- # axs[0].axvline(i - 0.5, color='gray', linestyle='--')
311
- #
312
- # # For the second plot (supertype), the position will be based on unique supertypes per subclass
313
- # supertype_ends = df_subset.groupby('subclass')['supertype'].nunique().cumsum()
314
- # supertype_positions = supertype_ends - 1
315
- # for pos in supertype_positions[:-1]:
316
- # axs[1].axvline(pos + 0.5, color='gray', linestyle='--')
317
- #
318
- # # For the first plot (subclass):
319
- # subclasses = df_subset['subclass'].unique()
320
- # start = -.5
321
- # for i, subclass in enumerate(subclasses):
322
- # end = i + 0.5
323
- # color = classification_cmap[subclass]
324
- # axs[0].axvspan(start + .05, end - .05, facecolor=color, alpha=0.15)
325
- # start = end
326
- #
327
- # # For the second plot (supertype), determine filling areas based on unique supertypes per subclass
328
- # supertype_ends = df_subset.groupby('subclass')['supertype'].nunique().cumsum()
329
- # supertype_positions = supertype_ends - 1
330
- #
331
- # previous_position = -0.5 # initialize to start from the first entry
332
- # for idx, pos in enumerate(supertype_positions):
333
- # current_position = pos + 0.5
334
- # # Retrieve the subclass name for the current supertype
335
- # subclass_name = df_subset['subclass'].unique()[idx]
336
- # color = classification_cmap[subclass_name]
337
- #
338
- # axs[1].axvspan(previous_position + 0.2, current_position - .2, facecolor=color, alpha=0.15)
339
- #
340
- # previous_position = current_position # set for the next iteration
341
- #
342
- # ####third plot filling
343
- # # Get a mapping of subclasses to their dominant cluster
344
- # subclass_to_cluster = df_subset.groupby('subclass')['cluster'].apply(lambda x: x.value_counts().idxmax())
345
- #
346
- # # Define previous position to help us fill areas between borders
347
- # prev_pos = 0
348
- #
349
- # # Iterate over the subclass positions and the corresponding subclasses
350
- # for idx, (subclass, cluster) in enumerate(subclass_to_cluster.items()):
351
- # # Get the color for this subclass's dominant cluster from your cmap
352
- # color_value = classification_cmap[cluster]
353
- #
354
- # # End position is either the next border position or the end of the plot
355
- # end_pos = subclass_positions.iloc[idx] if idx < len(subclass_positions) else len(df_subset['cluster']) - 1
356
- #
357
- # # Fill the area with the given color
358
- # axs[2].fill_between([prev_pos, end_pos], 0, 100, color=color_value, alpha=0.15)
359
- #
360
- # # Update the previous position to the current position
361
- # prev_pos = end_pos + 1
362
- #
363
- # # Adjust the xlim of each axis
364
- # axs[0].set_xlim(-0.5, len(df_subset['subclass'].unique()) - 0.5)
365
- # axs[1].set_xlim(-0.5, len(df_subset['supertype'].unique()) - 0.5)
366
- # axs[2].set_xlim(-.8, len(df_subset['cluster'].unique()))
367
- #
368
- # # Now, add legend in the fourth axis:
369
- # patches = [plt.Line2D([0], [0], color=classification_cmap[c], lw=8) for c in df_subset["subclass"].unique()]
370
- # labels = list(df_subset["subclass"].unique())
371
- #
372
- # axs[3].legend(patches, labels, loc='center', ncol=6, handlelength=1.8, handleheight=1)
373
- # axs[3].axis('off') # Hide axis
374
- #
375
- # sns.despine(bottom=True)
376
- #
377
- #
378
- # group_selector = pn.widgets.Select(name='Group', options=neuron_cluster_groups_order, value=neuron_cluster_groups_order[0])
379
- # gene_selector = pn.widgets.Select(name='Gene', options=list(selected_genes_cl), value=selected_genes_cl[0])
380
- #
381
- #
382
- # @pn.depends(group_selector, gene_selector)
383
- # def interactive_plot(group, gene):
384
- # global global_saved_fig, group_g, gene_g
385
- # data = joined_with_membership_sub[joined_with_membership_sub["cluster_group_name"] == group]
386
- # data = data.groupby(["cluster_group_name", "class", "subclass", "supertype", "cluster"])[gene].apply(
387
- # percentage_above_threshold).reset_index()
388
- # data = data[data["cluster_group_name"] != "WholeBrain"]
389
- # data["cluster_group_name"] = pd.Categorical(data["cluster_group_name"], categories=neuron_cluster_groups_order,
390
- # ordered=True)
391
- # data = data.sort_values(by=["cluster_group_name", "class"])
392
- #
393
- # data.rename(columns={gene: f'{gene} prevalence (%)'}, inplace=True)
394
- #
395
- # fig = plt.figure(figsize=(25, 5 * data['class'].nunique()))
396
- # gs = gridspec.GridSpec(data['class'].nunique(), 1)
397
- #
398
- # for n, cls in enumerate(data['class'].unique()):
399
- # df_subset = data[data['class'] == cls]
400
- # subfig = fig.add_subfigure(gs[n, :])
401
- # subfig.subplots_adjust(left=0.05, right=.95, bottom=0.01)
402
- # plot_class_expression_split_by_categories(subfig, cls, df_subset, gene)
403
- #
404
- # global_saved_fig = fig
405
- # group_g = group
406
- # gene_g = gene
407
- #
408
- # fig.suptitle(group, y=1.04, fontweight='bold', fontsize=20);
409
- # #print(group, gene)
410
- #
411
- # return fig
412
- #
413
- # dashboard_receptor_centric = pn.Column(
414
- # pn.Row(group_selector, gene_selector),
415
- # pn.pane.Matplotlib(interactive_plot, sizing_mode = 'stretch_width')
416
- # )
417
- #
418
- #
419
- # def update_subclass_selector(event):
420
- # selected_classes = event.new
421
- # if "None" in selected_classes or not selected_classes:
422
- # all_subclasses = sorted(joined_sub["subclass"].unique().tolist())
423
- # else:
424
- # all_subclasses = sorted(joined_sub[joined_sub["class"].isin(selected_classes)]["subclass"].unique().tolist())
425
- # subclass_selector.options = ["None"] + all_subclasses
426
- # subclass_selector.value = ["None"]
427
- #
428
- #
429
- # class_selector = pn.widgets.MultiSelect(name='Class selector',
430
- # options=["None"] + sorted(joined_sub["class"].unique().tolist()),
431
- # value=[joined_sub["class"].unique()[0]])
432
- # subclass_selector = pn.widgets.MultiSelect(name='Subclass selector',
433
- # options=["None"] + sorted(joined_sub["subclass"].unique().tolist()),
434
- # value=["None"])
435
- # groupby_selector = pn.widgets.Select(name='Group by', options=["class", "subclass", "supertype", "cluster"],
436
- # value="class")
437
- # sortby_selector = pn.widgets.Select(name='Sort by', options=["class"] + list(selected_genes_cl), value="class")
438
- #
439
- # class_selector.param.watch(update_subclass_selector, 'value')
440
- #
441
- #
442
- # @pn.depends(class_selector, subclass_selector, groupby_selector, sortby_selector)
443
- # def heatmap_cell_centric(class_, subclass, groupby, sortby):
444
- # if class_ != ["None"] or subclass != ["None"]:
445
- #
446
- # filtered_data = joined_sub
447
- # if "None" not in class_:
448
- # filtered_data = filtered_data[filtered_data["class"].isin(class_)]
449
- # if "None" not in subclass:
450
- # filtered_data = filtered_data[filtered_data["subclass"].isin(subclass)]
451
- #
452
- # if sortby == "class":
453
- # sortby = groupby
454
- # ascending = True
455
- # else:
456
- # ascending = False
457
- #
458
- # num_rows = len(filtered_data.groupby(groupby))
459
- # fig_height = max(5, num_rows * 0.2) # Set a minimum height and scale per row
460
- #
461
- # fig, ax = plt.subplots(figsize=(10, fig_height))
462
- # sns.heatmap(
463
- # filtered_data.groupby(groupby)[selected_genes_cl].apply(percentage_above_threshold).sort_values(sortby,
464
- # ascending=ascending),
465
- # yticklabels=True, cmap=sns.light_palette("#CC5656", as_cmap=True), ax=ax, cbar=False, vmax=90)
466
- #
467
- # for ytick in ax.get_xticklabels():
468
- # ytick.set_color(genes_cmap_rgb[ytick.get_text()])
469
- # for ytick in ax.get_yticklabels():
470
- # ytick.set_color(classification_cmap[ytick.get_text()])
471
- #
472
- # plt.tight_layout()
473
- # else:
474
- # fig = plt.figure(figsize=(10, 5)) # Default size if no data
475
- # plt.text(0.5, 0.5, 'No data to display', horizontalalignment='center', verticalalignment='center')
476
- #
477
- # return fig
478
- #
479
- #
480
- # dashboard_cell_centric = pn.Column(pn.Row(class_selector, subclass_selector, groupby_selector, sortby_selector),
481
- # pn.pane.Matplotlib(heatmap_cell_centric, sizing_mode='stretch_width'))
482
- #
483
- # title = "5-HT Transcriptomic"
484
- # pn.template.BootstrapTemplate(
485
- # header_background="#F9B9B7",
486
- # logo="https://upload.wikimedia.org/wikipedia/commons/5/51/Logo_Charite.svg",
487
- # title="5-HT Transcriptomics",
488
- # main=pn.Column(
489
- # pn.Tabs(
490
- # ("Spatial", dashboard_spatial), # Add your spatial content here
491
- # ("Receptor-centric", dashboard_receptor_centric),
492
- # ("Cell-centric", dashboard_cell_centric),
493
- # dynamic=True
494
- # )
495
- # )
496
- # ).servable(title=title)
497
 
498
  title = "5-HT Transcriptomic"
499
  pn.template.BootstrapTemplate(
500
  header_background="#F9B9B7",
501
  logo="https://upload.wikimedia.org/wikipedia/commons/5/51/Logo_Charite.svg",
502
  title="5-HT Transcriptomics",
503
- main=pn.Column(df_pane
 
 
 
 
 
504
  )
 
505
  ).servable(title=title)
506
 
 
 
 
 
 
 
 
 
 
507
 
 
13
  import matplotlib.colors as plt_colors
14
  import pickle
15
 
 
16
  genes_families = {
17
  'Htr1': ['Htr1a', 'Htr1b', 'Htr1d', 'Htr1f'],
18
  'Htr2': ['Htr2a', 'Htr2b', 'Htr2c'],
 
69
 
70
  print(joined_sub.columns)
71
 
72
+ #df_pane = pn.pane.DataFrame(joined_sub, width=400)
73
+
74
+ classification_cmap = joined_sub.drop_duplicates(subset='subclass').set_index('subclass')['subclass_color'].to_dict()
75
+ classification_cmap.update(joined_sub.drop_duplicates(subset='supertype').set_index('supertype')['subclass_color'].to_dict())
76
+ classification_cmap.update(joined_sub.drop_duplicates(subset='cluster').set_index('cluster')['subclass_color'].to_dict())
77
+ classification_cmap.update(joined_sub.drop_duplicates(subset='class').set_index('class')['class_color'].to_dict())
78
+
79
+
80
+ class MERFISH_viz(param.Parameterized):
81
+ dataset_selector = param.Selector(objects=datasets)
82
+ brain_section_index = param.Integer(default=0, bounds=(
83
+ 0, sub_cell_expression[datasets[0]]["brain_section_label"].unique().shape[0]))
84
+ gene_selector = param.ObjectSelector(default=selected_genes[0], objects=selected_genes.tolist())
85
+ class_selector = param.ListSelector(default=sorted(sub_cell_expression[dataset]['class'].unique()),
86
+ objects=sorted(sub_cell_expression[dataset]['class'].unique()))
87
+ subclass_selector = param.ListSelector(default=sorted(sub_cell_expression[dataset]['subclass'].unique()),
88
+ objects=sorted(sub_cell_expression[dataset]['subclass'].unique()))
89
+
90
+ # Naming the keyword arguments `**params` is purely a convention.
91
+ def __init__(self, sub_cell_expression, sel_dataset, sel_class, sel_subclass, brain_section_index, **params):
92
+ super().__init__(**params)
93
+ self.sub_cell_expression = sub_cell_expression
94
+ self.current_data = self.sub_cell_expression[sel_dataset]
95
+ self.filtered_data = self.current_data[
96
+ self.current_data['class'].isin(sel_class) & self.current_data['subclass'].isin(sel_subclass)]
97
+
98
+ brain_section = self.current_data['brain_section_label'].unique()[brain_section_index]
99
+ section = self.filtered_data[self.filtered_data['brain_section_label'] == brain_section]
100
+
101
+ self.section = section[section['parcellation_division'] != "unassigned"]
102
+
103
+ self.control_panel = pn.Row(
104
+ pn.Param(self.param['dataset_selector']),
105
+ pn.Param(self.param['brain_section_index']),
106
+ pn.Param(self.param['gene_selector']),
107
+ pn.Param(self.param['class_selector']),
108
+ pn.Param(self.param['subclass_selector'])
109
+ )
110
+
111
+ @param.depends('dataset_selector', 'brain_section_index', 'gene_selector', 'class_selector', 'subclass_selector')
112
+ def view(self):
113
+ return pn.Column(
114
+ f'Selected dataset: {self.dataset_selector}',
115
+ f'Brain Section Index: {self.brain_section_index}',
116
+ f'Selected Gene: {self.gene_selector}',
117
+ f'Selected Classes: {self.class_selector}, {self.subclass_selector}')
118
+
119
+ @pn.depends("filter_by_class_subclass", "gene_selector", "brain_section_index")
120
+ def plot_expr_across_slices(self):
121
+ curve_data = self.filtered_data[self.filtered_data[self.gene_selector] > 0].groupby('brain_section_label')[
122
+ self.gene_selector].mean()
123
+ curve_data.rename(f"Expression {self.gene_selector}", inplace=True)
124
+ curve = hv.Curve(curve_data, label=f'Log(CPM) {self.gene_selector}').opts(xaxis=None, height=140,
125
+ responsive=True, active_tools=[])
126
+
127
+ grouped_data = self.filtered_data.groupby('brain_section_label')[self.gene_selector].apply(
128
+ percentage_above_threshold_MER).reset_index()
129
+ grouped_data.rename(columns={self.gene_selector: f"% expressing {self.gene_selector}"}, inplace=True)
130
+ percentage_curve = hv.Curve(grouped_data, 'brain_section_label', f"% expressing {self.gene_selector}",
131
+ label=f'Percentage expressing {self.gene_selector}').opts(xaxis=None,
132
+ height=140,
133
+ responsive=True,
134
+ active_tools=[])
135
+
136
+ vline = hv.VLine(self.brain_section_index).opts(line_color='red', line_width=2)
137
+ percentage_of_all_cells = ((self.filtered_data.groupby(
138
+ 'brain_section_label').size() / self.current_data.groupby('brain_section_label').size()) * 100).fillna(0)
139
+ percentage_of_all_cells.name = "% of all cells"
140
+ ratio_cells = hv.Curve(percentage_of_all_cells, 'brain_section_label', "% of all cells",
141
+ label='Percentage of all cells').opts(xaxis=None,
142
+ height=100,
143
+ responsive=True,
144
+ active_tools=[])
145
+
146
+ return hv.Layout([(ratio_cells * vline), (curve * vline), (percentage_curve * vline)]).cols(1)
147
+
148
+ @pn.depends("filter_by_class_subclass", "gene_selector", "brain_section_index")
149
+ def plot_bar(self):
150
+ color_map = self.section.groupby('parcellation_structure')['parcellation_structure_color'].first().to_dict()
151
+
152
+ hv_ds = hv.Dataset(self.section.groupby(['parcellation_structure'])[self.gene_selector].apply(
153
+ percentage_above_threshold_MER).sort_values(ascending=False).head(20).reset_index(),
154
+ kdims=['parcellation_structure'], vdims=[self.gene_selector])
155
+
156
+ # Create the vertical Bar chart with rotated xticklabels
157
+ bar_plot = hv.Bars(hv_ds).opts(
158
+ color=dim('parcellation_structure').categorize(color_map, 'gray'),
159
+ active_tools=[],
160
+ tools=["hover"],
161
+ responsive=True,
162
+ frame_height=100,
163
+ invert_axes=False,
164
+ xrotation=90 # Rotate xticklabels by 90 degrees
165
+ )
166
+
167
+ grouped_data = self.section.groupby(['parcellation_structure'])[self.gene_selector].apply(
168
+ percentage_above_threshold_MER).sort_values(
169
+ ascending=False).head(30).reset_index()
170
+ counts = self.section['parcellation_structure'].value_counts().reindex(
171
+ grouped_data['parcellation_structure']).fillna(0)
172
+
173
+ labels = hv.Labels({'x': grouped_data['parcellation_structure'], 'y': grouped_data[self.gene_selector], 'text': counts},
174
+ ['x', 'y'], 'text').opts(text_font_size='8pt', text_color="black", yoffset=-5)
175
+
176
+ return bar_plot * labels
177
+
178
+ @pn.depends("filter_by_class_subclass", "gene_selector", "get_section")
179
+ def plot_section(self):
180
+ plot1 = hv.Points(data=self.section, kdims=['x', 'y'],
181
+ vdims=[self.gene_selector, 'parcellation_structure', 'parcellation_substructure']).opts(
182
+ width=550, colorbar=True, cmap='rocket_r', size=2, color=self.gene_selector)
183
+ plot2 = hv.NdOverlay({division: hv.Points(self.section[self.section['parcellation_division'] == division],
184
+ ['x', 'y'], ['parcellation_division_color', 'parcellation_structure',
185
+ 'parcellation_substructure']).opts(
186
+ color='parcellation_division_color', size=2) for division in
187
+ self.section[self.section['parcellation_category'] == "grey"][
188
+ 'parcellation_division'].unique()}, kdims='parcellation_division').opts(
189
+ legend_position='right', width=650, show_legend=True)
190
+
191
+ common_opts = opts.Points(height=500, invert_yaxis=True, xaxis=None, yaxis=None, show_grid=False,
192
+ active_tools=[], tools=["hover"])
193
+
194
+ return (plot1 + plot2).opts(common_opts)
195
+
196
+ @param.depends("brain_section_index", watch=True)
197
+ def get_section(self):
198
+ brain_section = self.current_data['brain_section_label'].unique()[self.brain_section_index]
199
+ section = self.filtered_data[self.filtered_data['brain_section_label'] == brain_section]
200
+ self.section = section[section['parcellation_division'] != "unassigned"]
201
+
202
+ @param.depends('dataset_selector', watch=True)
203
+ def update_current_data(self):
204
+ self.current_data = self.sub_cell_expression[self.dataset_selector]
205
+ self.brain_section_index = 0
206
+ self.brain_section_index.bounds = (0, self.current_data["brain_section_label"].unique().shape[0])
207
+
208
+ @param.depends("update_current_data", 'class_selector', 'subclass_selector', watch=True)
209
+ def filter_by_class_subclass(self):
210
+ self.filtered_data = self.current_data[
211
+ self.current_data['class'].isin(self.class_selector) & self.current_data['subclass'].isin(
212
+ self.subclass_selector)]
213
+
214
+ @param.depends("update_current_data", 'class_selector', watch=True)
215
+ def update_subclasses(self):
216
+ self.param.subclass_selector.objects = sorted(
217
+ self.current_data[self.current_data['class'].isin(self.class_selector)]['subclass'].unique())
218
+ self.subclass_selector = sorted(
219
+ self.current_data[(self.current_data['class'].isin(self.class_selector))]['subclass'].unique())
220
+
221
+
222
+ viz = MERFISH_viz(sub_cell_expression, datasets[0], sub_cell_expression[datasets[0]]["class"].unique(),
223
+ sub_cell_expression[dataset]["subclass"].unique(), 0)
224
+
225
+ # Title of the paper and authors
226
+ # Custom HTML for the title
227
+ custom_title_html = """
228
+ <div style="text-align: center; max-width: 1200px; margin: 20px auto;">
229
+ <h1 style="font-weight: 900; font-size: 3rem; margin: 0rem">
230
+ Transcriptomic Mapping of the 5-HT Receptor Landscape
231
+ </h1>
232
+ <h2 style="font-weight: 450; font-size: 1rem; margin: 0rem">
233
+ Roberto De Filippo<sup>#</sup>, Dietmar Schmitz
234
+ </h2>
235
+ <h2 style="font-weight: 450; font-size: 1rem; margin: 0rem">
236
+ <sup>#</sup>Corresponding author
237
+ </h2>
238
+ <h2 style="font-weight: 450; font-size: 1rem; margin: 0rem">
239
+ [<a href="https://github.com/RobertoDF/5-HT2A-MERFISH" style="color:blue;">Article</a>]
240
+ [<a href="https://github.com/RobertoDF/5-HT2A-MERFISH" style="color:blue;">Github</a>]
241
+ </h2>
242
+ <h2 style="font-weight: 450; font-size: 1rem;">
243
+ Custom visualizer for MERFISH dataset provided by [<a href="https://www.nature.com/articles/s41586-023-06808-9" style="color:blue;">Zhang et al., 2023</a>] </h2>
244
+ <h2 style="font-weight: 450; font-size: 1rem;">
245
+ By <b>Roberto De Filippo</b>
246
+ </h2>
247
+ </div>
248
+ """
249
+
250
+ # Create a Panel HTML pane with the custom title
251
+ custom_title_pane = pn.pane.HTML(custom_title_html, sizing_mode='stretch_width')
252
+
253
+ dashboard_spatial = pn.Column(custom_title_pane, viz.control_panel, viz.plot_expr_across_slices, viz.plot_bar, viz.plot_section)
254
+
255
+
256
+ def plot_class_expression_split_by_categories(subfig, cls, df_subset, gene):
257
+ axs = subfig.subplots(4, 1)
258
+ subfig.subplots_adjust(left=0.05, right=.95)
259
+
260
+ sns.violinplot(data=df_subset, y=f'{gene} prevalence (%)', x='subclass', hue='subclass', ax=axs[0],
261
+ palette=classification_cmap, fill=False)
262
+
263
+ # Set the title with desired modifications
264
+ title = axs[0].set_title(cls, color=classification_cmap[cls], fontweight='bold', fontsize=20)
265
+ title.set_path_effects([path_effects.withStroke(linewidth=3, foreground='black')])
266
+
267
+ subfig.set_facecolor(mcolors.to_rgba(classification_cmap[cls], alpha=0.15))
268
+
269
+ axs[0].set_ylim(0, 100) # Set y-axis limit to 1
270
+ axs[0].xaxis.set_ticks_position('top')
271
+ axs[0].tick_params(axis='x', length=0)
272
+
273
+ sns.violinplot(data=df_subset, y=f'{gene} prevalence (%)', x='supertype', hue='supertype', ax=axs[1],
274
+ palette=classification_cmap, fill=False)
275
+ axs[1].set_title(cls)
276
+ axs[1].set_ylim(0, 100) # Set y-axis limit to 1
277
+
278
+ sns.barplot(data=df_subset, y=f'{gene} prevalence (%)', x='cluster', hue='cluster', ax=axs[2],
279
+ palette=classification_cmap)
280
+ axs[2].set_title(cls)
281
+ axs[2].set_ylim(0, 100) # Set y-axis limit to 1
282
+
283
+ axs[2].set(ylabel='')
284
+ axs[0].set(ylabel='')
285
+ axs[2].set(xticks=[], xlabel='')
286
+ axs[1].set(xticks=[], xlabel='')
287
+ axs[0].set(xticks=[], xlabel='')
288
+ axs[0].set(xlabel='')
289
+ axs[2].set(xticks=[], xlabel='')
290
+ axs[2].set(xticks=[], xlabel='')
291
+ axs[1].set_title('')
292
+ axs[2].set_title('')
293
+ plt.draw()
294
+ for tick in axs[0].get_xticklabels():
295
+ tick.set_color(classification_cmap[tick.get_text()])
296
+
297
+ # Identify positions for subclass delimiters in the cluster graph
298
+ subclass_ends = df_subset.groupby('subclass').size().cumsum()
299
+ subclass_positions = subclass_ends - 1
300
+
301
+ # For the third plot (clusters):
302
+ for pos in subclass_positions[:-1]:
303
+ axs[2].axvline(pos + 0.5, color='gray', linestyle='--')
304
+
305
+ # For the first plot (subclass), simply draw lines between unique subclasses
306
+ for i in range(1, len(df_subset['subclass'].unique())):
307
+ axs[0].axvline(i - 0.5, color='gray', linestyle='--')
308
+
309
+ # For the second plot (supertype), the position will be based on unique supertypes per subclass
310
+ supertype_ends = df_subset.groupby('subclass')['supertype'].nunique().cumsum()
311
+ supertype_positions = supertype_ends - 1
312
+ for pos in supertype_positions[:-1]:
313
+ axs[1].axvline(pos + 0.5, color='gray', linestyle='--')
314
+
315
+ # For the first plot (subclass):
316
+ subclasses = df_subset['subclass'].unique()
317
+ start = -.5
318
+ for i, subclass in enumerate(subclasses):
319
+ end = i + 0.5
320
+ color = classification_cmap[subclass]
321
+ axs[0].axvspan(start + .05, end - .05, facecolor=color, alpha=0.15)
322
+ start = end
323
+
324
+ # For the second plot (supertype), determine filling areas based on unique supertypes per subclass
325
+ supertype_ends = df_subset.groupby('subclass')['supertype'].nunique().cumsum()
326
+ supertype_positions = supertype_ends - 1
327
+
328
+ previous_position = -0.5 # initialize to start from the first entry
329
+ for idx, pos in enumerate(supertype_positions):
330
+ current_position = pos + 0.5
331
+ # Retrieve the subclass name for the current supertype
332
+ subclass_name = df_subset['subclass'].unique()[idx]
333
+ color = classification_cmap[subclass_name]
334
+
335
+ axs[1].axvspan(previous_position + 0.2, current_position - .2, facecolor=color, alpha=0.15)
336
+
337
+ previous_position = current_position # set for the next iteration
338
+
339
+ ####third plot filling
340
+ # Get a mapping of subclasses to their dominant cluster
341
+ subclass_to_cluster = df_subset.groupby('subclass')['cluster'].apply(lambda x: x.value_counts().idxmax())
342
+
343
+ # Define previous position to help us fill areas between borders
344
+ prev_pos = 0
345
+
346
+ # Iterate over the subclass positions and the corresponding subclasses
347
+ for idx, (subclass, cluster) in enumerate(subclass_to_cluster.items()):
348
+ # Get the color for this subclass's dominant cluster from your cmap
349
+ color_value = classification_cmap[cluster]
350
+
351
+ # End position is either the next border position or the end of the plot
352
+ end_pos = subclass_positions.iloc[idx] if idx < len(subclass_positions) else len(df_subset['cluster']) - 1
353
+
354
+ # Fill the area with the given color
355
+ axs[2].fill_between([prev_pos, end_pos], 0, 100, color=color_value, alpha=0.15)
356
+
357
+ # Update the previous position to the current position
358
+ prev_pos = end_pos + 1
359
+
360
+ # Adjust the xlim of each axis
361
+ axs[0].set_xlim(-0.5, len(df_subset['subclass'].unique()) - 0.5)
362
+ axs[1].set_xlim(-0.5, len(df_subset['supertype'].unique()) - 0.5)
363
+ axs[2].set_xlim(-.8, len(df_subset['cluster'].unique()))
364
+
365
+ # Now, add legend in the fourth axis:
366
+ patches = [plt.Line2D([0], [0], color=classification_cmap[c], lw=8) for c in df_subset["subclass"].unique()]
367
+ labels = list(df_subset["subclass"].unique())
368
+
369
+ axs[3].legend(patches, labels, loc='center', ncol=6, handlelength=1.8, handleheight=1)
370
+ axs[3].axis('off') # Hide axis
371
+
372
+ sns.despine(bottom=True)
373
+
374
+
375
+ group_selector = pn.widgets.Select(name='Group', options=neuron_cluster_groups_order, value=neuron_cluster_groups_order[0])
376
+ gene_selector = pn.widgets.Select(name='Gene', options=list(selected_genes_cl), value=selected_genes_cl[0])
377
+
378
+
379
+ @pn.depends(group_selector, gene_selector)
380
+ def interactive_plot(group, gene):
381
+ global global_saved_fig, group_g, gene_g
382
+ data = joined_with_membership_sub[joined_with_membership_sub["cluster_group_name"] == group]
383
+ data = data.groupby(["cluster_group_name", "class", "subclass", "supertype", "cluster"])[gene].apply(
384
+ percentage_above_threshold).reset_index()
385
+ data = data[data["cluster_group_name"] != "WholeBrain"]
386
+ data["cluster_group_name"] = pd.Categorical(data["cluster_group_name"], categories=neuron_cluster_groups_order,
387
+ ordered=True)
388
+ data = data.sort_values(by=["cluster_group_name", "class"])
389
+
390
+ data.rename(columns={gene: f'{gene} prevalence (%)'}, inplace=True)
391
+
392
+ fig = plt.figure(figsize=(25, 5 * data['class'].nunique()))
393
+ gs = gridspec.GridSpec(data['class'].nunique(), 1)
394
+
395
+ for n, cls in enumerate(data['class'].unique()):
396
+ df_subset = data[data['class'] == cls]
397
+ subfig = fig.add_subfigure(gs[n, :])
398
+ subfig.subplots_adjust(left=0.05, right=.95, bottom=0.01)
399
+ plot_class_expression_split_by_categories(subfig, cls, df_subset, gene)
400
+
401
+ global_saved_fig = fig
402
+ group_g = group
403
+ gene_g = gene
404
+
405
+ fig.suptitle(group, y=1.04, fontweight='bold', fontsize=20);
406
+ #print(group, gene)
407
+
408
+ return fig
409
+
410
+ dashboard_receptor_centric = pn.Column(
411
+ pn.Row(group_selector, gene_selector),
412
+ pn.pane.Matplotlib(interactive_plot, sizing_mode = 'stretch_width')
413
+ )
414
+
415
+
416
+ def update_subclass_selector(event):
417
+ selected_classes = event.new
418
+ if "None" in selected_classes or not selected_classes:
419
+ all_subclasses = sorted(joined_sub["subclass"].unique().tolist())
420
+ else:
421
+ all_subclasses = sorted(joined_sub[joined_sub["class"].isin(selected_classes)]["subclass"].unique().tolist())
422
+ subclass_selector.options = ["None"] + all_subclasses
423
+ subclass_selector.value = ["None"]
424
+
425
+
426
+ class_selector = pn.widgets.MultiSelect(name='Class selector',
427
+ options=["None"] + sorted(joined_sub["class"].unique().tolist()),
428
+ value=[joined_sub["class"].unique()[0]])
429
+ subclass_selector = pn.widgets.MultiSelect(name='Subclass selector',
430
+ options=["None"] + sorted(joined_sub["subclass"].unique().tolist()),
431
+ value=["None"])
432
+ groupby_selector = pn.widgets.Select(name='Group by', options=["class", "subclass", "supertype", "cluster"],
433
+ value="class")
434
+ sortby_selector = pn.widgets.Select(name='Sort by', options=["class"] + list(selected_genes_cl), value="class")
435
+
436
+ class_selector.param.watch(update_subclass_selector, 'value')
437
+
438
+
439
+ @pn.depends(class_selector, subclass_selector, groupby_selector, sortby_selector)
440
+ def heatmap_cell_centric(class_, subclass, groupby, sortby):
441
+ if class_ != ["None"] or subclass != ["None"]:
442
+
443
+ filtered_data = joined_sub
444
+ if "None" not in class_:
445
+ filtered_data = filtered_data[filtered_data["class"].isin(class_)]
446
+ if "None" not in subclass:
447
+ filtered_data = filtered_data[filtered_data["subclass"].isin(subclass)]
448
+
449
+ if sortby == "class":
450
+ sortby = groupby
451
+ ascending = True
452
+ else:
453
+ ascending = False
454
+
455
+ num_rows = len(filtered_data.groupby(groupby))
456
+ fig_height = max(5, num_rows * 0.2) # Set a minimum height and scale per row
457
+
458
+ fig, ax = plt.subplots(figsize=(10, fig_height))
459
+ sns.heatmap(
460
+ filtered_data.groupby(groupby)[selected_genes_cl].apply(percentage_above_threshold).sort_values(sortby,
461
+ ascending=ascending),
462
+ yticklabels=True, cmap=sns.light_palette("#CC5656", as_cmap=True), ax=ax, cbar=False, vmax=90)
463
+
464
+ for ytick in ax.get_xticklabels():
465
+ ytick.set_color(genes_cmap_rgb[ytick.get_text()])
466
+ for ytick in ax.get_yticklabels():
467
+ ytick.set_color(classification_cmap[ytick.get_text()])
468
+
469
+ plt.tight_layout()
470
+ else:
471
+ fig = plt.figure(figsize=(10, 5)) # Default size if no data
472
+ plt.text(0.5, 0.5, 'No data to display', horizontalalignment='center', verticalalignment='center')
473
+
474
+ return fig
475
+
476
+
477
+ dashboard_cell_centric = pn.Column(pn.Row(class_selector, subclass_selector, groupby_selector, sortby_selector),
478
+ pn.pane.Matplotlib(heatmap_cell_centric, sizing_mode='stretch_width'))
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
479
 
480
  title = "5-HT Transcriptomic"
481
  pn.template.BootstrapTemplate(
482
  header_background="#F9B9B7",
483
  logo="https://upload.wikimedia.org/wikipedia/commons/5/51/Logo_Charite.svg",
484
  title="5-HT Transcriptomics",
485
+ main=pn.Column(
486
+ pn.Tabs(
487
+ ("Spatial", dashboard_spatial), # Add your spatial content here
488
+ ("Receptor-centric", dashboard_receptor_centric),
489
+ ("Cell-centric", dashboard_cell_centric),
490
+ dynamic=True
491
  )
492
+ )
493
  ).servable(title=title)
494
 
495
+ # title = "5-HT Transcriptomic"
496
+ # pn.template.BootstrapTemplate(
497
+ # header_background="#F9B9B7",
498
+ # logo="https://upload.wikimedia.org/wikipedia/commons/5/51/Logo_Charite.svg",
499
+ # title="5-HT Transcriptomics",
500
+ # main=pn.Column(df_pane
501
+ # )
502
+ # ).servable(title=title)
503
+
504