-
Notifications
You must be signed in to change notification settings - Fork 3
/
Copy pathVizHeatmap.R
695 lines (615 loc) · 31.3 KB
/
VizHeatmap.R
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
## ---------------------------
##
## Script name: Visualization
##
## Purpose of script: Data Visualisation of the MetaProViz analysis to aid biological interpretation
##
## Author: Dimitrios Prymidis and Christina Schmidt
##
## Date Created: 2022-10-28
##
## Copyright (c) Dimitrios Prymidis and Christina Schmidt
## Email:
##
## ---------------------------
##
## Notes:
##
##
## ---------------------------
###############################
### ### ### Heatmap ### ### ###
###############################
#' Heatmap visualization
#'
#' @param InputData DF with unique sample identifiers as row names and
#' metabolite numerical values in columns with metabolite identifiers as column
#' names. Includes experimental design and outlier column.
#' @param SettingsInfo \emph{Optional: } NULL or Named vector where you can
#' include vectors or lists for annotation c(individual_Metab=
#' "ColumnName_SettingsFile_Metab",individual_Sample=
#' "ColumnName_SettingsFile_Sample",
#' color_Metab="ColumnName_SettingsFile_Metab", color_Sample=
#' list("ColumnName_SettingsFile_Sample",
#' "ColumnName_SettingsFile_Sample",...)).\strong{Default = NULL}
#' @param SettingsFile_Sample DF which contains information about the samples,
#' which will be combined with your input data based on the unique sample
#' identifiers. and other columns with required PlotSettingInfo.\strong{Default
#' = NULL}
#' @param SettingsFile_Metab \emph{Optional: } DF with column "Metabolite"
#' including the Metabolite names (needs to match Metabolite names of
#' Input_data) and other columns with required PlotSettingInfo. \strong{Default
#' = NULL}
#' @param PlotName \emph{Optional: } String which is added to the output files of the plot
#' @param Scale \emph{Optional: } String with the information for Scale row, column or none. \strong{Default = row}
#' @param SaveAs_Plot \emph{Optional: } Select the file type of output plots. Options are svg, pdf, png or NULL. \strong{Default = "svg"}
#' @param Enforce_FeatureNames \emph{Optional: } If there are more than 100 features no rownames will be shown, which is due to readability. You can Enforce this by setting this parameter to TRUE. \strong{Default = FALSE}
#' @param Enforce_SampleNames \emph{Optional: } If there are more than 50 sampless no colnames will be shown, which is due to readability. You can Enforce this by setting this parameter to TRUE. \strong{Default = FALSE}
#' @param PrintPlot \emph{Optional: } print the plots to the active graphic
#' device.
#' @param FolderPath {Optional:} String which is added to the resulting folder name \strong{default: NULL}
#'
#' @return List with two elements: Plot and Plot_Sized
#'
#' @examples
#' Intra <- ToyData("IntraCells_Raw")
#' Res <- MetaProViz::VizHeatmap(InputData=Intra[,-c(1:3)])
#'
#' @keywords Heatmap
#'
#' @importFrom ggplot2 ggplot theme
#' @importFrom dplyr rename select
#' @importFrom magrittr %>% %<>%
#' @importFrom tibble rownames_to_column column_to_rownames
#' @importFrom logger log_trace
#' @export
VizHeatmap <- function(InputData,
SettingsInfo= NULL,
SettingsFile_Sample=NULL,
SettingsFile_Metab= NULL,
PlotName= "",
Scale = "row",
SaveAs_Plot = "svg",
Enforce_FeatureNames= FALSE,
Enforce_SampleNames= FALSE,
PrintPlot=TRUE,
FolderPath = NULL
){
## ------------ Create log file ----------- ##
MetaProViz_Init()
## ------------ Check Input files ----------- ##
# HelperFunction `CheckInput`
CheckInput(InputData=InputData,
SettingsFile_Sample=SettingsFile_Sample,
SettingsFile_Metab=SettingsFile_Metab,
SettingsInfo=SettingsInfo,
SaveAs_Plot=SaveAs_Plot,
SaveAs_Table=NULL,
CoRe=FALSE,
PrintPlot= PrintPlot)
# CheckInput` Specific
if(is.logical(Enforce_FeatureNames) == FALSE | is.logical(Enforce_SampleNames) == FALSE){
message <- paste0("Check input. The Enforce_FeatureNames and Enforce_SampleNames value should be either =TRUE or = FALSE.")
logger::log_trace(paste("Error ", message, sep=""))
stop(message)
}
Scale_options <- c("row","column", "none")
if(Scale %in% Scale_options == FALSE){
message <- paste0("Check input. The selected Scale option is not valid. Please select one of the folowwing: ",paste(Scale_options,collapse = ", "),"." )
logger::log_trace(paste("Error ", message, sep=""))
stop(message)
}
## ------------ Create Results output folder ----------- ##
if(is.null(SaveAs_Plot)==FALSE){
Folder <- SavePath(FolderName= "Heatmap",
FolderPath=FolderPath)
}
#####################################################
## -------------- Load Data --------------- ##
data <- InputData
if(is.null(SettingsFile_Metab)==FALSE){#removes information about metabolites that are not included in the InputData
SettingsFile_Metab <- merge(x=SettingsFile_Metab, y=as.data.frame(t(InputData)), by=0, all.y=TRUE)%>%
tibble::column_to_rownames("Row.names")
SettingsFile_Metab <- SettingsFile_Metab[,-c((ncol(SettingsFile_Metab)-nrow(InputData)+1):ncol(SettingsFile_Metab))]
}
if(is.null(SettingsFile_Sample)==FALSE){#removes information about samples that are not included in the InputData
SettingsFile_Sample <- merge(x=SettingsFile_Sample, y=InputData, by=0, all.y=TRUE)%>%
tibble::column_to_rownames("Row.names")
SettingsFile_Sample <- SettingsFile_Sample[,-c((ncol(SettingsFile_Sample)-ncol(InputData)+1):ncol(SettingsFile_Sample))]
}
## -------------- Plot --------------- ##
if("individual_Metab" %in% names(SettingsInfo)==TRUE & "individual_Sample" %in% names(SettingsInfo)==FALSE){
#Ensure that groups that are assigned NAs do not cause problems:
SettingsFile_Metab[[SettingsInfo[["individual_Metab"]]]] <-ifelse(is.na(SettingsFile_Metab[[SettingsInfo[["individual_Metab"]]]]), "NA", SettingsFile_Metab[[SettingsInfo[["individual_Metab"]]]])
unique_paths <- unique(SettingsFile_Metab[[SettingsInfo[["individual_Metab"]]]])
for (i in unique_paths){# Check pathways with 1 metabolite
selected_path <- SettingsFile_Metab %>% filter(get(SettingsInfo[["individual_Metab"]]) == i)
selected_path_metabs <- colnames(data) [colnames(data) %in% row.names(selected_path)]
if(length(selected_path_metabs)==1 ){
message <- paste0("The metadata group ", i, " includes only 1 metabolite. Heatmap cannot be made for 1 metabolite, thus it will be ignored.")
logger::log_trace(paste("Warning ", message, sep=""))
warning(message)
unique_paths <- unique_paths[!unique_paths %in% i] # Remove the pathway
}
}
IndividualPlots <-unique_paths
PlotList <- list()#Empty list to store all the plots
PlotList_adaptedGrid <- list()#Empty list to store all the plots
for (i in IndividualPlots){
selected_path <- SettingsFile_Metab %>% filter(get(SettingsInfo[["individual_Metab"]]) == i)
selected_path_metabs <- colnames(data) [colnames(data) %in% row.names(selected_path)]
data_path <- data %>% dplyr::select(all_of(selected_path_metabs))
# Column annotation
col_annot_vars <- SettingsInfo[grepl("color_Sample", names(SettingsInfo))]
col_annot<- NULL
if(length(col_annot_vars)>0){
for (x in 1:length(col_annot_vars)){
annot_sel <- col_annot_vars[[x]]
col_annot[x] <- SettingsFile_Sample %>% select(annot_sel) %>% as.data.frame()
names(col_annot)[x] <- annot_sel
}
col_annot<- as.data.frame(col_annot)
rownames(col_annot) <- rownames(data_path)
}
# Row annotation
row_annot_vars <- SettingsInfo[grepl("color_Metab", names(SettingsInfo))]
row_annot<- NULL
if(length(row_annot_vars)>0){
for (y in 1:length(row_annot_vars)){
annot_sel <- row_annot_vars[[y]]
row_annot[y] <- SettingsFile_Metab %>% select(all_of(annot_sel))
row_annot <- row_annot %>% as.data.frame()
names(row_annot)[y] <- annot_sel
}
row_annot<- as.data.frame(row_annot)
rownames(row_annot) <- rownames(SettingsFile_Metab)
}
#Check number of features:
Features <- as.data.frame(t(data_path))
if(Enforce_FeatureNames==TRUE){
show_rownames <- TRUE
cellheight_Feature <- 9
}else if(nrow(Features)>100){
show_rownames <- FALSE
cellheight_Feature <- 1
}else{
show_rownames <- TRUE
cellheight_Feature <- 9
}
#Check number of samples
if(Enforce_SampleNames==TRUE){
show_colnames <- TRUE
cellwidth_Sample <- 9
}else if(nrow(data_path)>50){
show_colnames <- FALSE
cellwidth_Sample <- 1
}else{
show_colnames <- TRUE
cellwidth_Sample <- 9
}
# Make the plot
if(nrow(t(data_path))>= 2){
set.seed(1234)
heatmap <- pheatmap::pheatmap(t(data_path),
show_rownames = as.logical(show_rownames),
show_colnames = as.logical(show_colnames),
clustering_method = "complete",
scale = Scale,
clustering_distance_rows = "correlation",
annotation_col = col_annot,
annotation_row = row_annot,
legend = T,
cellwidth = cellwidth_Sample,
cellheight = cellheight_Feature,
fontsize_row= 10,
fontsize_col = 10,
fontsize=9,
main = paste(PlotName, " Metabolites: ", i, sep=" " ),
silent = TRUE)
## Store the plot in the 'plots' list
cleaned_i <- gsub("[[:space:],/\\\\]", "-", i)#removes empty spaces and replaces /,\ with -
PlotList[[cleaned_i]] <- heatmap
#Width and height according to Sample and metabolite number
Plot_Sized <- PlotGrob_Heatmap(InputPlot=heatmap, SettingsInfo=SettingsInfo, SettingsFile_Sample=SettingsFile_Sample, SettingsFile_Metab=SettingsFile_Metab, PlotName= cleaned_i)
PlotHeight <- grid::convertUnit(Plot_Sized$height, 'cm', valueOnly = TRUE)
PlotWidth <- grid::convertUnit(Plot_Sized$width, 'cm', valueOnly = TRUE)
Plot_Sized %<>%
{ggplot2::ggplot() + annotation_custom(.)} %>%
add(theme(panel.background = ggplot2::element_rect(fill = "transparent")))
PlotList_adaptedGrid[[cleaned_i]] <- Plot_Sized
#----- Save
suppressMessages(suppressWarnings(
SaveRes(InputList_DF=NULL,
InputList_Plot= PlotList_adaptedGrid,
SaveAs_Table=NULL,
SaveAs_Plot=SaveAs_Plot,
FolderPath= Folder,
FileName=paste("Heatmap_",PlotName, sep=""),
CoRe=FALSE,
PrintPlot=PrintPlot,
PlotHeight=PlotHeight,
PlotWidth=PlotWidth,
PlotUnit="cm")))
}else{
message <- paste0(i , " includes <= 2 objects and is hence not plotted.")
logger::log_trace(paste("Message ", message, sep=""))
message(message)
}
}
#Return if assigned:
return(invisible(list("Plot"=PlotList,"Plot_Sized" = PlotList_adaptedGrid)))
}else if("individual_Metab" %in% names(SettingsInfo)==FALSE & "individual_Sample" %in% names(SettingsInfo)==TRUE){
#Ensure that groups that are assigned NAs do not cause problems:
SettingsFile_Sample[[SettingsInfo[["individual_Sample"]]]] <-ifelse(is.na(SettingsFile_Sample[[SettingsInfo[["individual_Sample"]]]]), "NA", SettingsFile_Sample[[SettingsInfo[["individual_Sample"]]]])
unique_paths_Sample <- unique(SettingsFile_Sample[[SettingsInfo[["individual_Sample"]]]])
for (i in unique_paths_Sample){# Check pathways with 1 metabolite
selected_path <- SettingsFile_Sample %>% filter(get(SettingsInfo[["individual_Sample"]]) == i)
selected_path_metabs <- colnames(data) [colnames(data) %in% row.names(selected_path)]
if(length(selected_path_metabs)==1 ){
message <- paste0("The metadata group ", i, " includes only 1 metabolite. Heatmap cannot be made for 1 metabolite, thus it will be ignored.")
logger::log_trace(paste("Warning ", message, sep=""))
warning(message)
unique_paths_Sample <- unique_paths_Sample[!unique_paths_Sample %in% i] # Remove the pathway
}
}
IndividualPlots <-unique_paths_Sample
PlotList <- list()#Empty list to store all the plots
PlotList_adaptedGrid <- list()#Empty list to store all the plots
for (i in IndividualPlots){
#Select the data:
selected_path <- SettingsFile_Sample %>% filter(get(SettingsInfo[["individual_Sample"]]) == i)%>%
tibble::rownames_to_column("UniqueID")
selected_path <- as.data.frame(selected_path[,1])%>%
dplyr::rename("UniqueID"=1)
data_path <- merge(selected_path, data%>% tibble::rownames_to_column("UniqueID"), by="UniqueID", all.x=TRUE)
data_path <- data_path%>%
tibble::column_to_rownames("UniqueID")
# Column annotation
selected_SettingsFile_Sample <- merge(selected_path, SettingsFile_Sample%>% tibble::rownames_to_column("UniqueID"), by="UniqueID", all.x=TRUE)
col_annot_vars <- SettingsInfo[grepl("color_Sample", names(SettingsInfo))]
col_annot<- NULL
if(length(col_annot_vars)>0){
for (x in 1:length(col_annot_vars)){
annot_sel <- col_annot_vars[[x]]
col_annot[x] <- selected_SettingsFile_Sample %>% select(annot_sel) %>% as.data.frame()
names(col_annot)[x] <- annot_sel
}
col_annot<- as.data.frame(col_annot)
rownames(col_annot) <- rownames(data_path)
}
# Row annotation
row_annot_vars <- SettingsInfo[grepl("color_Metab", names(SettingsInfo))]
row_annot<- NULL
if(length(row_annot_vars)>0){
for (y in 1:length(row_annot_vars)){
annot_sel <- row_annot_vars[[y]]
row_annot[y] <- SettingsFile_Metab %>% select(all_of(annot_sel))
row_annot <- row_annot %>% as.data.frame()
names(row_annot)[y] <- annot_sel
}
row_annot<- as.data.frame(row_annot)
rownames(row_annot) <- rownames(SettingsFile_Metab)
}
#Check number of features:
Features <- as.data.frame(t(data_path))
if(Enforce_FeatureNames==TRUE){
show_rownames <- TRUE
cellheight_Feature <- 9
}else if(nrow(Features)>100){
show_rownames <- FALSE
cellheight_Feature <- 1
}else{
show_rownames <- TRUE
cellheight_Feature <- 9
}
#Check number of samples
if(Enforce_SampleNames==TRUE){
show_colnames <- TRUE
cellwidth_Sample <- 9
}else if(nrow(data_path)>50){
show_colnames <- FALSE
cellwidth_Sample <- 1
}else{
show_colnames <- TRUE
cellwidth_Sample <- 9
}
# Make the plot
if(nrow(t(data_path))>= 2){
set.seed(1234)
heatmap <- pheatmap::pheatmap(t(data_path),
show_rownames = as.logical(show_rownames),
show_colnames = as.logical(show_colnames),
clustering_method = "complete",
scale = Scale,
clustering_distance_rows = "correlation",
annotation_col = col_annot,
annotation_row = row_annot,
legend = T,
cellwidth = cellwidth_Sample,
cellheight = cellheight_Feature,
fontsize_row= 10,
fontsize_col = 10,
fontsize=9,
main = paste(PlotName," Samples: ", i, sep=" " ),
silent = TRUE)
#----- Save
cleaned_i <- gsub("[[:space:],/\\\\]", "-", i)#removes empty spaces and replaces /,\ with -
PlotList[[cleaned_i]] <- heatmap
#Width and height according to Sample and metabolite number
Plot_Sized <- PlotGrob_Heatmap(InputPlot=heatmap, SettingsInfo=SettingsInfo, SettingsFile_Sample=SettingsFile_Sample, SettingsFile_Metab=SettingsFile_Metab, PlotName= cleaned_i)
PlotHeight <- grid::convertUnit(Plot_Sized$height, 'cm', valueOnly = TRUE)
PlotWidth <- grid::convertUnit(Plot_Sized$width, 'cm', valueOnly = TRUE)
Plot_Sized %<>%
{ggplot2::ggplot() + annotation_custom(.)} %>%
add(theme(panel.background = ggplot2::element_rect(fill = "transparent")))
PlotList_adaptedGrid[[cleaned_i]] <- Plot_Sized
#----- Save
suppressMessages(suppressWarnings(
SaveRes(InputList_DF=NULL,
InputList_Plot= PlotList_adaptedGrid,
SaveAs_Table=NULL,
SaveAs_Plot=SaveAs_Plot,
FolderPath= Folder,
FileName= paste("Heatmap_",PlotName, sep=""),
CoRe=FALSE,
PrintPlot=PrintPlot,
PlotHeight=PlotHeight,
PlotWidth=PlotWidth,
PlotUnit="cm")))
}else{
message <- paste0(i , " includes <= 2 objects and is hence not plotted.")
logger::log_trace(paste("Message ", message, sep=""))
message(message)
}
}
#Return if assigned:
return(invisible(list("Plot"=PlotList,"Plot_Sized" = PlotList_adaptedGrid)))
}else if("individual_Metab" %in% names(SettingsInfo)==TRUE & "individual_Sample" %in% names(SettingsInfo)==TRUE){
#Ensure that groups that are assigned NAs do not cause problems:
SettingsFile_Metab[[SettingsInfo[["individual_Metab"]]]] <-ifelse(is.na(SettingsFile_Metab[[SettingsInfo[["individual_Metab"]]]]), "NA", SettingsFile_Metab[[SettingsInfo[["individual_Metab"]]]])
unique_paths <- unique(SettingsFile_Metab[[SettingsInfo[["individual_Metab"]]]])
for (i in unique_paths){# Check pathways with 1 metabolite
selected_path <- SettingsFile_Metab %>% filter(get(SettingsInfo[["individual_Metab"]]) == i)
selected_path_metabs <- colnames(data) [colnames(data) %in% row.names(selected_path)]
if(length(selected_path_metabs)==1 ){
message <- paste0("The metadata group ", i, " includes only 1 metabolite. Heatmap cannot be made for 1 metabolite, thus it will be ignored.")
logger::log_trace(paste("Warning ", message, sep=""))
warning(message)
unique_paths <- unique_paths[!unique_paths %in% i] # Remove the pathway
}
}
#Ensure that groups that are assigned NAs do not cause problems:
SettingsFile_Sample[[SettingsInfo[["individual_Sample"]]]] <-ifelse(is.na(SettingsFile_Sample[[SettingsInfo[["individual_Sample"]]]]), "NA", SettingsFile_Sample[[SettingsInfo[["individual_Sample"]]]])
unique_paths_Sample <- unique(SettingsFile_Sample[[SettingsInfo[["individual_Sample"]]]])
for (i in unique_paths_Sample){# Check pathways with 1 metabolite
selected_path <- SettingsFile_Sample %>% filter(get(SettingsInfo[["individual_Sample"]]) == i)
selected_path_metabs <- colnames(data) [colnames(data) %in% row.names(selected_path)]
if(length(selected_path_metabs)==1 ){
message <- paste0("The metadata group ", i, " includes only 1 metabolite. Heatmap cannot be made for 1 metabolite, thus it will be ignored.")
logger::log_trace(paste("Warning ", message, sep=""))
warning(message)
unique_paths_Sample <- unique_paths_Sample[!unique_paths_Sample %in% i] # Remove the pathway
}
}
IndividualPlots_Metab <-unique_paths
IndividualPlots_Sample <-unique_paths_Sample
PlotList <- list()#Empty list to store all the plots
PlotList_adaptedGrid <- list()#Empty list to store all the plots
for (i in IndividualPlots_Metab){
selected_path <- SettingsFile_Metab %>% filter(get(SettingsInfo[["individual_Metab"]]) == i)
selected_path_metabs <- colnames(data) [colnames(data) %in% row.names(selected_path)]
data_path_metab <- data %>% dplyr::select(all_of(selected_path_metabs))
# Row annotation
row_annot_vars <- SettingsInfo[grepl("color_Metab", names(SettingsInfo))]
row_annot<- NULL
if(length(row_annot_vars)>0){
for (y in 1:length(row_annot_vars)){
annot_sel <- row_annot_vars[[y]]
row_annot[y] <- SettingsFile_Metab %>% select(all_of(annot_sel))
row_annot <- row_annot %>% as.data.frame()
names(row_annot)[y] <- annot_sel
}
row_annot<- as.data.frame(row_annot)
rownames(row_annot) <- rownames(SettingsFile_Metab)
}
#Col annotation:
for (s in IndividualPlots_Sample){
#Select the data:
selected_path <- SettingsFile_Sample %>% filter(get(SettingsInfo[["individual_Sample"]]) == s)%>%
tibble::rownames_to_column("UniqueID")
selected_path <- as.data.frame(selected_path[,1])%>%
dplyr::rename("UniqueID"=1)
data_path <- merge(selected_path, data_path_metab%>% tibble::rownames_to_column("UniqueID"), by="UniqueID", all.x=TRUE)
data_path <- data_path%>%
tibble::column_to_rownames("UniqueID")
# Column annotation
selected_SettingsFile_Sample <- merge(selected_path, SettingsFile_Sample%>% tibble::rownames_to_column("UniqueID"), by="UniqueID", all.x=TRUE)
col_annot_vars <- SettingsInfo[grepl("color_Sample", names(SettingsInfo))]
col_annot<- NULL
if(length(col_annot_vars)>0){
for (x in 1:length(col_annot_vars)){
annot_sel <- col_annot_vars[[x]]
col_annot[x] <- selected_SettingsFile_Sample %>% select(annot_sel) %>% as.data.frame()
names(col_annot)[x] <- annot_sel
}
col_annot<- as.data.frame(col_annot)
rownames(col_annot) <- rownames(data_path)
}
#Check number of features:
Features <- as.data.frame(t(data_path))
if(Enforce_FeatureNames==TRUE){
show_rownames <- TRUE
cellheight_Feature <- 9
}else if(nrow(Features)>100){
show_rownames <- FALSE
cellheight_Feature <- 1
}else{
show_rownames <- TRUE
cellheight_Feature <- 9
}
#Check number of samples
if(Enforce_SampleNames==TRUE){
show_colnames <- TRUE
cellwidth_Sample <- 9
}else if(nrow(data_path)>50){
show_colnames <- FALSE
cellwidth_Sample <- 1
}else{
show_colnames <- TRUE
cellwidth_Sample <- 9
}
# Make the plot
if(nrow(t(data_path))>= 2){
set.seed(1234)
heatmap <- pheatmap::pheatmap(t(data_path),
show_rownames = as.logical(show_rownames),
show_colnames = as.logical(show_colnames),
clustering_method = "complete",
scale = Scale,
clustering_distance_rows = "correlation",
annotation_col = col_annot,
annotation_row = row_annot,
legend = T,
cellwidth = cellwidth_Sample,
cellheight = cellheight_Feature,
fontsize_row= 10,
fontsize_col = 10,
fontsize=9,
main = paste(PlotName," Metabolites: ", i, " Sample:", s, sep="" ),
silent = TRUE)
## Store the plot in the 'plots' list
cleaned_i <- gsub("[[:space:],/\\\\]", "-", i)#removes empty spaces and replaces /,\ with -
cleaned_s <- gsub("[[:space:],/\\\\]", "-", s)#removes empty spaces and replaces /,\ with -
PlotList[[paste(cleaned_i,cleaned_s, sep="_")]] <- heatmap
#-------- Plot width and heights
#Width and height according to Sample and metabolite number
PlotName <- paste(cleaned_i,cleaned_s, sep="_")
Plot_Sized <- PlotGrob_Heatmap(InputPlot=heatmap, SettingsInfo=SettingsInfo, SettingsFile_Sample=SettingsFile_Sample, SettingsFile_Metab=SettingsFile_Metab, PlotName= PlotName)
PlotHeight <- grid::convertUnit(Plot_Sized$height, 'cm', valueOnly = TRUE)
PlotWidth <- grid::convertUnit(Plot_Sized$width, 'cm', valueOnly = TRUE)
Plot_Sized %<>%
{ggplot2::ggplot() + annotation_custom(.)} %>%
add(theme(panel.background = ggplot2::element_rect(fill = "transparent")))
PlotList_adaptedGrid[[paste(cleaned_i,cleaned_s, sep="_")]] <- Plot_Sized
#----- Save
suppressMessages(suppressWarnings(
SaveRes(InputList_DF=NULL,
InputList_Plot= PlotList_adaptedGrid,
SaveAs_Table=NULL,
SaveAs_Plot=SaveAs_Plot,
FolderPath= Folder,
FileName=paste("Heatmap_",PlotName, sep=""),
CoRe=FALSE,
PrintPlot=PrintPlot,
PlotHeight=PlotHeight,
PlotWidth= PlotWidth,
PlotUnit="cm")))
}
else{
message(i , " includes <= 2 objects and is hence not plotted.")
}
}
}
return(invisible(list("Plot"=PlotList,"Plot_Sized" = PlotList_adaptedGrid)))
} else if("individual_Metab" %in% names(SettingsInfo)==FALSE & "individual_Sample" %in% names(SettingsInfo)==FALSE){
PlotList <- list()#Empty list to store all the plots
PlotList_adaptedGrid <- list()#Empty list to store all the plots
# Column annotation
col_annot_vars <- SettingsInfo[grepl("color_Sample", names(SettingsInfo))]
col_annot<- NULL
if(length(col_annot_vars)>0){
for (i in 1:length(col_annot_vars)){
annot_sel <- col_annot_vars[[i]]
col_annot[i] <- SettingsFile_Sample %>% select(annot_sel) %>% as.data.frame()
names(col_annot)[i] <- annot_sel
}
col_annot<- as.data.frame(col_annot)
rownames(col_annot) <- rownames(data)
}
# Row annotation
row_annot_vars <- SettingsInfo[grepl("color_Metab", names(SettingsInfo))]
row_annot<- NULL
if(length(row_annot_vars)>0){
for (i in 1:length(row_annot_vars)){
annot_sel <- row_annot_vars[[i]]
row_annot[i] <- SettingsFile_Metab %>% select(all_of(annot_sel))
row_annot <- row_annot %>% as.data.frame()
names(row_annot)[i] <- annot_sel
}
row_annot<- as.data.frame(row_annot)
rownames(row_annot) <- rownames(SettingsFile_Metab)
}
#Check number of features:
Features <- as.data.frame(t(data))
if(Enforce_FeatureNames==TRUE){
show_rownames <- TRUE
cellheight_Feature <- 9
}else if(nrow(Features)>100){
show_rownames <- FALSE
cellheight_Feature <- 1
}else{
show_rownames <- TRUE
cellheight_Feature <- 9
}
#Check number of samples
if(Enforce_SampleNames==TRUE){
show_colnames <- TRUE
cellwidth_Sample <- 9
}else if(nrow(data)>50){
show_colnames <- FALSE
cellwidth_Sample <- 1
}else{
show_colnames <- TRUE
cellwidth_Sample <- 9
}
#Make the plot:
if(nrow(t(data))>= 2){
set.seed(1234)
heatmap <- pheatmap::pheatmap(t(data),
show_rownames = as.logical(show_rownames),
show_colnames = as.logical(show_colnames),
clustering_method = "complete",
scale = Scale,
clustering_distance_rows = "correlation",
annotation_col = col_annot,
annotation_row = row_annot,
legend = T,
cellwidth = cellwidth_Sample,
cellheight = cellheight_Feature,
fontsize_row= 10,
fontsize_col = 10,
fontsize=9,
main = PlotName,
silent = TRUE)
## Store the plot in the 'plots' list
PlotList[[PlotName]] <- heatmap
#-------- Plot width and heights
#Width and height according to Sample and metabolite number
Plot_Sized <- PlotGrob_Heatmap(InputPlot=heatmap, SettingsInfo=SettingsInfo, SettingsFile_Sample=SettingsFile_Sample, SettingsFile_Metab=SettingsFile_Metab, PlotName= PlotName)
PlotHeight <- grid::convertUnit(Plot_Sized$height, 'cm', valueOnly = TRUE)
PlotWidth <- grid::convertUnit(Plot_Sized$width, 'cm', valueOnly = TRUE)
Plot_Sized %<>%
{ggplot2::ggplot() + annotation_custom(.)} %>%
add(theme(panel.background = ggplot2::element_rect(fill = "transparent")))
PlotList_adaptedGrid[[paste("Heatmap_",PlotName, sep="")]] <- Plot_Sized
#----- Save
suppressMessages(suppressWarnings(
SaveRes(InputList_DF=NULL,
InputList_Plot= PlotList_adaptedGrid,
SaveAs_Table=NULL,
SaveAs_Plot=SaveAs_Plot,
FolderPath= Folder,
FileName= paste("Heatmap_",PlotName, sep=""),
CoRe=FALSE,
PrintPlot=PrintPlot,
PlotHeight=PlotHeight,
PlotWidth=PlotWidth,
PlotUnit="cm")))
}else{
message <- paste0(PlotName , " includes <= 2 objects and is hence not plotted.")
logger::log_trace(paste("Message ", message, sep=""))
message(message)
}
}
return(invisible(list("Plot"=PlotList,"Plot_Sized" = PlotList_adaptedGrid)))
}