/
plot_dr.R
executable file
·1387 lines (1291 loc) · 50.5 KB
/
plot_dr.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
#' @title Mapping the dimension reduction plot
#' @description Creates a scatterplot given two dimensions from a data
#' dimension reduction tool (e.g tSNE) output.
#' @param x Numeric matrix or a \linkS4class{SingleCellExperiment} object
#' with the matrix located in the assay slot under \code{useAssay}. Each
#' row of the matrix will be plotted as a separate facet.
#' @param reducedDimName The name of the dimension reduction slot in
#' \code{reducedDimNames(x)} if \code{x} is a
#' \linkS4class{SingleCellExperiment} object. Ignored if both \code{dim1} and
#' \code{dim2} are set.
#' @param dim1 Numeric vector. Second dimension from data dimension
#' reduction output.
#' @param dim2 Numeric vector. Second dimension from data dimension
#' reduction output.
#' @param useAssay A string specifying which \link{assay}
#' slot to use if \code{x} is a
#' \linkS4class{SingleCellExperiment} object. Default "counts".
#' @param altExpName The name for the \link{altExp} slot
#' to use. Default "featureSubset".
#' @param size Numeric. Sets size of point on plot. Default 1.
#' @param xlab Character vector. Label for the x-axis. Default 'Dimension_1'.
#' @param ylab Character vector. Label for the y-axis. Default 'Dimension_2'.
#' @param limits Passed to \link{scale_colour_gradient2}. The range
#' of color scale.
#' @param colorLow Character. A color available from `colors()`.
#' The color will be used to signify the lowest values on the scale.
#' Default "blue4".
#' @param colorMid Character. A color available from `colors()`.
#' The color will be used to signify the midpoint on the scale. Default
#' "grey90".
#' @param colorHigh Character. A color available from `colors()`.
#' The color will be used to signify the highest values on the scale.
#' Default "firebrick1".
#' @param midpoint Numeric. The value indicating the midpoint of the
#' diverging color scheme. If \code{NULL}, defaults to the mean
#' with 10 percent of values trimmed. Default \code{0}.
#' @param varLabel Character vector. Title for the color legend.
#' @param ncol Integer. Passed to \link[ggplot2]{facet_wrap}. Specify the
#' number of columns for facet wrap.
#' @param headers Character vector. If `NULL`, the corresponding rownames are
#' used as labels. Otherwise, these headers are used to label the genes.
#' @param decreasing logical. Specifies the order of plotting the points.
#' If \code{FALSE}, the points will be plotted in increasing order where
#' the points with largest values will be on top. \code{TRUE} otherwise.
#' If \code{NULL}, no sorting is performed. Points will be plotted in their
#' current order in \code{x}. Default \code{FALSE}.
#' @return The plot as a ggplot object
#' @export
setGeneric("plotDimReduceGrid",
function(x,
reducedDimName,
dim1 = NULL,
dim2 = NULL,
useAssay = "counts",
altExpName = "featureSubset",
size = 1,
xlab = "Dimension_1",
ylab = "Dimension_2",
limits = c(-2, 2),
colorLow = "blue4",
colorMid = "grey90",
colorHigh = "firebrick1",
midpoint = 0,
varLabel = NULL,
ncol = NULL,
headers = NULL,
decreasing = FALSE) {
standardGeneric("plotDimReduceGrid")
})
#' @rdname plotDimReduceGrid
#' @examples
#' data(sceCeldaCG)
#' sce <- celdaTsne(sceCeldaCG)
#' plotDimReduceGrid(x = sce,
#' reducedDimName = "celda_tSNE",
#' xlab = "Dimension1",
#' ylab = "Dimension2",
#' varLabel = "tSNE")
#' @export
setMethod("plotDimReduceGrid",
signature(x = "SingleCellExperiment"),
function(x,
reducedDimName,
dim1 = NULL,
dim2 = NULL,
useAssay = "counts",
altExpName = "featureSubset",
size = 1,
xlab = "Dimension_1",
ylab = "Dimension_2",
limits = c(-2, 2),
colorLow = "blue4",
colorMid = "grey90",
colorHigh = "firebrick1",
midpoint = 0,
varLabel = NULL,
ncol = NULL,
headers = NULL,
decreasing = FALSE) {
altExp <- SingleCellExperiment::altExp(x, altExpName)
matrix <- SummarizedExperiment::assay(x, i = useAssay)
if (is.null(dim1)) {
dim1 <- SingleCellExperiment::reducedDim(altExp,
reducedDimName)[, 1]
}
if (is.null(dim2)) {
dim2 <- SingleCellExperiment::reducedDim(altExp,
reducedDimName)[, 2]
}
g <- .plotDimReduceGrid(
dim1 = dim1,
dim2 = dim2,
matrix = matrix,
size = size,
xlab = xlab,
ylab = ylab,
limits = limits,
colorLow = colorLow,
colorMid = colorMid,
colorHigh = colorHigh,
midpoint = midpoint,
varLabel = varLabel,
ncol = ncol,
headers = headers,
decreasing = decreasing
)
return(g)
})
#' @rdname plotDimReduceGrid
#' @examples
#' library(SingleCellExperiment)
#' data(sceCeldaCG)
#' sce <- celdaTsne(sceCeldaCG)
#' plotDimReduceGrid(x = counts(sce),
#' dim1 = reducedDim(altExp(sce), "celda_tSNE")[, 1],
#' dim2 = reducedDim(altExp(sce), "celda_tSNE")[, 2],
#' xlab = "Dimension1",
#' ylab = "Dimension2",
#' varLabel = "tSNE")
#' @export
setMethod("plotDimReduceGrid",
signature(x = "ANY"),
function(x,
dim1,
dim2,
size = 1,
xlab = "Dimension_1",
ylab = "Dimension_2",
limits = c(-2, 2),
colorLow = "blue4",
colorMid = "grey90",
colorHigh = "firebrick1",
midpoint = 0,
varLabel = NULL,
ncol = NULL,
headers = NULL,
decreasing = FALSE) {
x <- as.matrix(x)
g <- .plotDimReduceGrid(
dim1 = dim1,
dim2 = dim2,
matrix = x,
size = size,
xlab = xlab,
ylab = ylab,
limits = limits,
colorLow = colorLow,
colorMid = colorMid,
colorHigh = colorHigh,
midpoint = midpoint,
varLabel = varLabel,
ncol = ncol,
headers = headers,
decreasing = decreasing
)
return(g)
})
#' @importFrom reshape2 melt
.plotDimReduceGrid <- function(dim1,
dim2,
matrix,
size,
xlab,
ylab,
limits,
colorLow,
colorMid,
colorHigh,
midpoint,
varLabel,
ncol,
headers,
decreasing) {
df <-
data.frame(dim1, dim2, t(as.data.frame(matrix)), check.names = FALSE)
naIx <- is.na(dim1) | is.na(dim2)
df <- df[!naIx, ]
m <- reshape2::melt(df, id.vars = c("dim1", "dim2"))
colnames(m) <- c(xlab, ylab, "facet", "Expression")
if (!is.null(decreasing)) {
m <- m[order(m$facet, m$Expression, decreasing = decreasing), ]
}
if (is.null(midpoint)) {
midpoint <- mean(m[, 4], trim = 0.1)
}
varLabel <- gsub("_", " ", varLabel)
if (isFALSE(is.null(headers))) {
names(headers) <- levels(m$facet)
headers <- ggplot2::as_labeller(headers)
g <- ggplot2::ggplot(m,
ggplot2::aes_string(x = xlab, y = ylab)) +
ggplot2::geom_point(stat = "identity",
size = size,
ggplot2::aes_string(color = m$Expression)) +
ggplot2::theme_bw() +
ggplot2::scale_colour_gradient2(
limits = limits,
low = colorLow,
high = colorHigh,
mid = colorMid,
midpoint = midpoint,
name = varLabel
) +
ggplot2::theme(
strip.background = ggplot2::element_blank(),
panel.grid.major = ggplot2::element_blank(),
panel.grid.minor = ggplot2::element_blank(),
panel.spacing = unit(0, "lines"),
panel.background = ggplot2::element_blank(),
axis.line = ggplot2::element_line(colour = "black")
)
if (isFALSE(is.null(ncol))) {
g <- g + ggplot2::facet_wrap(~ facet,
labeller = headers,
ncol = ncol)
} else {
g <- g + ggplot2::facet_wrap(~ facet, labeller = headers)
}
} else {
g <- ggplot2::ggplot(m,
ggplot2::aes_string(x = xlab, y = ylab)) +
ggplot2::geom_point(stat = "identity",
size = size,
ggplot2::aes_string(color = m$Expression)) +
ggplot2::facet_wrap(~ facet) +
ggplot2::theme_bw() +
ggplot2::scale_colour_gradient2(
limits = limits,
low = colorLow,
high = colorHigh,
mid = colorMid,
midpoint = midpoint,
name = varLabel
) +
ggplot2::theme(
strip.background = ggplot2::element_blank(),
panel.grid.major = ggplot2::element_blank(),
panel.grid.minor = ggplot2::element_blank(),
panel.spacing = unit(0, "lines"),
panel.background = ggplot2::element_blank(),
axis.line = ggplot2::element_line(colour = "black")
)
if (isFALSE(is.null(ncol))) {
g <- g + ggplot2::facet_wrap(~ facet, ncol = ncol)
} else {
g <- g + ggplot2::facet_wrap(~ facet)
}
}
return(g)
}
#' @title Plotting feature expression on a dimension reduction plot
#' @description Create a scatterplot for each row of a normalized gene
#' expression matrix where x and y axis are from a data dimension
#' reduction tool. The cells are colored by expression of
#' the specified feature.
#' @param x Numeric matrix or a \linkS4class{SingleCellExperiment} object
#' with the matrix located in the assay slot under \code{useAssay}. Rows
#' represent features and columns represent cells.
#' @param features Character vector. Features in the rownames of counts to plot.
#' @param reducedDimName The name of the dimension reduction slot in
#' \code{reducedDimNames(x)} if \code{x} is a
#' \linkS4class{SingleCellExperiment} object. If \code{NULL}, then both
#' \code{dim1} and \code{dim2} need to be set. Default \code{NULL}.
#' @param displayName Character. The column name of
#' \code{rowData(x)} that specifies the display names for
#' the features. Default \code{NULL}, which displays the row names. Only works
#' if \code{x} is a \linkS4class{SingleCellExperiment} object. Overwrites
#' \code{headers}.
#' @param dim1 Integer or numeric vector. If \code{reducedDimName} is supplied,
#' then, this will be used as an index to determine which dimension will be
#' plotted on the x-axis. If \code{reducedDimName} is not supplied, then this
#' should be a vector which will be plotted on the x-axis. Default \code{1}.
#' @param dim2 Integer or numeric vector. If \code{reducedDimName} is supplied,
#' then, this will be used as an index to determine which dimension will be
#' plotted on the y-axis. If \code{reducedDimName} is not supplied, then this
#' should be a vector which will be plotted on the y-axis. Default \code{2}.
#' @param headers Character vector. If \code{NULL}, the corresponding
#' rownames are used as labels. Otherwise, these headers are used to label
#' the features. Only works if \code{displayName} is \code{NULL} and
#' \code{exactMatch} is \code{FALSE}.
#' @param useAssay A string specifying which \link{assay}
#' slot to use if \code{x} is a
#' \linkS4class{SingleCellExperiment} object. Default "counts".
#' @param altExpName The name for the \link{altExp} slot
#' to use. Default "featureSubset".
#' @param normalize Logical. Whether to normalize the columns of `counts`.
#' Default \code{FALSE}.
#' @param zscore Logical. Whether to scale each feature to have a mean 0
#' and standard deviation of 1. Default \code{TRUE}.
#' @param exactMatch Logical. Whether an exact match or a partial match using
#' \code{grep()} is used to look up the feature in the rownames of the counts
#' matrix. Default TRUE.
#' @param trim Numeric vector. Vector of length two that specifies the lower
#' and upper bounds for the data. This threshold is applied after row scaling.
#' Set to NULL to disable. Default \code{c(-1,1)}.
#' @param limits Passed to \link{scale_colour_gradient2}. The range
#' of color scale.
#' @param size Numeric. Sets size of point on plot. Default 1.
#' @param xlab Character vector. Label for the x-axis. If \code{reducedDimName}
#' is used, then this will be set to the column name of the first dimension of
#' that object. Default "Dimension_1".
#' @param ylab Character vector. Label for the y-axis. If \code{reducedDimName}
#' is used, then this will be set to the column name of the second dimension of
#' that object. Default "Dimension_2".
#' @param colorLow Character. A color available from `colors()`. The color
#' will be used to signify the lowest values on the scale.
#' @param colorMid Character. A color available from `colors()`. The color
#' will be used to signify the midpoint on the scale.
#' @param colorHigh Character. A color available from `colors()`. The color
#' will be used to signify the highest values on the scale.
#' @param midpoint Numeric. The value indicating the midpoint of the
#' diverging color scheme. If \code{NULL}, defaults to the mean
#' with 10 percent of values trimmed. Default \code{0}.
#' @param ncol Integer. Passed to \link[ggplot2]{facet_wrap}. Specify the
#' number of columns for facet wrap.
#' @param decreasing logical. Specifies the order of plotting the points.
#' If \code{FALSE}, the points will be plotted in increasing order where
#' the points with largest values will be on top. \code{TRUE} otherwise.
#' If \code{NULL}, no sorting is performed. Points will be plotted in their
#' current order in \code{x}. Default \code{FALSE}.
#' @return The plot as a ggplot object
#' @export
setGeneric("plotDimReduceFeature", function(x,
features,
reducedDimName = NULL,
displayName = NULL,
dim1 = NULL,
dim2 = NULL,
headers = NULL,
useAssay = "counts",
altExpName = "featureSubset",
normalize = FALSE,
zscore = TRUE,
exactMatch = TRUE,
trim = c(-2, 2),
limits = c(-2, 2),
size = 0.5,
xlab = NULL,
ylab = NULL,
colorLow = "blue4",
colorMid = "grey90",
colorHigh = "firebrick1",
midpoint = 0,
ncol = NULL,
decreasing = FALSE) {
standardGeneric("plotDimReduceFeature")
})
#' @rdname plotDimReduceFeature
#' @examples
#' data(sceCeldaCG)
#' sce <- celdaTsne(sceCeldaCG)
#' plotDimReduceFeature(x = sce,
#' reducedDimName = "celda_tSNE",
#' normalize = TRUE,
#' features = c("Gene_98", "Gene_99"),
#' exactMatch = TRUE)
#' @export
setMethod("plotDimReduceFeature",
signature(x = "SingleCellExperiment"),
function(x,
features,
reducedDimName,
displayName = NULL,
dim1 = 1,
dim2 = 2,
headers = NULL,
useAssay = "counts",
altExpName = "featureSubset",
normalize = FALSE,
zscore = TRUE,
exactMatch = TRUE,
trim = c(-2, 2),
limits = c(-2, 2),
size = 0.5,
xlab = NULL,
ylab = NULL,
colorLow = "blue4",
colorMid = "grey90",
colorHigh = "firebrick1",
midpoint = 0,
ncol = NULL,
decreasing = FALSE) {
altExp <- SingleCellExperiment::altExp(x, altExpName)
counts <- SummarizedExperiment::assay(x, i = useAssay)
reddim <- .processReducedDim(
x = altExp,
reducedDimName = reducedDimName,
dim1 = dim1,
dim2 = dim2,
xlab = xlab,
ylab = ylab
)
if (isFALSE(is.null(displayName))) {
featuresIx <- retrieveFeatureIndex(features,
x,
by = displayName,
exactMatch = exactMatch)
headers <- SummarizedExperiment::rowData(x)[[displayName]][featuresIx]
} else {
featuresIx <- retrieveFeatureIndex(features,
counts,
by = "rownames",
exactMatch = exactMatch)
if (isFALSE(is.null(headers))) {
if (length(headers) != length(features)) {
stop("Headers ",
headers,
" should be the same length as features ",
features)
}
if (isFALSE(exactMatch)) {
warning("exactMatch is FALSE. headers will not be used!")
headers <- NULL
}
}
}
g <- .plotDimReduceFeature(
dim1 = reddim$dim1,
dim2 = reddim$dim2,
counts = counts,
features = features,
headers = headers,
normalize = normalize,
zscore = zscore,
featuresIx = featuresIx,
trim = trim,
limits = limits,
size = size,
xlab = reddim$xlab,
ylab = reddim$ylab,
colorLow = colorLow,
colorMid = colorMid,
colorHigh = colorHigh,
midpoint = midpoint,
ncol = ncol,
decreasing = decreasing
)
return(g)
})
#' @rdname plotDimReduceFeature
#' @examples
#' library(SingleCellExperiment)
#' data(sceCeldaCG)
#' sce <- celdaTsne(sceCeldaCG)
#' plotDimReduceFeature(x = counts(sce),
#' dim1 = reducedDim(altExp(sce), "celda_tSNE")[, 1],
#' dim2 = reducedDim(altExp(sce), "celda_tSNE")[, 2],
#' normalize = TRUE,
#' features = c("Gene_98", "Gene_99"),
#' exactMatch = TRUE)
#' @export
setMethod("plotDimReduceFeature",
signature(x = "ANY"),
function(x,
features,
dim1,
dim2,
headers = NULL,
normalize = FALSE,
zscore = TRUE,
exactMatch = TRUE,
trim = c(-2, 2),
limits = c(-2, 2),
size = 0.5,
xlab = "Dimension_1",
ylab = "Dimension_2",
colorLow = "blue4",
colorMid = "grey90",
colorHigh = "firebrick1",
midpoint = 0,
ncol = NULL,
decreasing = FALSE) {
x <- as.matrix(x)
if (isFALSE(is.null(headers))) {
if (length(headers) != length(features)) {
stop("Headers ",
headers,
" should be the same length as features ",
features)
}
if (isFALSE(exactMatch)) {
warning("exactMatch is FALSE. headers will not be used!")
headers <- NULL
}
}
featuresIx <- retrieveFeatureIndex(features,
x,
by = "rownames",
exactMatch = exactMatch)
g <- .plotDimReduceFeature(
dim1 = dim1,
dim2 = dim2,
counts = x,
features = features,
headers = headers,
normalize = normalize,
zscore = zscore,
featuresIx = featuresIx,
trim = trim,
limits = limits,
size = size,
xlab = xlab,
ylab = ylab,
colorLow = colorLow,
colorMid = colorMid,
colorHigh = colorHigh,
midpoint = midpoint,
ncol = ncol,
decreasing = decreasing
)
return(g)
})
.plotDimReduceFeature <- function(dim1,
dim2,
counts,
features,
headers,
normalize,
zscore,
featuresIx,
trim,
limits,
size,
xlab,
ylab,
colorLow,
colorMid,
colorHigh,
midpoint,
ncol,
decreasing) {
# Perform checks
if (is.null(features)) {
stop("at least one feature is required to create a plot")
}
## Normalize data if needed
if (isTRUE(normalize)) {
counts <- normalizeCounts(counts, transformationFun = sqrt)
}
# After normalization, features can be selected
featuresIx <- featuresIx[stats::complete.cases(featuresIx)]
counts <- as.matrix(counts[featuresIx, , drop = FALSE])
# Scale/zscore data if needed
varLabel <- "Expression"
if (isTRUE(zscore)) {
counts <- t(scale(t(counts)))
varLabel <- "Scaled\nExpression"
}
if (!is.null(trim)) {
if (length(trim) != 2) {
stop("'trim' should be a 2 element vector",
"specifying the lower and upper boundaries")
}
trim <- sort(trim)
counts[counts < trim[1]] <- trim[1]
counts[counts > trim[2]] <- trim[2]
}
.plotDimReduceGrid(
dim1 = dim1,
dim2 = dim2,
matrix = counts,
size = size,
xlab = xlab,
ylab = ylab,
limits = limits,
colorLow = colorLow,
colorMid = colorMid,
colorHigh = colorHigh,
varLabel = varLabel,
midpoint = midpoint,
ncol = ncol,
headers = headers,
decreasing = decreasing
)
}
#' @title Plotting Celda module probability on a
#' dimension reduction plot
#' @description Create a scatterplot for each row of a normalized
#' gene expression matrix where x and y axis are from a data
#' dimension reduction tool.
#' The cells are colored by the module probability.
#' @param x Numeric matrix or a \linkS4class{SingleCellExperiment} object
#' with the matrix located in the assay slot under \code{useAssay}. Rows
#' represent features and columns represent cells.
#' @param reducedDimName The name of the dimension reduction slot in
#' \code{reducedDimNames(x)} if \code{x} is a
#' \linkS4class{SingleCellExperiment} object. Ignored if both \code{dim1} and
#' \code{dim2} are set.
#' @param dim1 Integer or numeric vector. If \code{reducedDimName} is supplied,
#' then, this will be used as an index to determine which dimension will be
#' plotted on the x-axis. If \code{reducedDimName} is not supplied, then this
#' should be a vector which will be plotted on the x-axis. Default \code{1}.
#' @param dim2 Integer or numeric vector. If \code{reducedDimName} is supplied,
#' then, this will be used as an index to determine which dimension will be
#' plotted on the y-axis. If \code{reducedDimName} is not supplied, then this
#' should be a vector which will be plotted on the y-axis. Default \code{2}.
#' @param useAssay A string specifying which \link{assay}
#' slot to use if \code{x} is a
#' \linkS4class{SingleCellExperiment} object. Default "counts".
#' @param altExpName The name for the \link{altExp} slot
#' to use. Default "featureSubset".
#' @param celdaMod Celda object of class "celda_G" or "celda_CG". Used only if
#' \code{x} is a matrix object.
#' @param modules Character vector. Module(s) from celda model to be plotted.
#' e.g. c("1", "2").
#' @param size Numeric. Sets size of point on plot. Default 0.5.
#' @param xlab Character vector. Label for the x-axis. Default "Dimension_1".
#' @param ylab Character vector. Label for the y-axis. Default "Dimension_2".
#' @param colorLow Character. A color available from `colors()`.
#' The color will be used to signify the lowest values on the scale.
#' @param rescale Logical.
#' Whether rows of the matrix should be rescaled to [0, 1]. Default TRUE.
#' @param limits Passed to \link{scale_colour_gradient}. The range
#' of color scale.
#' @param colorHigh Character. A color available from `colors()`.
#' The color will be used to signify the highest values on the scale.
#' @param ncol Integer. Passed to \link[ggplot2]{facet_wrap}. Specify the
#' number of columns for facet wrap.
#' @param decreasing logical. Specifies the order of plotting the points.
#' If \code{FALSE}, the points will be plotted in increasing order where
#' the points with largest values will be on top. \code{TRUE} otherwise.
#' If \code{NULL}, no sorting is performed. Points will be plotted in their
#' current order in \code{x}. Default \code{FALSE}.
#' @return The plot as a ggplot object
#' @export
setGeneric("plotDimReduceModule",
function(x,
reducedDimName,
useAssay = "counts",
altExpName = "featureSubset",
celdaMod,
modules = NULL,
dim1 = NULL,
dim2 = NULL,
size = 0.5,
xlab = NULL,
ylab = NULL,
rescale = TRUE,
limits = c(0, 1),
colorLow = "grey90",
colorHigh = "firebrick1",
ncol = NULL,
decreasing = FALSE) {
standardGeneric("plotDimReduceModule")
})
#' @rdname plotDimReduceModule
#' @examples
#' data(sceCeldaCG)
#' sce <- celdaTsne(sceCeldaCG)
#' plotDimReduceModule(x = sce,
#' reducedDimName = "celda_tSNE",
#' modules = c("1", "2"))
#' @export
setMethod("plotDimReduceModule",
signature(x = "SingleCellExperiment"),
function(x,
reducedDimName,
useAssay = "counts",
altExpName = "featureSubset",
modules = NULL,
dim1 = 1,
dim2 = 2,
size = 0.5,
xlab = NULL,
ylab = NULL,
rescale = TRUE,
limits = c(0, 1),
colorLow = "grey90",
colorHigh = "firebrick1",
ncol = NULL,
decreasing = FALSE) {
# Get reduced dim object
altExp <- SingleCellExperiment::altExp(x, altExpName)
reddim <- .processReducedDim(
x = altExp,
reducedDimName = reducedDimName,
dim1 = dim1,
dim2 = dim2,
xlab = xlab,
ylab = ylab
)
factorized <- factorizeMatrix(x,
useAssay = useAssay,
altExpName = altExpName,
type = "proportion")
g <- .plotDimReduceModule(
dim1 = reddim$dim1,
dim2 = reddim$dim2,
factorized = factorized,
modules = modules,
rescale = rescale,
limits = limits,
size = size,
xlab = reddim$xlab,
ylab = reddim$ylab,
colorLow = colorLow,
colorHigh = colorHigh,
ncol = ncol,
decreasing = decreasing
)
return(g)
})
#' @rdname plotDimReduceModule
#' @examples
#' library(SingleCellExperiment)
#' data(sceCeldaCG, celdaCGMod)
#' sce <- celdaTsne(sceCeldaCG)
#' plotDimReduceModule(x = counts(sce),
#' dim1 = reducedDim(altExp(sce), "celda_tSNE")[, 1],
#' dim2 = reducedDim(altExp(sce), "celda_tSNE")[, 2],
#' celdaMod = celdaCGMod,
#' modules = c("1", "2"))
#' @export
setMethod("plotDimReduceModule",
signature(x = "ANY"),
function(x,
celdaMod,
modules = NULL,
dim1,
dim2,
size = 0.5,
xlab = "Dimension_1",
ylab = "Dimension_2",
rescale = TRUE,
limits = c(0, 1),
colorLow = "grey90",
colorHigh = "firebrick1",
ncol = NULL,
decreasing = FALSE) {
factorized <- factorizeMatrix(x = x, celdaMod = celdaMod)
reddim <- .processReducedDim(
x = x,
dim1 = dim1,
dim2 = dim2,
xlab = xlab,
ylab = ylab
)
g <- .plotDimReduceModule(
dim1 = reddim$dim1,
dim2 = reddim$dim2,
factorized = factorized,
modules = modules,
rescale = rescale,
limits = limits,
size = size,
xlab = reddim$xlab,
ylab = reddim$ylab,
colorLow = colorLow,
colorHigh = colorHigh,
ncol = ncol,
decreasing = decreasing
)
return(g)
})
.plotDimReduceModule <- function(dim1,
dim2,
factorized,
modules,
rescale,
limits,
size,
xlab,
ylab,
colorLow,
colorHigh,
ncol,
decreasing) {
matrix <- factorized$proportions$cell
if (rescale == TRUE) {
for (x in seq(nrow(matrix))) {
matrix[x, ] <- matrix[x, ] - min(matrix[x, ])
matrix[x, ] <- matrix[x, ] / max(matrix[x, ])
varLabel <- "Scaled Probability"
}
} else {
varLabel <- "Probability"
}
rownames(matrix) <- gsub("L", "", rownames(matrix))
if (!is.null(modules)) {
if (length(rownames(matrix)[rownames(matrix) %in% modules]) < 1) {
stop("All modules selected do not exist in the model.")
}
matrix <-
matrix[which(rownames(matrix) %in% modules), , drop = FALSE]
matrix <-
matrix[match(rownames(matrix), modules), , drop = FALSE]
}
rownames(matrix) <- paste0("L", rownames(matrix))
df <-
data.frame(dim1, dim2, t(as.data.frame(matrix)), check.names = FALSE)
naIx <- is.na(dim1) | is.na(dim2)
df <- df[!naIx, ]
m <- reshape2::melt(df, id.vars = c("dim1", "dim2"))
colnames(m) <- c(xlab, ylab, "facet", "Expression")
if (!is.null(decreasing)) {
m <- m[order(m$facet, m$Expression, decreasing = decreasing), ]
}
g <-
ggplot2::ggplot(m, ggplot2::aes_string(x = xlab, y = ylab)) +
ggplot2::geom_point(stat = "identity",
size = size,
ggplot2::aes_string(color = m$Expression)) +
ggplot2::facet_wrap(~ facet) +
ggplot2::theme_bw() +
ggplot2::scale_colour_gradient(
limits = limits,
low = colorLow,
high = colorHigh,
name = varLabel
) +
ggplot2::theme(
strip.background = ggplot2::element_blank(),
panel.grid.major = ggplot2::element_blank(),
panel.grid.minor = ggplot2::element_blank(),
panel.spacing = unit(0, "lines"),
panel.background = ggplot2::element_blank(),
axis.line = ggplot2::element_line(colour = "black")
)
if (isFALSE(is.null(ncol))) {
g <- g + ggplot2::facet_wrap(~ facet, ncol = ncol)
} else {
g <- g + ggplot2::facet_wrap(~ facet)
}
return(g)
}
# Labeling code adapted from Seurat (https://github.com/satijalab/seurat)
#' @title Plotting the cell labels on a dimension reduction plot
#' @description Create a scatterplot for each row of a normalized
#' gene expression matrix where x and y axis are from a
#' data dimension reduction tool.
#' The cells are colored by "celda_cell_cluster" column in
#' \code{colData(altExp(x, altExpName))} if \code{x} is a
#' \linkS4class{SingleCellExperiment} object, or \code{x} if \code{x} is
#' a integer vector of cell cluster labels.
#' @param x Integer vector of cell cluster labels or a
#' \linkS4class{SingleCellExperiment} object
#' containing cluster labels for each cell in \code{"celda_cell_cluster"}
#' column in \code{colData(x)}.
#' @param reducedDimName The name of the dimension reduction slot in
#' \code{reducedDimNames(x)} if \code{x} is a
#' \linkS4class{SingleCellExperiment} object. Ignored if both \code{dim1} and
#' \code{dim2} are set.
#' @param altExpName The name for the \link{altExp} slot
#' to use. Default "featureSubset".
#' @param dim1 Integer or numeric vector. If \code{reducedDimName} is supplied,
#' then, this will be used as an index to determine which dimension will be
#' plotted on the x-axis. If \code{reducedDimName} is not supplied, then this
#' should be a vector which will be plotted on the x-axis. Default \code{1}.
#' @param dim2 Integer or numeric vector. If \code{reducedDimName} is supplied,
#' then, this will be used as an index to determine which dimension will be
#' plotted on the y-axis. If \code{reducedDimName} is not supplied, then this
#' should be a vector which will be plotted on the y-axis. Default \code{2}.
#' @param size Numeric. Sets size of point on plot. Default \code{0.5}.
#' @param xlab Character vector. Label for the x-axis. Default \code{NULL}.
#' @param ylab Character vector. Label for the y-axis. Default \code{NULL}.
#' @param specificClusters Numeric vector.
#' Only color cells in the specified clusters.
#' All other cells will be grey.
#' If NULL, all clusters will be colored. Default \code{NULL}.
#' @param labelClusters Logical. Whether the cluster labels are plotted.
#' Default FALSE.
#' @param groupBy Character vector. Contains sample labels for each cell.
#' If NULL, all samples will be plotted together. Default NULL.
#' @param labelSize Numeric. Sets size of label if labelClusters is TRUE.
#' Default 3.5.
#' @return The plot as a ggplot object
#' @importFrom ggrepel geom_text_repel
#' @export
setGeneric("plotDimReduceCluster",
function(x,
reducedDimName,
altExpName = "featureSubset",
dim1 = NULL,
dim2 = NULL,
size = 0.5,
xlab = NULL,
ylab = NULL,
specificClusters = NULL,
labelClusters = FALSE,
groupBy = NULL,
labelSize = 3.5) {
standardGeneric("plotDimReduceCluster")
})
#' @rdname plotDimReduceCluster
#' @examples
#' data(sceCeldaCG)
#' sce <- celdaTsne(sceCeldaCG)
#' plotDimReduceCluster(x = sce,
#' reducedDimName = "celda_tSNE",
#' specificClusters = c(1, 2, 3))
#' @export
setMethod("plotDimReduceCluster",
signature(x = "SingleCellExperiment"),
function(x,
reducedDimName,
altExpName = "featureSubset",
dim1 = 1,
dim2 = 2,
size = 0.5,
xlab = NULL,
ylab = NULL,
specificClusters = NULL,
labelClusters = FALSE,
groupBy = NULL,
labelSize = 3.5) {
altExp <- SingleCellExperiment::altExp(x, altExpName)
if (!("celda_cell_cluster" %in%
colnames(SummarizedExperiment::colData(altExp)))) {
stop("Must have column 'celda_cell_cluster' in",
" colData(altExp(x, altExpName))!")
}
cluster <-
SummarizedExperiment::colData(altExp)[["celda_cell_cluster"]]
reddim <- .processReducedDim(
x = altExp,
reducedDimName = reducedDimName,
dim1 = dim1,
dim2 = dim2,
xlab = xlab,
ylab = ylab