-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy path5_plotFunctions.R
2652 lines (2491 loc) · 101 KB
/
5_plotFunctions.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
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
#' PlotFlowSOM
#'
#' Base layer to plot a FlowSOM result
#'
#' Base layer of the FlowSOM plot, where you can choose layout (MST, grid or
#' coordinates of your own choosing), background colors and node size. Can
#' then be extended by e.g. \code{\link{AddStars}}, \code{\link{AddLabels}},
#' \code{\link{AddPies}}, ...
#'
#' @param fsom FlowSOM object, as created by \code{\link{FlowSOM}}
#' @param view Preferred view, options: "MST", "grid" or "matrix"
#' with a matrix/dataframe consisting of coordinates
#' given in coords. Default = "MST"
#' @param nodeSizes A vector containing nodesizes. These will
#' automatically be scaled between 0 and maxNodeSize
#' and transformed with a sqrt. Default = fsom$MST$sizes
#' @param maxNodeSize Determines the maximum nodesize. Default is 1.
#' @param refNodeSize Reference for nodesize against which the nodeSizes
#' will be scaled. Default = max(nodeSizes)
#' @param equalNodeSize If \code{TRUE}, the nodes will be equal to
#' maxNodeSize. If \code{FALSE} (default), the nodes
#' will be scaled to the number of cells in each
#' cluster
#' @param backgroundValues Values to be used for background coloring, either
#' numerical values or something that can be made into
#' a factor (e.g. a clustering)
#' @param backgroundColors Colorpalette to be used for the background coloring.
#' Can be either a function or an array specifying
#' colors.
#' @param backgroundLim Only used when backgroundValues are numerical.
#' Defaults to min and max of the backgroundValues.
#' @param title Title of the plot
#'
#' @return A ggplot object with the base layer of a FlowSOM plot
#'
#' @seealso \code{\link{PlotStars}}, \code{\link{PlotVariable}},
#' \code{\link{PlotMarker}}, \code{\link{PlotLabels}},
#' \code{\link{PlotNumbers}}, \code{\link{PlotPies}},
#' \code{\link{QueryStarPlot}}, \code{\link{PlotSD}}
#'
#' @examples
#' # Locate file on file system
#' fcs_file <- system.file("extdata", "68983.fcs", package = "FlowSOM")
#'
#' # Build FlowSOM model
#' flowSOM.res <- FlowSOM(fcs_file,
#' scale = TRUE,
#' compensate = TRUE,
#' transform = TRUE,
#' toTransform = 8:18,
#' colsToUse = c(9, 12, 14:18),
#' nClus = 10,
#' seed = 1)
#'
#' # Plot with background coloring
#' PlotFlowSOM(flowSOM.res,
#' backgroundValues = flowSOM.res$metaclustering)
#'
#' # Own layout
#' mfis <- GetClusterMFIs(flowSOM.res)[,GetChannels(flowSOM.res, c("CD3", "CD4"))]
#' PlotFlowSOM(flowSOM.res,
#' view = mfis,
#' maxNodeSize = 0.1,
#' backgroundValues = flowSOM.res$metaclustering)
#'
#' # Adapted node sizes
#' PlotFlowSOM(flowSOM.res,
#' nodeSizes = 1:100,
#' view = "grid")
#'
#' @importFrom ggplot2 ggplot coord_fixed theme_void ggtitle
#'
#' @export
PlotFlowSOM <- function(fsom,
view = "MST",
nodeSizes = fsom$map$pctgs,
maxNodeSize = 1,
refNodeSize = max(nodeSizes),
equalNodeSize = FALSE,
backgroundValues = NULL,
backgroundColors = NULL,
backgroundLim = NULL,
title = NULL)
{
#----Initialization----
requireNamespace("ggplot2")
fsom <- UpdateFlowSOM(fsom)
nNodes <- NClusters(fsom)
isEmpty <- fsom$map$pctgs == 0
#----Warnings----
if (length(nodeSizes) != nNodes){
stop(paste0("Length of 'nodeSizes' should be equal to number of clusters ",
"in FlowSOM object (", nNodes, " clusters and ",
length(nodeSizes), " nodesizes)."))
}
if (length(backgroundValues) != nNodes && !is.null(backgroundValues)){
stop(paste0("Length of 'backgroundValues' should be equal to number of ",
"clusters in FlowSOM object (", nNodes, " clusters and ",
length(backgroundValues), " backgroundValues)."))
}
#---- Layout----
layout <- ParseLayout(fsom, view)
if(is.matrix(view) || is.data.frame(view)) view <- "matrix"
#---- Nodesize----
autoNodeSize <- AutoMaxNodeSize(layout = layout,
overlap = ifelse(view %in% c("grid"),
-0.3, 1))
maxNodeSize <- autoNodeSize * maxNodeSize
if (equalNodeSize){
scaledNodeSize <- rep(maxNodeSize, nNodes)
} else {
scaledNodeSize <- ParseNodeSize(nodeSizes, maxNodeSize, refNodeSize)
}
if (any(isEmpty)) {scaledNodeSize[isEmpty] <- min(maxNodeSize, 0.05)}
#----GGplot----
plot_df <- data.frame(x = layout$x,
y = layout$y,
size = scaledNodeSize,
bg_size = scaledNodeSize * 1.5)
p <- ggplot2::ggplot(plot_df)
# Add background
if (!is.null(backgroundValues)){
p <- AddBackground(p,
backgroundValues = backgroundValues,
backgroundColors = backgroundColors,
backgroundLim = backgroundLim)
}
# Add MST
if (view == "MST"){
p <- AddMST(p, fsom)
}
# Add nodes
p <- AddNodes(p = p,
values = as.character(isEmpty),
colorPalette = c("TRUE" = "grey", "FALSE" = "white"),
showLegend = FALSE)
# Fix plotlayout
p <- p + ggplot2::coord_fixed() + ggplot2::theme_void()
if (!is.null(title)){
p <- p + ggplot2::ggtitle(title)
}
return(p)
}
#' FlowSOM default colors
#'
#' @param n Number of colors to generate
#'
#' @return array of n colors
#'
#' @importFrom grDevices colorRampPalette
#' @export
FlowSOM_colors <- function(n){
grDevices::colorRampPalette(c("#00007F",
"blue",
"#007FFF",
"cyan",
"#7FFF7F",
"yellow",
"#FF7F00",
"red",
"#7F0000"))(n)
}
#' PlotStars
#'
#' Plot star charts
#'
#' Plot FlowSOM grid or tree, where each node is represented by
#' a star chart indicating median marker values
#'
#' @param fsom FlowSOM object, as generated by \code{\link{BuildMST}}
#' @param markers Markers to plot (will be parsed by GetChannels)
#' @param colorPalette ColorPalette to use
#' @param list_insteadof_ggarrange If FALSE (default), the plot and the legend
#' are combined by ggarrange. If TRUE, the
#' seperate elements are returned in a list,
#' to allow further customization.
#' @param ... Additional arguments to pass to \code{\link{PlotFlowSOM}}
#'
#' @return Nothing is returned. A plot is drawn in which each node is
#' represented by a star chart indicating the median fluorescence intensities.
#' Resets the layout back to 1 plot at the end.
#
#' @seealso \code{\link{PlotMarker}}, \code{\link{PlotVariable}},
#' \code{\link{PlotFlowSOM}}, \code{\link{PlotLabels}},
#' \code{\link{PlotNumbers}}, \code{\link{PlotPies}},
#' \code{\link{QueryStarPlot}}, \code{\link{PlotSD}}
#'
#' @examples
#' # Read from file, build self-organizing map and minimal spanning tree
#' fileName <- system.file("extdata", "68983.fcs", package = "FlowSOM")
#' flowSOM.res <- FlowSOM(fileName, compensate = TRUE, transform = TRUE,
#' scale = TRUE, colsToUse = c(9, 12, 14:18))
#'
#' # Plot stars indicating the MFI of the cells present in the nodes
#' PlotStars(flowSOM.res)
#'
#' @importFrom ggpubr get_legend ggarrange
#' @importFrom ggforce geom_circle
#'
#' @export
PlotStars <- function(fsom,
markers = fsom$map$colsUsed,
colorPalette = FlowSOM_colors,
list_insteadof_ggarrange = FALSE,
...){
fsom <- UpdateFlowSOM(fsom)
channels <- GetChannels(fsom, markers)
p <- PlotFlowSOM(fsom = fsom,
...)
if(!is.null(names(colorPalette))) {
names(colorPalette) <- GetChannels(fsom, names(colorPalette))
}
p <- AddStars(p = p,
fsom = fsom,
markers = channels,
colorPalette = colorPalette)
if(!is.null(names(colorPalette))) {
names(colorPalette) <- fsom$prettyColnames[GetChannels(fsom,
names(colorPalette))]
}
l1 <- PlotStarLegend(fsom$prettyColnames[channels],
colorPalette)
l2 <- ggpubr::get_legend(p)
if (list_insteadof_ggarrange){
p <- p + ggplot2::theme(legend.position = "none")
l2 <- ggpubr::as_ggplot(l2)
return(list(tree = p,
starLegend = l1,
backgroundLegend = l2))
} else {
p <- ggpubr::ggarrange(p,
ggpubr::ggarrange(l1, l2,
ncol = 1),
NULL,
ncol = 3, widths = c(3, 1, 0.3),
legend = "none")
return(p)
}
}
#' PlotPies
#'
#' Plot comparison with other clustering
#'
#' Plot FlowSOM grid or tree, with pies indicating another clustering
#' or manual gating result
#'
#' @param fsom FlowSOM object, as generated by \code{\link{FlowSOM}}
#' @param cellTypes Array of factors indicating the celltypes
#' @param colorPalette Color palette to use.
#' @param ... Additional arguments to pass to \code{\link{PlotFlowSOM}}
#'
#' @return Ggplot plot
#'
#' @seealso \code{\link{PlotStars}}, \code{\link{PlotVariable}},
#' \code{\link{PlotFlowSOM}}, \code{\link{PlotLabels}},
#' \code{\link{PlotNumbers}}, \code{\link{PlotMarker}},
#' \code{\link{QueryStarPlot}}, \code{\link{PlotSD}}
#'
#' @examples
#' # Identify the files
#' fcs_file <- system.file("extdata", "68983.fcs", package = "FlowSOM")
#' wsp_file <- system.file("extdata", "gating.wsp", package = "FlowSOM")
#'
#' # Specify the cell types of interest for assigning one label per cell
#' cellTypes <- c("B cells",
#' "gd T cells", "CD4 T cells", "CD8 T cells",
#' "NK cells", "NK T cells")
#'
#' # Parse the FlowJo workspace
#' gatingResult <- GetFlowJoLabels(fcs_file, wsp_file,
#' cellTypes = cellTypes)
#'
#' # Check the number of cells assigned to each gate
#' colSums(gatingResult$matrix)
#'
#' # Build a FlowSOM tree
#' flowSOM.res <- FlowSOM(fcs_file,
#' scale = TRUE,
#' compensate = TRUE,
#' transform = TRUE,
#' toTransform = 8:18,
#' colsToUse = c(9, 12, 14:18),
#' nClus = 10,
#' seed = 1)
#'
#' # Plot pies indicating the percentage of cell types present in the nodes
#' PlotPies(flowSOM.res,
#' gatingResult$manual,
#' backgroundValues = flowSOM.res$metaclustering)
#'
#' @importFrom grDevices colorRampPalette
#'
#' @export
PlotPies <- function(fsom,
cellTypes,
colorPalette = grDevices::colorRampPalette(c("white",
"#00007F",
"blue",
"#007FFF",
"cyan",
"#7FFF7F",
"yellow",
"#FF7F00",
"red",
"#7F0000")),
...){
if(length(cellTypes) != nrow(fsom$data)){
stop("There are ", nrow(fsom$data), " cells, while you provided ",
length(cellTypes), " labels. These numbers should match.")
}
p <- PlotFlowSOM(fsom = fsom,
...)
p <- AddPies(p,
fsom = fsom,
colorPalette = colorPalette,
cellLabels = cellTypes)
return(p)
}
#' PlotLabels
#'
#' Plot labels for each cluster
#'
#' Plot FlowSOM grid or tree, with in each node a label.
#' Especially useful to show metacluster numbers
#'
#' @param fsom FlowSOM object, as generated by \code{\link{FlowSOM}}
#' @param labels A vector of labels for every node.
#' @param maxNodeSize Determines the maximum nodesize. Default is 0.
#' @param textSize Size for geom_text. Default (=3.88) is from geom_text.
#' @param textColor Color for geom_text. Default = black.
#' @param ... Additional arguments to pass to \code{\link{PlotFlowSOM}}
#'
#' @return Nothing is returned. A plot is drawn in which each node is
#' represented by a label.
#'
#'
#' @seealso \code{\link{PlotStars}}, \code{\link{PlotVariable}},
#' \code{\link{PlotFlowSOM}}, \code{\link{PlotMarker}},
#' \code{\link{PlotNumbers}}, \code{\link{PlotPies}},
#' \code{\link{QueryStarPlot}}, \code{\link{PlotSD}}
#'
#' @examples
#' # Read from file, build self-organizing map and minimal spanning tree
#' fileName <- system.file("extdata", "68983.fcs", package="FlowSOM")
#' ff <- flowCore::read.FCS(fileName)
#' ff <- flowCore::compensate(ff, flowCore::keyword(ff)[["SPILL"]])
#' ff <- flowCore::transform(ff,
#' flowCore::transformList(colnames(flowCore::keyword(ff)[["SPILL"]]),
#' flowCore::logicleTransform()))
#' flowSOM.res <- FlowSOM(ff,
#' scale = TRUE,
#' colsToUse = c(9, 12, 14:18),
#' nClus = 10,
#' seed = 1)
#'
#' # Plot the node IDs
#' PlotLabels( flowSOM.res,
#' flowSOM.res$metaclustering)
#'
#' @importFrom grDevices colorRampPalette
#'
#' @export
PlotLabels <- function(fsom,
labels,
maxNodeSize = 0,
textSize = 3.88,
textColor = "black",
...){
fsom <- UpdateFlowSOM(fsom)
if(length(labels) != NClusters(fsom)) {
stop(paste0("Length of 'labels' should be equal to number of clusters in ",
"FlowSOM object (", NClusters(fsom), " clusters, ",
length(labels), " labels)."))
}
p <- PlotFlowSOM(fsom = fsom,
maxNodeSize = maxNodeSize,
...)
p <- AddLabels(p,
labels = labels,
textSize = textSize,
textColor = textColor)
return(p)
}
#' PlotNumbers
#'
#' Plot cluster ids for each cluster
#'
#' Plot FlowSOM grid or tree, with in each node the cluster id.
#'
#' @param fsom FlowSOM object
#' @param level Character string, should be either "clusters" or
#' "metaclusters"
#' @param maxNodeSize Determines the maximum nodesize. Default is 0.
#' See \code{\link{PlotFlowSOM}} for more options.
#' @param ... Additional arguments to pass to \code{\link{PlotLabels}}
#' and to \code{\link{PlotFlowSOM}}
#'
#' @return Nothing is returned. A plot is drawn in which each node is
#' labeled by its cluster id.
#'
#' @seealso \code{\link{PlotStars}}, \code{\link{PlotVariable}},
#' \code{\link{PlotFlowSOM}}, \code{\link{PlotLabels}},
#' \code{\link{PlotMarker}}, \code{\link{PlotPies}},
#' \code{\link{QueryStarPlot}}, \code{\link{PlotSD}}
#'
#' @examples
#' # Read from file, build self-organizing map and minimal spanning tree
#' fileName <- system.file("extdata", "68983.fcs", package = "FlowSOM")
#' ff <- flowCore::read.FCS(fileName)
#' ff <- flowCore::compensate(ff, flowCore::keyword(ff)[["SPILL"]])
#' ff <- flowCore::transform(ff, flowCore::estimateLogicle(ff,
#' flowCore::colnames(ff)[8:18]))
#' flowSOM.res <- FlowSOM(ff,
#' scale = TRUE,
#' colsToUse = c(9, 12, 14:18),
#' nClus = 10,
#' seed = 1)
#'
#' # Plot the node IDs
#' PlotNumbers(flowSOM.res)
#' PlotNumbers(flowSOM.res, "metaclusters")
#'
#' PlotNumbers(flowSOM.res,
#' view = "grid")
#'
#' PlotNumbers(flowSOM.res,
#' maxNodeSize = 1,
#' equalNodeSize = TRUE)
#'
#' @export
PlotNumbers <- function(fsom,
level = "clusters",
maxNodeSize = 0,
...){
if (level == "clusters"){
numbers <- seq_len(NClusters(fsom))
} else if (level == "metaclusters") {
numbers <- fsom$metaclustering
} else {
stop("level should be \"clusters\" or \"metaclusters\"")
}
p <- PlotLabels(fsom = fsom,
labels = numbers,
maxNodeSize = maxNodeSize,
...)
return(p)
}
#' PlotMarker
#'
#' Plot comparison with other clustering
#'
#' Plot FlowSOM grid or tree, coloured by node values for a specific marker
#'
#' @param fsom FlowSOM object
#' @param marker A vector of markers/channels to plot.
#' @param refMarkers Is used to determine relative scale of the marker
#' that will be plotted. Default are all markers used in the
#' clustering.
#' @param title A vector with custom titles for the plot. Default is
#' the marker name.
#' @param colorPalette Colorpalette to use. Can be a function or a vector.
#' @param lim Limits for the scale
#' @param ... Additional arguments to pass to \code{\link{PlotFlowSOM}},
#' e.g. view, backgroundValues, equalNodeSize ...
#'
#' @return A ggplot figure is returned in which every cluster is colored
#' according to the MFI value for the specified marker
#'
#' @seealso \code{\link{PlotStars}}, \code{\link{PlotVariable}}
#'
#' @examples
#' # Build FlowSOM model
#' fileName <- system.file("extdata", "68983.fcs", package = "FlowSOM")
#' flowSOM.res <- FlowSOM(fileName,
#' compensate = TRUE, transform = TRUE, scale = FALSE,
#' colsToUse = c(9, 12, 14:18),
#' nClus = 10,
#' seed = 1)
#' # Plot one marker
#' PlotMarker(flowSOM.res,
#' "CD19")
#'
#' PlotMarker(flowSOM.res,
#' "CD19",
#' colorPalette = c("grey", "red"))
#'
#' # Plot all markers
#' PlotMarker(flowSOM.res,
#' c(9, 12, 14:18))
#'
#' # Use specific limits if the ones from the columns used for clustering
#' # are not relevant for your marker of choice
#' PlotMarker(flowSOM.res,
#' "FSC-A",
#' lim = c(55000, 130000))
#'
#' # Example with additional FlowSOM plotting options
#' PlotMarker(flowSOM.res,
#' "CD19",
#' view = "grid",
#' equalNodeSize = TRUE,
#' backgroundValues = 1:100 == 27,
#' backgroundColors = c("white", "red"))
#'
#'
#' @importFrom grDevices colorRampPalette
#' @importFrom ggplot2 ggtitle
#'
#' @export
PlotMarker <- function(fsom,
marker,
refMarkers = fsom$map$colsUsed,
title = GetMarkers(fsom, marker),
colorPalette = FlowSOM_colors,
lim = NULL,
...){
fsom <- UpdateFlowSOM(fsom)
# Get median values to visualise
mfis <- GetClusterMFIs(fsom)
# Get column names
channels <- GetChannels(fsom, marker)
# Compute limits based on all reference markers
ref_channels <- GetChannels(fsom, refMarkers)
if (is.null(lim)) lim <- c(min(mfis[, ref_channels]),
max(mfis[, ref_channels]))
plotList <- lapply(seq_along(channels), function(channelI){
# Use MFI values as variable to plot
p <- PlotVariable(fsom,
variable = mfis[, channels[channelI]],
variableName = "MFI",
colorPalette = colorPalette,
lim = lim,
...)
# Add title
if (is.na(title[channelI])) title[channelI] <- ""
p <- p + ggplot2::ggtitle(title[channelI])
})
p <- ggpubr::ggarrange(plotlist = plotList, common.legend = TRUE,
legend = "right")
return(p)
}
#' PlotVariable
#'
#' Plot a variable for all nodes
#'
#' Plot FlowSOM grid or tree, coloured by node values given in variable
#'
#' @param fsom FlowSOM object
#' @param variable A vector containing a value for every cluster
#' @param variableName Label to show on the legend
#' @param colorPalette Colorpalette to use. Can be a function or a vector.
#' @param lim Limits for the scale
#' @param ... Additional arguments to pass to \code{\link{PlotFlowSOM}},
#' e.g. view, backgroundValues, equalNodeSize ...
#'
#' @seealso \code{\link{PlotStars}}, \code{\link{QueryStarPlot}},
#' \code{\link{PlotFlowSOM}}, \code{\link{PlotLabels}},
#' \code{\link{PlotNumbers}}, \code{\link{PlotMarker}},
#' \code{\link{PlotPies}}, \code{\link{PlotSD}}
#'
#' @examples
#' # Build FlowSOM model
#' fileName <- system.file("extdata", "68983.fcs", package = "FlowSOM")
#' flowSOM.res <- FlowSOM(fileName,
#' compensate = TRUE, transform = TRUE, scale = FALSE,
#' colsToUse = c(9, 12, 14:18),
#' nClus = 10,
#' seed = 1)
#'
#' # Plot some random values
#' rand <- runif(flowSOM.res$map$nNodes)
#' PlotVariable(flowSOM.res,
#' variable = rand,
#' variableName = "Random")
#'
#' @export
PlotVariable <- function(fsom,
variable,
variableName = "",
colorPalette = FlowSOM_colors,
lim = NULL,
...){
fsom <- UpdateFlowSOM(fsom)
if (length(variable) != fsom$map$nNodes){
stop(paste0("Length of 'variable' should be equal to number of clusters in",
" FlowSOM object (", fsom$map$nNodes, " clusters and ",
length(variable), " variables)."))
}
# Base plot
p <- PlotFlowSOM(fsom = fsom,
...)
p <- AddNodes(p = p,
values = variable,
colorPalette = colorPalette,
lim = lim,
label = variableName)
return(p)
}
#' PlotDimRed
#'
#' Plot a dimensionality reduction
#'
#' Plot a dimensionality reduction of fsom$data
#'
#' @param fsom FlowSOM object, as generated by \code{\link{BuildMST}}
#' @param colsToUse The columns used for the dimensionality reduction.
#' Default = fsom$map$colsUsed.
#' @param colorBy Defines how the dimensionality reduction will be
#' colored. Can be "metaclusters" (default), "clusters"
#' or a marker/channel/index.
#' @param cTotal The total amount of cells to be used in the
#' dimensionality reduction. Default is all the cells.
#' @param dimred A dimensionality reduction function.
#' Default = Rtsne::Rtsne. Alternatively, a data.frame or
#' matrix with either equal number of rows to the
#' fsom or an OriginalID column. Recommended to put
#' cTotal to NULL when providing a matrix (or ensuring
#' that the dimred corresponds to subsampling the
#' flowSOM data for cTotal cells with the same seed).
#' @param extractLayout A function to extract the coordinates from the results
#' of the dimred default = function(dimred){dimred$Y}.
#' @param label If label = TRUE (default), labels are added to plot.
#' @param returnLayout If TRUE, this function returns a dataframe with
#' the layout of dimred and the original IDs and the
#' plot. Default = FALSE.
#' @param seed A seed for reproducibility.
#' @param title A title for the plot.
#' @param ... Additional arguments to pass to dimred.
#'
#' @return A dimensionality reduction plot made in ggplot2
#'
#' @examples
#' file <- system.file("extdata", "68983.fcs", package="FlowSOM")
#' flowSOM.res <- FlowSOM(file, compensate = TRUE, transform = TRUE,
#' scale = TRUE,
#' colsToUse = c(9, 12, 14:18), nClus = 10, silent = FALSE,
#' xdim = 7, ydim = 7)
#' PlotDimRed(flowSOM.res, cTotal = 5000, seed = 1, title = "t-SNE")
#' PlotDimRed(flowSOM.res, cTotal = 5000, colorBy = "CD3", seed = 1,
#' title = "t-SNE")
#'
#' @import ggplot2
#' @importFrom Rtsne Rtsne
#' @importFrom scattermore geom_scattermore
#' @importFrom tidyr pivot_longer
#'
#' @export
PlotDimRed <- function(fsom,
colsToUse = fsom$map$colsUsed,
colorBy = "metaclusters",
cTotal = NULL,
dimred = Rtsne::Rtsne,
extractLayout = function(dimred){dimred$Y},
label = TRUE,
returnLayout = FALSE,
seed = NULL,
title = NULL,
...){
dimred_data <- fsom$data
if (length(colorBy) == 1 && colorBy == "metaclusters") {
if (is.null(fsom$metaclustering)) stop("No metaclustering present")
dimred_col <- as.data.frame(GetMetaclusters(fsom))
} else if (length(colorBy) == 1 && colorBy == "clusters") {
dimred_col <- as.data.frame(as.factor(GetClusters(fsom)))
} else if (all(colorBy %in% colnames(dimred_data)) ||
all(colorBy %in% GetMarkers(fsom, colnames(dimred_data))) ||
all(colorBy %in% seq_len(ncol(dimred_data)))){
dimred_col <- fsom$data[, GetChannels(fsom, colorBy), drop = FALSE]
colnames(dimred_col) <- GetMarkers(fsom, colnames(dimred_col))
colorBy <- "marker"
} else stop(paste0("colorBy should be \"metaclusters\", \"clusters\" or a ",
"vector of channels, markers or indices"))
if (!is.null(colsToUse)) dimred_data <- dimred_data[, GetChannels(fsom,
colsToUse)]
if (!is.null(seed)) set.seed(seed)
if (!is.null(cTotal) && cTotal < nrow(dimred_data)) {
downsample <- sample(seq_len(nrow(dimred_data)), cTotal)
dimred_data <- dimred_data[downsample, , drop = FALSE]
dimred_col <- dimred_col[downsample, , drop = FALSE]
} else {
downsample <- seq_len(nrow(dimred_data))
}
if (is.function(dimred)){
dimred_res <- dimred(dimred_data, ...)
dimred_layout <- as.data.frame(extractLayout(dimred_res))
if (nrow(dimred_layout) == 0 && ncol(dimred_layout) != 2) {
stop("Please use the right extraction function in extractLayout")
}
} else if((is.matrix(dimred) | is.data.frame(dimred)) &
(nrow(dimred) == nrow(dimred_data) |
any(colnames(dimred) == "Original_ID"))){
id_col <- which(colnames(dimred) == "Original_ID")
dimred_layout <- as.data.frame(dimred[,-id_col])
if("Original_ID" %in% colnames(dimred)){
dimred_data <- dimred_data[dimred[,"Original_ID"], , drop = FALSE]
dimred_col <- dimred_col[dimred[,"Original_ID"], , drop = FALSE]
}
} else stop("dimred should be a dimensionality reduction method or matrix")
colnames(dimred_layout) <- c("dimred_1", "dimred_2")
dimred_plot <- cbind(dimred_layout, dimred_col)
if (colorBy == "marker"){
dimred_plot <- dimred_plot %>% tidyr::pivot_longer(3:ncol(dimred_plot),
names_to = "markers")
p <- ggplot2::ggplot(dimred_plot) +
scattermore::geom_scattermore(ggplot2::aes(x = .data$dimred_1,
y = .data$dimred_2,
col = .data$value),
pointsize = 1) +
ggplot2::facet_wrap(~markers) +
ggplot2::theme_minimal() +
ggplot2::coord_fixed() +
ggplot2::scale_color_gradientn(colours = FlowSOM_colors(9))
} else {
colnames(dimred_plot) <- c("dimred_1", "dimred_2", "colors")
median_x <- tapply(dimred_plot[,"dimred_1"], dimred_plot[,"colors"], median)
median_y <- tapply(dimred_plot[,"dimred_2"], dimred_plot[,"colors"], median)
p <- ggplot2::ggplot(dimred_plot) +
scattermore::geom_scattermore(ggplot2::aes(x = .data$dimred_1,
y = .data$dimred_2,
col = .data$colors),
pointsize = 1) +
ggplot2::theme_minimal() +
ggplot2::coord_fixed()
if (label){
p <- p + ggrepel::geom_label_repel(aes(x = .data$x,
y = .data$y,
label = .data$label,
color = .data$label),
data = data.frame(x = median_x,
y = median_y,
label = names(median_x)),
segment.color = "grey", force = 20,
segment.size = 0.2, point.padding = 0.5)+
labs(col = colorBy)
}
}
if (!is.null(title)) p <- p + ggplot2::ggtitle(title)
if (returnLayout) {
if (!is.null(cTotal)){
dimred_layout <- data.frame(dimred_layout, "Original_ID" = downsample)
}
return(list("plot" = p, "layout" = dimred_layout))
} else return(p)
}
#' QueryStarPlot
#'
#' Query a certain cell type
#'
#' Identify nodes in the tree which resemble a certain profile of "high"
#' or "low" marker expressions.
#'
#' @param fsom FlowSOM object, as generated by \code{\link{BuildMST}}
#' @param query Array containing "high" or "low" for the specified
#' column names of the FlowSOM data.
#' @param plot If true, a plot with a gradient of scores for the
#' nodes is shown.
#' @param colorPalette ColorPalette to be used for colors for "stars",
#' "pies" or "marker". Can be either a function or an
#' array specifying colors.
#' @param backgroundColors Color to use for nodes with a high score in the plot.
#' Default is red.
#' @param ... Additional arguments to pass to \code{\link{PlotFlowSOM}}
#'
#' @return A list, containing the ids of the selected nodes, the individual
#' scores for all nodes and the scores for each marker for each node
#'
#' @seealso \code{\link{PlotStars}}, \code{\link{PlotVariable}},
#' \code{\link{PlotFlowSOM}}, \code{\link{PlotLabels}},
#' \code{\link{PlotNumbers}}, \code{\link{PlotMarker}},
#' \code{\link{PlotPies}}, \code{\link{PlotSD}}
#'
#' @examples
#' file <- system.file("extdata", "68983.fcs", package="FlowSOM")
#' flowSOM.res <- FlowSOM(file, compensate = TRUE, transform = TRUE,
#' scale = TRUE, colsToUse = c(9, 12, 14:18), nClus = 10,
#' silent = FALSE, xdim = 7, ydim = 7)
#' query <- c("CD3" = "high", #CD3
#' "CD4" = "low", #TCRb
#' "CD8" = "high") #CD8
#' query_res <- QueryStarPlot(flowSOM.res, query, equalNodeSize = TRUE)
#'
#' cellTypes <- factor(rep("Unlabeled", 49),
#' levels = c("Unlabeled", "CD8 T cells"))
#' cellTypes[query_res$selected] <- "CD8 T cells"
#' PlotStars(flowSOM.res,
#' backgroundValues = cellTypes,
#' backgroundColors = c("#FFFFFF00", "#ca0020aa"))
#'
#' @importFrom grDevices colorRampPalette
#' @importFrom ggpubr ggarrange
#'
#' @export
QueryStarPlot <- function(fsom,
query,
plot = TRUE,
colorPalette = FlowSOM_colors,
backgroundColors = "#CA0020",
...){
fsom <- UpdateFlowSOM(fsom)
names(query) <- GetChannels(fsom, names(query))
markers <- names(query)
lowMarkers <- which(query == "low")
query <- ParseQuery(fsom, query)
if (plot){
fP <- PlotStars(fsom = fsom,
markers = markers,
backgroundColors =
grDevices::colorRampPalette(c(rep("#FFFFFF00", 3),
backgroundColors)),
backgroundValues = query$nodeScores,
list_insteadof_ggarrange = TRUE,
...)
nMarkers <- length(markers)
starHeight <- rep(1, nMarkers)
starHeight[lowMarkers] <- 0
l <- PlotStarLegend(fsom$prettyColnames[markers],
colors = colorPalette(nMarkers),
starHeight = starHeight)
p <- ggpubr::ggarrange(fP$tree,
ggpubr::ggarrange(l, fP$backgroundLegend, ncol = 1),
NULL,
ncol = 3,
widths = c(3, 1, 0.3),
legend = "none")
query$plot <- p
}
return(query)
}
#' QueryMultiple
#'
#' Function which takes a named list of multiple cell types, where every item is
#' a named vector with values "high"/"low" and the names correspond to the
#' markers or channels (e.g. as generated by parse_markertable).
#'
#' @param fsom FlowSOM object
#' @param cellTypes Description of the cell types. Named list, with one named
#' vector per cell type containing "high"/"low" values
#' @param plotFile Path to a pdf file to save the plots (default is
#' queryMultiple.pdf). If \code{NULL}, no plots will be
#' generated
#' @param ... Additional arguments to pass to \code{\link{QueryStarPlot}}
#'
#' @return A label for every FlowSOM cluster (Unknown or one of the celltype
#' names of the list, if selected by QueryStarPlot)
#'
#' @examples
#' file <- system.file("extdata", "68983.fcs", package = "FlowSOM")
#' ff <- flowCore::read.FCS(file)
#' # Use the wrapper function to build a flowSOM object (saved in flowSOM.res)
#' # and a metaclustering (saved in flowSOM.res[["metaclustering"]])
#' flowSOM.res <- FlowSOM(ff, compensate = TRUE, transform = TRUE, scale = TRUE,
#' colsToUse = c(9, 12, 14:18), nClus = 10, silent = FALSE,
#' xdim = 7, ydim = 7)
#' cellTypes <- list("CD8 T cells" = c("PE-Cy7-A" = "high",
#' "APC-Cy7-A" = "high",
#' "Pacific Blue-A" = "high"),
#' "B cells" = c("PE-Cy5-A" = "high"),
#' "NK cells" = c("PE-A" = "high",
#' "PE-Cy7-A" = "low",
#' "APC-Cy7-A" = "low"))
#' query_res <- QueryMultiple(flowSOM.res, cellTypes, "query_multiple.pdf")
#'
#' @export
QueryMultiple <- function(fsom,
cellTypes,
plotFile = "queryMultiple.pdf",
...){
fsom <- UpdateFlowSOM(fsom)
labels <- rep("Unlabeled", fsom$map$nNodes)
plotList <- list()
plot <- ifelse(is.null(plotFile), FALSE, TRUE)
for(cell_type in names(cellTypes)){
query <- cellTypes[[cell_type]]
query_res <- QueryStarPlot(fsom,
equalNodeSize = TRUE,
query = query,
title = cell_type,
plot = plot,
...)
if (plot) plotList[[cell_type]] <- query_res$plot
labels[query_res$selected] <- cell_type
}
if (plot){
pdf(plotFile, useDingbats = FALSE)
for (p in plotList){
print(p)
}
dev.off()
}
return(labels)
}
#' PlotSD
#'
#' Plot FlowSOM grid or tree, coloured by standard deviaton.
#'
#' @param fsom FlowSOM object, as generated by \code{\link{FlowSOM}}
#' @param marker If a marker/channel is given, the sd for this marker is
#' shown. Otherwise, the maximum ratio is used.
#' @param ... Additional arguments to pass to \code{\link{PlotFlowSOM}}
#'
#' @return Nothing is returned. A plot is drawn in which each node
#' is coloured depending on its standard deviation
#'
#' @seealso \code{\link{PlotStars}}, \code{\link{PlotVariable}},
#' \code{\link{PlotFlowSOM}}, \code{\link{PlotLabels}},
#' \code{\link{PlotNumbers}}, \code{\link{PlotMarker}},
#' \code{\link{PlotPies}}, \code{\link{QueryStarPlot}}
#'
#' @examples
#' # Read from file, build self-organizing map and minimal spanning tree
#' fileName <- system.file("extdata", "68983.fcs", package = "FlowSOM")
#' flowSOM.res <- ReadInput(fileName, compensate = TRUE, transform = TRUE,
#' scale = TRUE)
#' flowSOM.res <- BuildSOM(flowSOM.res, colsToUse = c(9, 12, 14:18))
#' flowSOM.res <- BuildMST(flowSOM.res)
#'
#' PlotSD(flowSOM.res)
#'
#' @importFrom grDevices colorRampPalette
#'
#' @export
PlotSD <- function(fsom,
marker = NULL,
...){
fsom <- UpdateFlowSOM(fsom)
if(!is.null(marker)) marker <- GetChannels(fsom, marker)
SDs <- ParseSD(fsom, marker)
PlotVariable(fsom = fsom,
variable = SDs,
variableName = "SD",
...)
}
#' PlotStarLegend
#'
#' Plots star legend
#'
#' Function makes the legend of the FlowSOM star plot
#'
#' @param markers Vector of markers used in legend
#' @param colors ColorPalette for the legend. Can be a vector or a
#' function.
#' @param starHeight Star height. Default = 1.
#'
#' @return Returns nothing, but plots a legend for FlowSOM star plot
#'
#' @seealso \code{\link{PlotFlowSOM}}
#'
#' @examples
#' PlotStarLegend(c("CD3", "CD4", "CD8"),