-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathutils_v0.R
More file actions
3137 lines (2393 loc) · 131 KB
/
utils_v0.R
File metadata and controls
3137 lines (2393 loc) · 131 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
# Advanced spatial 2 - modified functions.R changed to: Phenalyzer_utils.R on 20250328 since PCF is incomaptible with the old code
#--------------------------------------
# initialize stage0 varibables:
#--------------------------------------
initialize_stage_0_variables <- function(cell.dat,
scatter.plots,
transform.rawdata,
qupath.separator,
cellular.segment.compartment,
cellular.segment.readout,
asinh.cofactor) {
# Store the image and core names away for the upcoming plotting machines
all_images <- unique(cell.dat$Image)
amount.of.TMAs <- length(all_images)
all_cores <- unique(cell.dat$TMA.ID_core)
amount.of.cores <- length(all_cores)
# In the global settings, we work only with the marker names for convenience.
# We push the proper column names into the markercomparision list:
# Now there is a chance you dont want to transform, in that case these columns might not even exist:
if (transform.rawdata == TRUE) {
markercomparision <- lapply(scatter.plots, function(x) {
ifelse(is.na(x), NA,
paste0(
x,
qupath.separator,
cellular.segment.compartment,
qupath.separator,
cellular.segment.readout,
"_t", asinh.cofactor
)
)
})
} else {
# In this case the transform flag does not exist but only the raw columns:
markercomparision <- lapply(scatter.plots, function(x) {
ifelse(is.na(x), NA,
paste0(
x,
qupath.separator,
cellular.segment.compartment,
qupath.separator,
cellular.segment.readout
)
)
})
}
# Return as a list instead of global assignment
return(list(
all_images = all_images,
amount.of.TMAs = amount.of.TMAs,
all_cores = all_cores,
amount.of.cores = amount.of.cores,
markercomparision = markercomparision
))
}
#--------------------------------------
# transformation and normalization:
#--------------------------------------
do.data.normalization <- function (dat,
use.cols,
do.transform = FALSE,
cofactor = 5,
do.minmax = FALSE,
do.zscore = FALSE,
new.min = 0,
new.max = 1,
append.name = "_rescaled")
{ require("data.table")
# Lets make sure the chose columns are numeric and make sense to process:
value <- dat[, use.cols, with = FALSE]
if (isFALSE(all(sapply(value, is.numeric)))) {
message("It appears that one column in your dataset is non numeric")
print(sapply(value, is.numeric))
stop("Transformation/Normalization engine stopped")
}
# Transform first:
if(do.transform==TRUE){
#this is the light version of do.sinh
message("Asinh transformation started...")
value <- asinh(value/cofactor)
if (length(use.cols) > 1) {
names(value) <- paste0(names(value), "_t",cofactor)
}
if (length(use.cols) == 1) {
names(value) <- paste0(use.cols, "_t",cofactor)
}
dat <- cbind(dat, value)
# now if we did transform, the upcoming functions need to work with these newly generated columns
# Hence, we gonna update the column names we supplied to the function:
use.cols <- paste0(use.cols, "_t",cofactor)
}# end transform
# Normalize data to 0 to 1:
if(do.minmax==TRUE){
message("Min-max normalization started...")
norm.fun <- function(x) {
(x - min(x))/(max(x) - min(x)) * (new.max - new.min) +
new.min
}
value <- dat[, use.cols, with = FALSE]
res <- as.data.table(lapply(value, norm.fun))
names(res) <- paste0(names(res), "_m",new.min,"m",new.max)
dat <- cbind(dat, res)
# We deliberatly do NOT update use.cols now so that z-score also pulls the asinh transformed columns.
# if you want, for any reason, do min-max AND z-score, you need to update use.cols right here.
}# end min-max normalization
# z-score data
if(do.zscore==TRUE){
message("Z-score normalization started...")
value <- apply( dat[, use.cols, with = FALSE], scale, MARGIN = 2)
res <- as.data.table(value)
names(res) <- paste0(names(res), "_z")
dat <- cbind(dat, res)
}# end z-score normalization
return(dat)
} # end do.data.normalization function def
#--------------------------------------
# IMC: spill-over matrix correction
#--------------------------------------
do.spill.over.corr <- function( dat = cell.dat,
spillover.matrix.path = spillover.matrix.path,
donor.col.name = "acq.chnl"
)
{
# Because the code would scale the scaled spilled-in signals over and over again,
# the function will create an object spill.over.ran only after it ran successfully, and will check its existence before starting.
# This object does not exist yet, and it will persist after the first run, blocking a second spill-over correction:
if( !exists("spill.over.ran") ){
# this is experimental and an attempt to get the spillover matrix incorporated, best would be the matrix that comes from the core unit:
#https://bodenmillergroup.github.io/IMCDataAnalysis/spillover-correction.html
message("\n ")
spillover.mat <- read_excel(spillover.matrix.path)
spillover.mat <- as.data.frame(spillover.mat)
spillover.mat[is.na(spillover.mat)] <- 0
# we now get rid of that percent counting if the max is 100. Instead we just divide by 1 here:
spillover.mat[,-1] <- spillover.mat[,-1] / max(spillover.mat[,-1])
# ...and we set the diagonal to 0 as well, we do not want to affect the own channel of course:
spillover.mat[spillover.mat=="1"]<-0
# now we will extract the isotope names:
acquired.channels <- pull(spillover.mat[donor.col.name]) #spillover.mat["acq.chnl"]
spotted.channels <- names(spillover.mat)[-1]
# and match the channel names onto spillover.mat:
spillover.mat[donor.col.name] <- names(dat)[match ( acquired.channels, gsub(".*_","",names(dat)) )]
names(spillover.mat) <- c(donor.col.name, names(dat)[match ( spotted.channels, gsub(".*_","",names(dat)) )])
# finally clean out isotopes that were not part of the panel:
spillover.mat <- spillover.mat[!is.na(names(spillover.mat))]
spillover.mat <- spillover.mat %>% drop_na(acq.chnl)
# and update the channel name vector that are part of the spillover matrix:
acquired.channels <- pull(spillover.mat[donor.col.name]) #spillover.mat["acq.chnl"]
spotted.channels <- names(spillover.mat)[-1]
pb <- progress_bar$new(format = "[:bar] :percent [Calculating total spillover | :eta]",
total = length(acquired.channels) , #*length(spotted.channels)
show_after=0, #allows to call it right way
current = "|", # Current bar character
clear = FALSE) # make it persist
pb$tick(0) # call in the progress bar without any progress, just to show it
# we will now run along all aquired channels, extract the cell segment signals of that channel and
# then create a dataframe with the relative spill-in from that channel based on the spillover.mat
# we then sum up all spilled over signals for each channel for all cells in a data.frame called total.signal.corr
# since we dont know the dimesions of that data.frame, lets create and fill it the first time with values i=1
# afterwards just sum the existing object up:
total.signal.corr <- data.frame()
i<-0
for(a in acquired.channels){
#and get its relative contribution into all other channels out:
temp.spill.contribution <- spillover.mat[ match ( a, spillover.mat$acq.chnl ) , ]
temp.spill.out.channel <- dat[,a, with=F]
# protect from working with a channel that is only party recorded in the dataset and would then yield in NA when calculating the spill-out in another channel:
if( !any(is.na(temp.spill.out.channel)) ){
if(i==0){
total.signal.corr <- data.frame(mapply(`*`, temp.spill.contribution[-1],temp.spill.out.channel,SIMPLIFY=FALSE))
i<-1
pb$tick()
}else{
total.signal.corr <- total.signal.corr + data.frame(mapply(`*`, temp.spill.contribution[-1],temp.spill.out.channel,SIMPLIFY=FALSE))
pb$tick()
}
}else{pb$tick()} # end protect from trying to calculate the spill in in other channels if spill out channel is not recorded on all ROIs
} # end run with a along acquired channels
# now there are some ideas as how to substract values in one df from the same column names in another
#https://stackoverflow.com/questions/18708395/subtract-values-in-one-dataframe-from-another
# but they need a unique column with unique entries by row, sth we do not have here: dat contains much more cols!
# due to missing ideas, lets do it the brutal way by substracting the spilled in signal column-by-column:
pb <- progress_bar$new(format = "[:bar] :percent [Correcting total spillover | :eta]",
total = length(spotted.channels) , #*length(spotted.channels)
show_after=0, #allows to call it right way
current = "|", # Current bar character
clear = FALSE) # make it persist
pb$tick(0) # call in the progress bar without any progress, just to show it
for(s in spotted.channels){
dat[, s[1] ] <- dat[,s, with=F] - total.signal.corr[,s]
pb$tick()
}
return(dat)
}else{
# if spill.over routine ran, the object spill.over.ran exists and we skip it:
message(paste0("Spill-over correction ran already on ",data, " and calculation blocked!") )
}
} # end function def spill over correction
#--------------------------------------
# Heatmap
#--------------------------------------
# the old heatmap wrapper is gonna be depreciated soon. we use complex heatmap for this. Here are the functions we need:
fh = function(x) fastcluster::hclust(dist(x))
# use the faster function for dendrogram sorting:
sort_hclust <- function(...) as.hclust(dendsort(as.dendrogram(...)))
#heatmap wrapper saved the png by default, but somehow this doesnt work today (yday worked but I dunno what function was loaded.)
# so we orverride the function here since the error comes back unused argument (file.name = paste0("somepath")):
# the rest is updated to the function found in v1.0.0; dendrograms.sort routine, which, funnily is turned off by default anyway..
make.pheatmap <- function (dat,
sample.col,
plot.cols,
annot.cols = NULL,
feature.annots = NULL,
annotation_colors = NULL,
plot.title = paste0(sample.col, " heatmap"),
# path = NULL, # this would give you the option to store it somewhere else. Its all commented out since we control that via outputdirs
file.name = NA, # if file.name is not provided, print rather than save
transpose = FALSE,
normalise = TRUE,
is.fold = FALSE,
fold.range = NULL,
dendrograms = "both",
dendrograms.sort = FALSE, # if TRUE, will SORT dendrograms
cutree_rows = 1,
cutree_cols = 1,
row.sep = c(),
col.sep = c(),
cell.size = NA, # was 15
standard.colours = "BuPu",
fold.colours = "Spectre")
{
if (!is.element("pheatmap", installed.packages()[, 1]))
stop("pheatmap is required but not installed")
if (!is.element("RColorBrewer", installed.packages()[, 1]))
stop("RColorBrewer is required but not installed")
if (!is.element("scales", installed.packages()[, 1]))
stop("scales is required but not installed")
require(pheatmap)
require(RColorBrewer)
require(scales)
if (standard.colours == "BuPu") {
colour.palette <- (colorRampPalette(RColorBrewer::brewer.pal(9,
"BuPu"))(31))
}
if (standard.colours == "RdYlBu") {
colour.palette <- (colorRampPalette(RColorBrewer::brewer.pal(9,
"RdYlBu"))(31))
colour.palette <- rev(colour.palette)
}
if (standard.colours == "rev(RdBu)") {
colour.palette <- (colorRampPalette(RColorBrewer::brewer.pal(9,
"RdBu"))(31))
colour.palette <- rev(colour.palette)
}
if (standard.colours == "Blues") {
colour.palette <- (colorRampPalette(RColorBrewer::brewer.pal(9,
"Blues"))(31))
}
if (standard.colours == "Reds") {
colour.palette <- (colorRampPalette(RColorBrewer::brewer.pal(9,
"Reds"))(31))
}
if (standard.colours == "Greys") {
colour.palette <- (colorRampPalette(RColorBrewer::brewer.pal(9,
"Greys"))(31))
}
if (standard.colours == "YlGnBu") {
colour.palette <- (colorRampPalette(RColorBrewer::brewer.pal(9,
"YlGnBu"))(31))
}
if (standard.colours == "viridis") {
colour.palette <- colorRampPalette(c((scales::viridis_pal(option = "viridis"))(50)))
colour.palette <- colour.palette(31)
}
if (standard.colours == "spectral") {
spectral.list <- colorRampPalette(RColorBrewer::brewer.pal(11,
"Spectral"))(50)
spectral.list <- rev(spectral.list)
colour.palette <- colorRampPalette(c(spectral.list))
colour.palette <- colour.palette(31)
}
if (standard.colours == "magma") {
colour.palette <- colorRampPalette(c((scales::viridis_pal(option = "magma"))(50)))
colour.palette <- colour.palette(31)
}
if (standard.colours == "inferno") {
colour.palette <- colorRampPalette(c((scales::viridis_pal(option = "inferno"))(50)))
colour.palette <- colour.palette(31)
}
if (fold.colours == "Spectre") {
fold.palette <- colorRampPalette(rev(c("#ffeda0", "#fed976",
"#feb24c", "#fd8d3c", "#fc4e2a", "#e31a1c", "#bd0026",
"#800026", "black", "#023858", "#045a8d", "#0570b0",
"#3690c0", "#74a9cf", "#a6bddb", "#d0d1e6", "#ece7f2")))
fold.palette <- fold.palette(31)
}
if (fold.colours == "BuPu") {
fold.palette <- (colorRampPalette(RColorBrewer::brewer.pal(9,
"BuPu"))(31))
}
if (fold.colours == "RdYlBu") {
fold.palette <- (colorRampPalette(RColorBrewer::brewer.pal(9,
"RdYlBu"))(31))
fold.palette <- rev(fold.palette)
}
if (fold.colours == "rev(RdBu)") {
fold.palette <- (colorRampPalette(RColorBrewer::brewer.pal(9,
"RdBu"))(31))
fold.palette <- rev(fold.palette)
}
if (fold.colours == "Blues") {
fold.palette <- (colorRampPalette(RColorBrewer::brewer.pal(9,
"Blues"))(31))
}
if (fold.colours == "Reds") {
fold.palette <- (colorRampPalette(RColorBrewer::brewer.pal(9,
"Reds"))(31))
}
if (fold.colours == "Greys") {
fold.palette <- (colorRampPalette(RColorBrewer::brewer.pal(9,
"Greys"))(31))
}
if (fold.colours == "YlGnBu") {
fold.palette <- (colorRampPalette(RColorBrewer::brewer.pal(9,
"YlGnBu"))(31))
}
if (fold.colours == "viridis") {
fold.palette <- colorRampPalette(c((scales::viridis_pal(option = "viridis"))(50)))
fold.palette <- fold.palette(31)
}
if (fold.colours == "spectral") {
spectral.list <- colorRampPalette(RColorBrewer::brewer.pal(11,
"Spectral"))(50)
spectral.list <- rev(spectral.list)
fold.palette <- colorRampPalette(c(spectral.list))
fold.palette <- fold.palette(31)
}
if (fold.colours == "magma") {
fold.palette <- colorRampPalette(c((scales::viridis_pal(option = "magma"))(50)))
fold.palette <- fold.palette(31)
}
if (fold.colours == "inferno") {
fold.palette <- colorRampPalette(c((scales::viridis_pal(option = "inferno"))(50)))
fold.palette <- fold.palette(31)
}
dat <- as.data.frame(dat)
heatmap.data <- dat
rownames(heatmap.data) <- t(dat[sample.col])
heatmap.data
if (is.null(annot.cols) == FALSE) {
annot <- heatmap.data[annot.cols]
heatmap.data <- heatmap.data[plot.cols]
heatmap.data
}
### Transpose (ONLY IF REQUIRED) -- the longest set (clusters or parameters) on x-axis --
# by default MARKERS are columns, CLUSTERS are rows -- transpose to flip these defaults
if (is.null(annot.cols) == TRUE) {
annot <- NULL
heatmap.data <- heatmap.data[plot.cols]
heatmap.data
}
if (transpose == TRUE) {
heatmap.data.t <- as.data.frame(t(heatmap.data))
heatmap.data <- heatmap.data.t
}
### NORMALISE BY COLUMN (i.e. each column/parameter has a max of 1 and a minimum of 0) # This is optional, but allows for better comparison between markers
if (normalise == TRUE) {
if (is.fold == FALSE) {
row.nam <- row.names(heatmap.data)
col.nam <- names(heatmap.data)
norm.fun <- function(x) {
(x - min(x, na.rm = TRUE))/(max(x, na.rm = TRUE) -
min(x, na.rm = TRUE))
}
heatmap.data.norm <- as.data.frame(lapply(heatmap.data,
norm.fun))
names(heatmap.data.norm) <- col.nam
max(heatmap.data.norm)
heatmap.data.norm <- as.matrix(heatmap.data.norm)
heatmap.data <- heatmap.data.norm
rownames(heatmap.data) <- row.nam
}
}#end normalize=T
heatmap.data <- as.matrix(heatmap.data)
### Set up clustering
if (dendrograms == "none") {
row.clustering <- FALSE
col.clustering <- FALSE
}
if (dendrograms != "none") {
# set the custom distance and clustering functions, per your example
hclustfunc <- function(x) hclust(x, method = "complete")
distfunc <- function(x) dist(x, method = "euclidean")
# perform clustering on rows and columns
if (dendrograms == "both") {
row.clustering <- TRUE
col.clustering <- TRUE
#this is the new block as by 0.5.4->1.0.0
if(isTRUE(dendrograms.sort)){
row.clustering <- hclustfunc(distfunc(heatmap.data))
col.clustering <- hclustfunc(distfunc(t(heatmap.data)))
require(dendsort)
sort_hclust <- function(...) as.hclust(dendsort(as.dendrogram(...)))
row.clustering <- sort_hclust(row.clustering)
col.clustering <- sort_hclust(col.clustering)
}
#end new block
}
if (dendrograms == "column") {
row.clustering <- FALSE
col.clustering <- TRUE
#this is the new block as by 0.5.4->1.0.0
if(isTRUE(dendrograms.sort)){
col.clustering <- hclustfunc(distfunc(t(heatmap.data)))
require(dendsort)
sort_hclust <- function(...) as.hclust(dendsort(as.dendrogram(...)))
col.clustering <- sort_hclust(col.clustering)
}
#end new block
}
if (dendrograms == "row") {
row.clustering <- TRUE
col.clustering <- FALSE
#this is the new block as by 0.5.4->1.0.0
if(isTRUE(dendrograms.sort)){
row.clustering <- hclustfunc(distfunc(t(heatmap.data)))
require(dendsort)
sort_hclust <- function(...) as.hclust(dendsort(as.dendrogram(...)))
row.clustering <- sort_hclust(row.clustering)
}
#end new block
}
}
if (is.fold == TRUE) {
map.colour <- fold.palette
sym.key <- FALSE
sym.breaks <- TRUE
if (is.null(fold.range)) {
fld.max <- max(heatmap.data, na.rm = TRUE)
fld.min <- min(heatmap.data, na.rm = TRUE)
if (fld.max == -fld.min) {
fold.max.range <- fld.max
fold.min.range <- fld.min
}
if (fld.max > -fld.min) {
fold.max.range <- fld.max
fold.min.range <- -fld.max
}
if (fld.max < -fld.min) {
fold.max.range <- -fld.min
fold.min.range <- fld.min
}
}
if (!is.null(fold.range)) {
fold.max.range <- fold.range[1]
fold.min.range <- fold.range[2]
}
my.breaks <- seq(fold.min.range, fold.max.range, length.out = 32)
}
if (is.fold == FALSE) {
map.colour <- colour.palette
sym.key <- FALSE
sym.breaks <- FALSE
heatmap.data
my.max <- function(x) ifelse(!all(is.na(x)), max(x,
na.rm = T), NA)
my.min <- function(x) ifelse(!all(is.na(x)), min(x,
na.rm = T), NA)
my.breaks <- seq(my.min(heatmap.data), my.max(heatmap.data),
length.out = 32)
}
scale.set <- "none"
title.text <- plot.title
# this here is a chunk of code deleted in v1.0, but I liked it and so I bring it back:
# for this to work, you need to supply path and you need to uncomment path= in the function input
# Specify directory heatmap will be saved
# if(is.null(path)){ flnm <- file.name }
# if(!is.null(path)){ flnm <- paste0(path, '/', file.name) }
# this is a bit stupid, but I want it pushed into storage and printed. so we need to pipe it to pheatmap twice:
pheatmap::pheatmap(mat = as.matrix(heatmap.data), main = title.text,
cellwidth = cell.size, cellheight = cell.size, cluster_rows = row.clustering,
cluster_cols = col.clustering, breaks = my.breaks, cutree_rows = cutree_rows,
cutree_cols = cutree_cols, gaps_row = row.sep, gaps_col = col.sep,
annotation_row = annot, annotation_col = feature.annots,
annotation_colors = annotation_colors, color = map.colour ,
filename = file.name # I brought this back in to control the filename when calling the funtion
)
} # end function def make.pheatmap
#--------------------------------------
# Colour plot functions
#--------------------------------------
make.colour.plot <- function (dat, x.axis, y.axis,
point.alpha, # I added an alpha channel for the geom_point for col.type=factor coloring plots
col.axis = NULL, col.type = "continuous",
add.label = FALSE, hex = FALSE, hex.bins = 30,
colours = "spectral",
polychromepalette = NULL, # this is the go-to way to color, you need to provide a table with colors via polychrome
col.min.threshold = 0.01, col.max.threshold = 0.995,
align.xy.by = dat,
align.col.by = dat, regression.line = NULL,
titlestring = col.axis, # that used to be title, but I changed the code to allow title and subtitle:
subtitlestring = NULL,
filename = NULL, dot.size = 1, plot.width = 9, plot.height = 7,
nudge_x = 0.5, # <- depreciated, as its calculated dynamically from the X-axis range
nudge_y = 0.5, # <- depreciated...
square = TRUE,
legend.loc = "right",
legend.text.size = 18, # was 18 default
save.to.disk = TRUE, path = getwd(), blank.axis = FALSE,
axis.title.size = 15, #font size of the axis titles. new, was 28
axis.text.size = 13, #font size of the axis numbers. new, was 24
title.size = 16 #font size of the title, new, was 32
)
{
if (!is.element("ggplot2", installed.packages()[, 1]))
stop("ggplot2 is required but not installed")
if (!is.element("scales", installed.packages()[, 1]))
stop("scales is required but not installed")
if (!is.element("colorRamps", installed.packages()[, 1]))
stop("colorRamps is required but not installed")
if (!is.element("ggthemes", installed.packages()[, 1]))
stop("ggthemes is required but not installed")
if (!is.element("RColorBrewer", installed.packages()[, 1]))
stop("RColorBrewer is required but not installed")
require(ggplot2)
require(scales)
require(colorRamps)
require(ggthemes)
require(RColorBrewer)
if (hex == TRUE) {
if (is.null(col.axis)) {
message("Note: hex bins do not currently work for density plots, only for colour plots when col.axis is specified and can be plotted as a continuous numeric variable")
}
if (!is.null(col.axis)) {
if (!is.numeric(dat[[col.axis]])) {
stop("Sorry, hex bins only work when col.type is specified, and can be plotted as a continuous numeric variable")
}
}
}
if (!is.null(col.axis)) {
if (col.type == "continuous") {
if (!is.numeric(dat[[col.axis]])) {
message("Non-numeric values detected in col.axis -- using col.type = 'factor'")
col.type <- "factor"
}
}
if (col.type == "factor") {
if (length(unique(as.factor(dat[[col.axis]]))) > 200) {
message("Over 200 factors detected, using continuous scale instead of a factor scale")
col.type <- "continuous"
}
}
}
if (colours == "jet") {
colour.scheme <- colorRampPalette(c("#00007F", "blue",
"#007FFF", "cyan", "#7FFF7F", "yellow", "#FF7F00",
"red", "#7F0000"))
}
if (colours == "spectral") {
spectral.list <- colorRampPalette(brewer.pal(11, "Spectral"))(50)
spectral.list <- rev(spectral.list)
colour.scheme <- colorRampPalette(c(spectral.list))
}
if (colours == "viridis") {
colour.scheme <- colorRampPalette(c(viridis_pal(option = "viridis")(50)))
}
if (colours == "inferno") {
colour.scheme <- colorRampPalette(c(viridis_pal(option = "inferno")(50)))
}
if (colours == "magma") {
colour.scheme <- colorRampPalette(c(viridis_pal(option = "magma")(50)))
}
if (colours == "BuPu") {
colour.list <- (colorRampPalette(RColorBrewer::brewer.pal(9,
"BuPu"))(31))
colour.scheme <- colorRampPalette(c(colour.list))
}
if (colours == "turbo") {
colour.scheme <- colorRampPalette(c(viridis_pal(option = "turbo")(50)))
}
if (colours == "mako") {
colour.scheme <- colorRampPalette(c(viridis_pal(option = "mako")(50)))
}
if (colours == "rocket") {
colour.scheme <- colorRampPalette(c(viridis_pal(option = "rocket")(50)))
}
if (is.null(align.xy.by)) {
Xmax <- max(dat[[x.axis]])
Xmin <- min(dat[[x.axis]])
}
else {
Xmax <- max(align.xy.by[[x.axis]])
Xmin <- min(align.xy.by[[x.axis]])
}
if (is.null(align.xy.by)) {
Ymax <- max(dat[[y.axis]])
Ymin <- min(dat[[y.axis]])
}
else {
Ymax <- max(align.xy.by[[y.axis]])
Ymin <- min(align.xy.by[[y.axis]])
}
if (!is.null(col.axis)) {
if (col.type == "continuous") {
if (is.null(align.col.by)) {
ColrMin <- quantile(dat[[col.axis]], probs = c(col.min.threshold),
na.rm = TRUE)
ColrMax <- quantile(dat[[col.axis]], probs = c(col.max.threshold),
na.rm = TRUE)
}
else {
ColrMin <- quantile(align.col.by[[col.axis]],
probs = c(col.min.threshold), na.rm = TRUE)
ColrMax <- quantile(align.col.by[[col.axis]],
probs = c(col.max.threshold), na.rm = TRUE)
}
}
if (col.type == "factor") {
if (is.null(align.col.by)) {
colRange <- unique(dat[[col.axis]])
colRange <- colRange[order(colRange)]
colRange <- as.character(colRange)
}
else {
colRange <- unique(align.col.by[[col.axis]])
colRange <- colRange[order(colRange)]
colRange <- as.character(colRange)
}
}
}
if (!is.null(col.axis)) {
if (col.type == "continuous") {
p <- ggplot(data = dat, aes(x = .data[[x.axis]],
y = .data[[y.axis]], colour = .data[[col.axis]]))
if (hex == TRUE) {
p <- p + stat_summary_hex(aes(z = dat[[col.axis]]),
fun = "mean", bins = hex.bins)
p <- p + scale_fill_gradientn(colours = c(colour.scheme(50)),
limits = c(ColrMin, ColrMax), oob = squish)
}
else {
p <- p + geom_point(size = dot.size)
p <- p + scale_colour_gradientn(colours = colour.scheme(50),
limits = c(ColrMin, ColrMax), oob = squish,
na.value = "grey50")
}
}
else if (col.type == "factor") {
# these are tSNEs and UMAPs. lets not overdraw the points here:
#this specral thing is annoying since you cannot see the clusters and the colors get re-assigned everytime we print another subset.
#so lets predefine a palette and then use it in here:
if (colours == "polychrome") {
p <- ggplot(data = dat, aes(x = .data[[x.axis]],
y = .data[[y.axis]], colour = as.factor(.data[[col.axis]]))) +
geom_point(size = dot.size, alpha = point.alpha)+
scale_colour_manual( values = polychromepalette )+ # push the polychrome palette in
guides(colour = guide_legend(override.aes = list(size=4, alpha=1), #we also gonna override the dot size how its depicted in the legend
byrow=TRUE) ) # and I want the elements listed row-by-row
} else {
p <- ggplot(data = dat, aes(x = .data[[x.axis]],
y = .data[[y.axis]], colour = as.factor(.data[[col.axis]]))) +
geom_point(size = dot.size, alpha = point.alpha) +
lims(colour = colRange)+
guides(colour = guide_legend(override.aes = list(size=4) ) ) #we also gonna override the dot size how its depicted in the legend
}#end default factor plot with col.axis set
}
}
if (is.null(col.axis)) {
p <- ggplot(data = dat, aes(x = .data[[x.axis]], y = .data[[y.axis]])) +
ggpointdensity::geom_pointdensity(size = dot.size)
if (colours == "viridis" || colours == "magma" || colours ==
"inferno") {
p <- p + viridis::scale_colour_viridis(option = colours)
}
else if (colours == "jet") {
p <- p + ggplot2::scale_colour_gradientn(colours = c("#00007F",
"blue", "#007FFF", "cyan", "#7FFF7F", "yellow",
"#FF7F00", "red", "#7F0000"))
}
else if (colours == "spectral") {
p <- p + ggplot2::scale_colour_gradientn(colours = rev(colorRampPalette(RColorBrewer::brewer.pal(11,
"Spectral"))(50)))
}
else if (colours == "BuPu") {
colour.list <- (colorRampPalette(RColorBrewer::brewer.pal(9,
"BuPu"))(31))
p <- p + ggplot2::scale_colour_gradientn(colours = colour.list)
}
}
if (!is.null(regression.line)) {
p <- p + geom_smooth(method = regression.line)
}
if (is.null(title)) {
title <- "Density"
}
p <- p + labs(title= titlestring ,
subtitle=subtitlestring#,
#caption="Created by M.Barone"#,
# y="ROI y",
# x="ROI x"
)
p <- p + scale_x_continuous(breaks = scales::pretty_breaks(n = 8),
name = x.axis, limits = c(Xmin, Xmax))
p <- p + scale_y_continuous(breaks = scales::pretty_breaks(n = 8),
name = y.axis, limits = c(Ymin, Ymax))
if (col.type == "continuous") {
p <- p + theme(panel.background = element_rect(fill = "white",
colour = "black", size = 0.5),
axis.title.x = element_text(color = "Black", size = 28),
axis.title.y = element_text(color = "Black", size = 28), axis.text.x = element_text(color = "Black", size = 24),
axis.text.y = element_text(color = "Black", size = 24),
panel.border = element_rect(colour = "black", fill = NA, size = 2),
plot.title = element_text(color = "Black", face = "bold", size = 32, hjust = 0)
)
}
if (col.type == "factor") {
p <- p + theme(panel.background = element_rect(fill = "white",
colour = "black", size = 0.5),
axis.title.x = element_text(color = "Black", size = axis.title.size),
axis.title.y = element_text(color = "Black", size = axis.title.size),
axis.text.x = element_text(color = "Black", size = axis.text.size),
axis.text.y = element_text(color = "Black", size = axis.text.size),
panel.border = element_rect(colour = "black", fill = NA, size = 2),
plot.title = element_text(color = "Black", size = title.size) # was also ,face = "bold", hjust = 0
#plot.subtitle = element_text(color = "Black", size = subtitle.size)
)
}
if (square == TRUE) {
p <- p + theme(aspect.ratio = 1)
}
if (legend.loc %in% c("top", "bottom")) {
p <- p + theme(legend.direction = "horizontal", legend.position = legend.loc,
legend.text = element_text(size = legend.text.size), legend.title = element_blank())
}
if (legend.loc %in% c("left", "right")) {
p <- p + theme(legend.direction = "vertical", legend.position = legend.loc,
legend.text = element_text(size = legend.text.size), legend.title = element_blank())
}
if (col.type == "factor") {
if (add.label == TRUE) {
if (is.numeric(dat[[col.axis]])) {
centroidX = tapply(dat[[x.axis]], dat[[col.axis]],
median)
centroidY = tapply(dat[[y.axis]], dat[[col.axis]],
median)
centroidCol = tapply(dat[[col.axis]], dat[[col.axis]],
median)
centroidsDf <- data.frame(centroidX, centroidY,
centroidCol)
}
if (!is.numeric(dat[[col.axis]])) {
labels <- sort(unique(dat[[col.axis]]))
centroidsDf <- data.frame(centroidX = tapply(dat[[x.axis]],
dat[[col.axis]], median), centroidY = tapply(dat[[y.axis]],
dat[[col.axis]], median), centroidCol = labels)
}
#https://ggrepel.slowkow.com/reference/geom_text_repel.html
#https://ggrepel.slowkow.com/articles/examples.html
p <- p + geom_label_repel(data = centroidsDf,
hjust = "right", # this only takes effect initially and is lost for labels that are pulled...
force = 30, # repulsion between overlapping text labels. default 1
force_pull = 0.8, # attraction betweenlabel and datapoint. default 1
# nudge_x = 0.1*(Xmax-Xmin),
#nudge_y = 0.05*(Ymax-Ymin),
xlim = c(-Inf, Inf), #c(Xmin, Xmax), # either plots them also outside the graph or restrains the labels to be within the datarange. this assures that no label is cut off
ylim = c(-Inf, Inf), #c(Ymin,Ymax), # either plots them also outside the graph or restrains the labels to be within the datarange. this assures that no label is cut off
box.padding = 0.01, # additional padding around each text label 0.25 default
label.padding = 0.20, #0.25 default
point.padding = 0, # additional padding around each point
min.segment.length = 0, # draw all line segments
segment.curvature = -0.1, #pos: more righthand, 0 straight, neg increase left-hand
segment.ncp = 3, # control points per curve
segment.angle = 20,
max.overlaps = Inf, # default 10
aes(x = centroidX, y = centroidY, label = centroidCol), #, alpha = 0.5
fill = "white",
col = "black", fontface = "bold",size = 5,
verbose = TRUE)
# Put geom_point() of the labels after geom_label_repel, so that its point is on top layer
p <- p + geom_point(data = centroidsDf, aes(x = centroidX,
y = centroidY), col = "black", size = 2 , alpha = 0.3)
p <- p +coord_cartesian(clip = "off") #this ensures that the label is not clipped off
#p <- p + guides(alpha = "none")
}
}
if (blank.axis == TRUE) {
p <- p + theme(axis.line = element_blank(), axis.text.x = element_blank(),
axis.text.y = element_blank(), axis.ticks = element_blank(),
axis.title.x = element_blank(), axis.title.y = element_blank(),
panel.grid.major = element_blank(), panel.background = element_blank(),
panel.border = element_blank(), panel.grid.minor = element_blank(),
plot.background = element_blank(), )
}
if (save.to.disk == TRUE) {
if (!is.null(col.axis)) {
if (col.type == "continuous") {
lb <- "Colour"
}
if (col.type == "factor") {
lb <- "Factor"
}
}
if (is.null(col.axis)) {
lb <- "Density plot"
}
if (is.null(filename)) {
filename <- paste0(lb, " plot - ", title, " - plotted on ",
x.axis, " by ", y.axis, ".png")
}
ggsave(filename = filename, plot = p, path = path, width = plot.width,
height = plot.height, limitsize = FALSE)
}
else {
# watch out, there is a cryptic error message if the Plots tab in RStudio is too small to send the plot to the viewer
# so protect from doing that:
if (min(dev.size("in")) > 2.2 ) { # Minimum width & height of 4 inches
print(p)
} else {
message("Plot window is too small. Resize the RStudio plot window to see the plot.")
}
}
return(p)
} # end function def make.colour.plot
make.colour.plot.adapted <- function (dat, x.axis, y.axis,
col.axis = NULL, col.type = "continuous",
add.label = FALSE, hex = FALSE, hex.bins = 30,
colours = "spectral",
polychromepalette = NULL, # this is the go-to way to color, you need to provide a table with colors via polychrome
NA.color = "#F1F1F1",
min.line.length.tolabel = 0,
col.min.threshold = 0.01, col.max.threshold = 0.995,
point.alpha, # I added an alpha channel for the geom_point for col.type=factor coloring plots
align.xy.by = dat,
align.col.by = dat, regression.line = NULL,
titlestring = col.axis, # that used to be title, but I changed the code to allow title and subtitle:
subtitlestring = NULL,
filename = NULL, dot.size = 1, plot.width = 9, plot.height = 7,
nudge_x = 0.5, # <- depreciated, as its calculated dynamically from the X-axis range
nudge_y = 0.5, # <- depreciated...