forked from satijalab/seurat
-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathplotting.old
3214 lines (3178 loc) · 99 KB
/
plotting.old
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
#' @include seurat.R
NULL
globalVariables(names = c('cell', 'gene'), package = 'Seurat', add = TRUE)
#' Gene expression heatmap
#'
#' Draws a heatmap of single cell gene expression using ggplot2.
#'
#' @param object Seurat object
#' @param data.use Option to pass in data to use in the heatmap. Default will pick from either
#' object@@data or object@@scale.data depending on use.scaled parameter. Should have cells as columns
#' and genes as rows.
#' @param use.scaled Whether to use the data or scaled data if data.use is NULL
#' @param cells.use Cells to include in the heatmap (default is all cells)
#' @param genes.use Genes to include in the heatmap (ordered)
#' @param disp.min Minimum display value (all values below are clipped)
#' @param disp.max Maximum display value (all values above are clipped)
#' @param group.by Groups cells by this variable. Default is object@@ident
#' @param group.order Order of groups from left to right in heatmap.
#' @param draw.line Draw vertical lines delineating different groups
#' @param col.low Color for lowest expression value
#' @param col.mid Color for mid expression value
#' @param col.high Color for highest expression value
#' @param slim.col.label display only the identity class name once for each group
#' @param remove.key Removes the color key from the plot.
#' @param rotate.key Rotate color scale horizantally
#' @param title Title for plot
#' @param cex.col Controls size of column labels (cells)
#' @param cex.row Controls size of row labels (genes)
#' @param group.label.loc Place group labels on bottom or top of plot.
#' @param group.label.rot Whether to rotate the group label.
#' @param group.cex Size of group label text
#' @param group.spacing Controls amount of space between columns.
#' @param assay.type to plot heatmap for (default is RNA)
#' @param do.plot Whether to display the plot.
#'
#' @return Returns a ggplot2 plot object
#'
#' @importFrom dplyr %>%
#' @importFrom reshape2 melt
#'
#' @export
#'
#' @examples
#' DoHeatmap(object = pbmc_small)
#'
DoHeatmap <- function(
object,
data.use = NULL,
use.scaled = TRUE,
cells.use = NULL,
genes.use = NULL,
disp.min = -2.5,
disp.max = 2.5,
group.by = "ident",
group.order = NULL,
draw.line = TRUE,
col.low = "#FF00FF",
col.mid = "#000000",
col.high = "#FFFF00",
slim.col.label = FALSE,
remove.key = FALSE,
rotate.key = FALSE,
title = NULL,
cex.col = 10,
cex.row = 10,
group.label.loc = "bottom",
group.label.rot = FALSE,
group.cex = 15,
group.spacing = 0.15,
assay.type = "RNA",
do.plot = TRUE
) {
if (is.null(x = data.use)) {
if (use.scaled) {
data.use <- GetAssayData(object,assay.type = assay.type,slot = "scale.data")
} else {
data.use <- GetAssayData(object,assay.type = assay.type,slot = "data")
}
}
cells.use <- SetIfNull(x = cells.use, default = [email protected])
cells.use <- intersect(x = cells.use, y = colnames(x = data.use))
if (length(x = cells.use) == 0) {
stop("No cells given to cells.use present in object")
}
genes.use <- SetIfNull(x = genes.use, default = rownames(x = data.use))
genes.use <- intersect(x = genes.use, y = rownames(x = data.use))
if (length(x = genes.use) == 0) {
stop("No genes given to genes.use present in object")
}
if (is.null(x = group.by) || group.by == "ident") {
cells.ident <- object@ident[cells.use]
} else {
cells.ident <- factor(x = FetchData(
object = object,
cells.use = cells.use,
vars.all = group.by
)[, 1])
names(x = cells.ident) <- cells.use
}
cells.ident <- factor(
x = cells.ident,
labels = intersect(x = levels(x = cells.ident), y = cells.ident)
)
data.use <- data.use[genes.use, cells.use, drop = FALSE]
if (!use.scaled) {
data.use <- as.matrix(x = data.use)
disp.max <- ifelse(test = disp.max == 2.5, yes = 10, no = disp.max)
}
data.use <- MinMax(data = data.use, min = disp.min, max = disp.max)
data.use <- as.data.frame(x = t(x = data.use))
data.use$cell <- rownames(x = data.use)
colnames(x = data.use) <- make.unique(names = colnames(x = data.use))
data.use %>% melt(id.vars = "cell") -> data.use
names(x = data.use)[names(x = data.use) == 'variable'] <- 'gene'
names(x = data.use)[names(x = data.use) == 'value'] <- 'expression'
data.use$ident <- cells.ident[data.use$cell]
if (!is.null(x = group.order)) {
if (length(group.order) == length(levels(data.use$ident)) && all(group.order %in% levels(data.use$ident))) {
data.use$ident <- factor(data.use$ident, levels = group.order)
}
else {
stop("Invalid group.order")
}
}
data.use$gene <- with(
data = data.use,
expr = factor(x = gene, levels = rev(x = unique(x = data.use$gene)))
)
data.use$cell <- with(
data = data.use,
expr = factor(x = cell, levels = cells.use)
)
if (rotate.key) {
key.direction <- "horizontal"
key.title.pos <- "top"
} else {
key.direction <- "vertical"
key.title.pos <- "left"
}
heatmap <- ggplot(
data = data.use,
mapping = aes(x = cell, y = gene, fill = expression)
) +
geom_tile() +
scale_fill_gradient2(
low = col.low,
mid = col.mid,
high = col.high,
name = "Expression",
guide = guide_colorbar(
direction = key.direction,
title.position = key.title.pos
)
) +
scale_y_discrete(position = "right", labels = rev(genes.use)) +
theme(
axis.line = element_blank(),
axis.title.y = element_blank(),
axis.ticks.y = element_blank(),
strip.text.x = element_text(size = group.cex),
axis.text.y = element_text(size = cex.row),
axis.text.x = element_text(size = cex.col),
axis.title.x = element_blank()
)
if (slim.col.label) {
heatmap <- heatmap +
theme(
axis.title.x = element_blank(),
axis.text.x = element_blank(),
axis.ticks.x = element_blank(),
axis.line = element_blank(),
axis.title.y = element_blank(),
axis.ticks.y = element_blank()
)
} else {
heatmap <- heatmap + theme(axis.text.x = element_text(angle = 90))
}
if (!is.null(x = group.by)) {
if (group.label.loc == "top") {
switch <- NULL
} else {
switch <- 'x'
}
heatmap <- heatmap +
facet_grid(
facets = ~ident,
drop = TRUE,
space = "free",
scales = "free",
switch = switch
) +
scale_x_discrete(expand = c(0, 0), drop = TRUE)
if (draw.line) {
panel.spacing <- unit(x = group.spacing, units = 'lines')
} else {
panel.spacing <- unit(x = 0, units = 'lines')
}
heatmap <- heatmap +
theme(strip.background = element_blank(), panel.spacing = panel.spacing)
if (group.label.rot) {
heatmap <- heatmap + theme(strip.text.x = element_text(angle = 90))
}
}
if (remove.key) {
heatmap <- heatmap + theme(legend.position = "none")
}
if (!is.null(x = title)) {
heatmap <- heatmap + labs(title = title)
}
return(heatmap)
}
#' Single cell violin plot
#'
#' Draws a violin plot of single cell data (gene expression, metrics, PC
#' scores, etc.)
#'
#' @param object Seurat object
#' @param features.plot Features to plot (gene expression, metrics, PC scores,
#' anything that can be retreived by FetchData)
#' @param ident.include Which classes to include in the plot (default is all)
#' @param nCol Number of columns if multiple plots are displayed
#' @param do.sort Sort identity classes (on the x-axis) by the average
#' expression of the attribute being potted
#' @param y.max Maximum y axis value
#' @param same.y.lims Set all the y-axis limits to the same values
#' @param size.x.use X axis title font size
#' @param size.y.use Y axis title font size
#' @param size.title.use Main title font size
#' @param adjust.use Adjust parameter for geom_violin
#' @param point.size.use Point size for geom_violin
#' @param cols.use Colors to use for plotting
#' @param group.by Group (color) cells in different ways (for example, orig.ident)
#' @param y.log plot Y axis on log scale
#' @param x.lab.rot Rotate x-axis labels
#' @param y.lab.rot Rotate y-axis labels
#' @param legend.position Position the legend for the plot
#' @param single.legend Consolidate legend the legend for all plots
#' @param remove.legend Remove the legend from the plot
#' @param do.return Return a ggplot2 object (default : FALSE)
#' @param return.plotlist Return the list of individual plots instead of compiled plot.
#' @param \dots additional parameters to pass to FetchData (for example, use.imputed, use.scaled, use.raw)
#'
#' @import ggplot2
#' @importFrom cowplot plot_grid get_legend
#'
#' @return By default, no return, only graphical output. If do.return=TRUE,
#' returns a list of ggplot objects.
#'
#' @export
#'
#' @examples
#' VlnPlot(object = pbmc_small, features.plot = 'PC1')
#'
VlnPlot <- function(
object,
features.plot,
ident.include = NULL,
nCol = NULL,
do.sort = FALSE,
y.max = NULL,
same.y.lims = FALSE,
size.x.use = 16,
size.y.use = 16,
size.title.use = 20,
adjust.use = 1,
point.size.use = 1,
cols.use = NULL,
group.by = NULL,
y.log = FALSE,
x.lab.rot = FALSE,
y.lab.rot = FALSE,
legend.position = "right",
single.legend = TRUE,
remove.legend = FALSE,
do.return = FALSE,
return.plotlist = FALSE,
...
) {
if (is.null(x = nCol)) {
if (length(x = features.plot) > 9) {
nCol <- 4
} else {
nCol <- min(length(x = features.plot), 3)
}
}
data.use <- data.frame(FetchData(object = object, vars.all = features.plot, ...), check.names = F)
if (is.null(x = ident.include)) {
cells.to.include <- [email protected]
} else {
cells.to.include <- WhichCells(object = object, ident = ident.include)
}
data.use <- data.use[cells.to.include, ,drop = FALSE]
if (!is.null(x = group.by)) {
ident.use <- as.factor(x = FetchData(
object = object,
vars.all = group.by
)[cells.to.include, 1])
} else {
ident.use <- object@ident[cells.to.include]
}
gene.names <- colnames(x = data.use)[colnames(x = data.use) %in% rownames(x = object@data)]
if (single.legend) {
remove.legend <- TRUE
}
if (same.y.lims && is.null(x = y.max)) {
y.max <- max(data.use)
}
plots <- lapply(
X = features.plot,
FUN = function(x) {
return(SingleVlnPlot(
feature = x,
data = data.use[, x, drop = FALSE],
cell.ident = ident.use,
do.sort = do.sort, y.max = y.max,
size.x.use = size.x.use,
size.y.use = size.y.use,
size.title.use = size.title.use,
adjust.use = adjust.use,
point.size.use = point.size.use,
cols.use = cols.use,
gene.names = gene.names,
y.log = y.log,
x.lab.rot = x.lab.rot,
y.lab.rot = y.lab.rot,
legend.position = legend.position,
remove.legend = remove.legend
))
}
)
if (length(x = features.plot) > 1) {
plots.combined <- plot_grid(plotlist = plots, ncol = nCol)
if (single.legend && !remove.legend) {
legend <- get_legend(
plot = plots[[1]] + theme(legend.position = legend.position)
)
if (legend.position == "bottom") {
plots.combined <- plot_grid(
plots.combined,
legend,
ncol = 1,
rel_heights = c(1, .2)
)
} else if (legend.position == "right") {
plots.combined <- plot_grid(
plots.combined,
legend,
rel_widths = c(3, .3)
)
} else {
warning("Shared legends must be at the bottom or right of the plot")
}
}
} else {
plots.combined <- plots[[1]]
}
if (do.return) {
if (return.plotlist) {
return(plots)
} else {
return(plots.combined)
}
} else {
if (length(x = plots.combined) > 1) {
plots.combined
}
else {
invisible(x = lapply(X = plots.combined, FUN = print))
}
}
}
#' Single cell ridge plot
#'
#' Draws a ridge plot of single cell data (gene expression, metrics, PC
#' scores, etc.)
#'
#' @param object Seurat object
#' @param features.plot Features to plot (gene expression, metrics, PC scores,
#' anything that can be retreived by FetchData)
#' @param ident.include Which classes to include in the plot (default is all)
#' @param nCol Number of columns if multiple plots are displayed
#' @param do.sort Sort identity classes (on the x-axis) by the average
#' expression of the attribute being potted
#' @param y.max Maximum y axis value
#' @param same.y.lims Set all the y-axis limits to the same values
#' @param size.x.use X axis title font size
#' @param size.y.use Y axis title font size
#' @param size.title.use Main title font size
#' @param cols.use Colors to use for plotting
#' @param group.by Group (color) cells in different ways (for example, orig.ident)
#' @param y.log plot Y axis on log scale
#' @param x.lab.rot Rotate x-axis labels
#' @param y.lab.rot Rotate y-axis labels
#' @param legend.position Position the legend for the plot
#' @param single.legend Consolidate legend the legend for all plots
#' @param remove.legend Remove the legend from the plot
#' @param do.return Return a ggplot2 object (default : FALSE)
#' @param return.plotlist Return the list of individual plots instead of compiled plot.
#' @param \dots additional parameters to pass to FetchData (for example, use.imputed, use.scaled, use.raw)
#'
#' @import ggplot2
#' @importFrom cowplot get_legend plot_grid
#' @importFrom ggridges geom_density_ridges theme_ridges
#'
#' @return By default, no return, only graphical output. If do.return=TRUE,
#' returns a list of ggplot objects.
#'
#' @export
#'
#' @examples
#' RidgePlot(object = pbmc_small, features.plot = 'PC1')
#'
RidgePlot <- function(
object,
features.plot,
ident.include = NULL,
nCol = NULL,
do.sort = FALSE,
y.max = NULL,
same.y.lims = FALSE,
size.x.use = 16,
size.y.use = 16,
size.title.use = 20,
cols.use = NULL,
group.by = NULL,
y.log = FALSE,
x.lab.rot = FALSE,
y.lab.rot = FALSE,
legend.position = "right",
single.legend = TRUE,
remove.legend = FALSE,
do.return = FALSE,
return.plotlist = FALSE,
...
) {
if (is.null(x = nCol)) {
if (length(x = features.plot) > 9) {
nCol <- 4
} else {
nCol <- min(length(x = features.plot), 3)
}
}
data.use <- data.frame(
FetchData(
object = object,
vars.all = features.plot,
...
),
check.names = F
)
if (is.null(x = ident.include)) {
cells.to.include <- [email protected]
} else {
cells.to.include <- WhichCells(object = object, ident = ident.include)
}
data.use <- data.use[cells.to.include, ,drop = FALSE]
if (!is.null(x = group.by)) {
ident.use <- as.factor(x = FetchData(
object = object,
vars.all = group.by
)[cells.to.include, 1])
} else {
ident.use <- object@ident[cells.to.include]
}
gene.names <- colnames(x = data.use)[colnames(x = data.use) %in% rownames(x = object@data)]
if (single.legend) {
remove.legend <- TRUE
}
if (same.y.lims && is.null(x = y.max)) {
y.max <- max(data.use)
}
plots <- lapply(
X = features.plot,
FUN = function(x) {
return(SingleRidgePlot(
feature = x,
data = data.use[, x, drop = FALSE],
cell.ident = ident.use,
do.sort = do.sort, y.max = y.max,
size.x.use = size.x.use,
size.y.use = size.y.use,
size.title.use = size.title.use,
cols.use = cols.use,
gene.names = gene.names,
y.log = y.log,
x.lab.rot = x.lab.rot,
y.lab.rot = y.lab.rot,
legend.position = legend.position,
remove.legend = remove.legend
))
}
)
if (length(x = features.plot) > 1) {
plots.combined <- plot_grid(plotlist = plots, ncol = nCol)
if (single.legend && !remove.legend) {
legend <- get_legend(
plot = plots[[1]] + theme(legend.position = legend.position)
)
if (legend.position == "bottom") {
plots.combined <- plot_grid(
plots.combined,
legend,
ncol = 1,
rel_heights = c(1, .2)
)
} else if (legend.position == "right") {
plots.combined <- plot_grid(
plots.combined,
legend,
rel_widths = c(3, .3)
)
} else {
warning("Shared legends must be at the bottom or right of the plot")
}
}
} else {
plots.combined <- plots[[1]]
}
if (do.return) {
if (return.plotlist) {
return(plots)
} else {
return(plots.combined)
}
} else {
if (length(x = plots.combined) > 1) {
plots.combined
}
else {
invisible(x = lapply(X = plots.combined, FUN = print))
}
}
}
#' Old Dot plot visualization (pre-ggplot implementation)
#
#' Intuitive way of visualizing how gene expression changes across different identity classes (clusters).
#' The size of the dot encodes the percentage of cells within a class, while the color encodes the
#' AverageExpression level of 'expressing' cells (green is high).
#'
#' @param object Seurat object
#' @param genes.plot Input vector of genes
#' @param cex.use Scaling factor for the dots (scales all dot sizes)
#' @param cols.use colors to plot
#' @param thresh.col The raw data value which corresponds to a red dot (lowest expression)
#' @param dot.min The fraction of cells at which to draw the smallest dot (default is 0.05)
#' @param group.by Factor to group the cells by
#'
#' @return Only graphical output
#'
#' @importFrom graphics axis plot
#'
#' @export
#'
#' @examples
#' cd_genes <- c("CD247", "CD3E", "CD9")
#' DotPlotOld(object = pbmc_small, genes.plot = cd_genes)
#'
DotPlotOld <- function(
object,
genes.plot,
cex.use = 2,
cols.use = NULL,
thresh.col = 2.5,
dot.min = 0.05,
group.by = NULL
) {
if (! is.null(x = group.by)) {
object <- SetAllIdent(object = object, id = group.by)
}
#object@data=object@data[genes.plot,]
object@data <- data.frame(t(x = FetchData(object = object, vars.all = genes.plot)))
#this line is in case there is a '-' in the cell name
colnames(x = object@data) <- [email protected]
avg.exp <- AverageExpression(object = object)
avg.alpha <- AverageDetectionRate(object = object)
cols.use <- SetIfNull(x = cols.use, default = CustomPalette(low = "red", high = "green"))
exp.scale <- t(x = scale(x = t(x = avg.exp)))
exp.scale <- MinMax(data = exp.scale, max = thresh.col, min = (-1) * thresh.col)
n.col <- length(x = cols.use)
data.y <- rep(x = 1:ncol(x = avg.exp), nrow(x = avg.exp))
data.x <- unlist(x = lapply(X = 1:nrow(x = avg.exp), FUN = rep, ncol(x = avg.exp)))
data.avg <- unlist(x = lapply(
X = 1:length(x = data.y),
FUN = function(x) {
return(exp.scale[data.x[x], data.y[x]])
}
))
exp.col <- cols.use[floor(
x = n.col * (data.avg + thresh.col) / (2 * thresh.col) + .5
)]
data.cex <- unlist(x = lapply(
X = 1:length(x = data.y),
FUN = function(x) {
return(avg.alpha[data.x[x], data.y[x]])
}
)) * cex.use + dot.min
plot(
x = data.x,
y = data.y,
cex = data.cex,
pch = 16,
col = exp.col,
xaxt = "n",
xlab = "",
ylab = "",
yaxt = "n"
)
axis(side = 1, at = 1:length(x = genes.plot), labels = genes.plot)
axis(side = 2, at = 1:ncol(x = avg.alpha), colnames(x = avg.alpha), las = 1)
}
globalVariables(
names = c('cell', 'id', 'avg.exp', 'avg.exp.scale', 'pct.exp'),
package = 'Seurat',
add = TRUE
)
#' Dot plot visualization
#'
#' Intuitive way of visualizing how gene expression changes across different
#' identity classes (clusters). The size of the dot encodes the percentage of
#' cells within a class, while the color encodes the AverageExpression level of
#' cells within a class (blue is high).
#'
#' @param object Seurat object
#' @param genes.plot Input vector of genes
#' @param cols.use Colors to plot, can pass a single character giving the name of
#' a palette from \code{RColorBrewer::brewer.pal.info}
#' @param col.min Minimum scaled average expression threshold (everything smaller
#' will be set to this)
#' @param col.max Maximum scaled average expression threshold (everything larger
#' will be set to this)
#' @param dot.min The fraction of cells at which to draw the smallest dot
#' (default is 0). All cell groups with less than this expressing the given
#' gene will have no dot drawn.
#' @param dot.scale Scale the size of the points, similar to cex
#' @param scale.by Scale the size of the points by 'size' or by 'radius'
#' @param scale.min Set lower limit for scaling, use NA for default
#' @param scale.max Set upper limit for scaling, use NA for default
#' @param group.by Factor to group the cells by
#' @param plot.legend plots the legends
#' @param x.lab.rot Rotate x-axis labels
#' @param do.return Return ggplot2 object
#'
#' @return default, no return, only graphical output. If do.return=TRUE, returns a ggplot2 object
#'
#' @importFrom tidyr gather
#' @importFrom dplyr %>% group_by summarize_each mutate ungroup
#'
#' @export
#' @seealso \code{RColorBrewer::brewer.pal.info}
#'
#' @examples
#' cd_genes <- c("CD247", "CD3E", "CD9")
#' DotPlot(object = pbmc_small, genes.plot = cd_genes)
#'
DotPlot <- function(
object,
genes.plot,
cols.use = c("lightgrey", "blue"),
col.min = -2.5,
col.max = 2.5,
dot.min = 0,
dot.scale = 6,
scale.by = 'radius',
scale.min = NA,
scale.max = NA,
group.by,
plot.legend = FALSE,
do.return = FALSE,
x.lab.rot = FALSE
) {
scale.func <- switch(
EXPR = scale.by,
'size' = scale_size,
'radius' = scale_radius,
stop("'scale.by' must be either 'size' or 'radius'")
)
if (!missing(x = group.by)) {
object <- SetAllIdent(object = object, id = group.by)
}
data.to.plot <- data.frame(FetchData(object = object, vars.all = genes.plot))
colnames(x = data.to.plot) <- genes.plot
data.to.plot$cell <- rownames(x = data.to.plot)
data.to.plot$id <- object@ident
data.to.plot %>% gather(
key = genes.plot,
value = expression,
-c(cell, id)
) -> data.to.plot
data.to.plot %>%
group_by(id, genes.plot) %>%
summarize(
avg.exp = mean(expm1(x = expression)),
pct.exp = PercentAbove(x = expression, threshold = 0)
) -> data.to.plot
data.to.plot %>%
ungroup() %>%
group_by(genes.plot) %>%
mutate(avg.exp.scale = scale(x = avg.exp)) %>%
mutate(avg.exp.scale = MinMax(
data = avg.exp.scale,
max = col.max,
min = col.min
)) -> data.to.plot
data.to.plot$genes.plot <- factor(
x = data.to.plot$genes.plot,
levels = rev(x = genes.plot)
)
# data.to.plot$genes.plot <- factor(
# x = data.to.plot$genes.plot,
# levels = rev(x = sub(pattern = "-", replacement = ".", x = genes.plot))
# )
data.to.plot$pct.exp[data.to.plot$pct.exp < dot.min] <- NA
data.to.plot$pct.exp <- data.to.plot$pct.exp * 100
p <- ggplot(data = data.to.plot, mapping = aes(x = genes.plot, y = id)) +
geom_point(mapping = aes(size = pct.exp, color = avg.exp.scale)) +
scale.func(range = c(0, dot.scale), limits = c(scale.min, scale.max)) +
theme(axis.title.x = element_blank(), axis.title.y = element_blank())
if (length(x = cols.use) == 1) {
p <- p + scale_color_distiller(palette = cols.use)
} else {
p <- p + scale_color_gradient(low = cols.use[1], high = cols.use[2])
}
if (!plot.legend) {
p <- p + theme(legend.position = "none")
}
if (x.lab.rot) {
p <- p + theme(axis.text.x = element_text(angle = 90, vjust = 0.5))
}
suppressWarnings(print(p))
if (do.return) {
return(p)
}
}
globalVariables(
names = c('cell', 'id', 'avg.exp', 'pct.exp', 'ptcolor', 'ident2'),
package = 'Seurat',
add = TRUE
)
#' Split Dot plot visualization
#'
#' Intuitive way of visualizing how gene expression changes across different identity classes (clusters).
#' The size of the dot encodes the percentage of cells within a class, while the color encodes the
#' AverageExpression level of 'expressing' cells. Splits the cells into groups based on a
#' grouping variable.
#' Still in BETA
#'
#' @param object Seurat object
#' @param grouping.var Grouping variable for splitting the dataset
#' @param genes.plot Input vector of genes
#' @param cols.use colors to plot
#' @param col.min Minimum scaled average expression threshold (everything smaller will be set to this)
#' @param col.max Maximum scaled average expression threshold (everything larger will be set to this)
#' @param dot.min The fraction of cells at which to draw the smallest dot (default is 0.05).
#' @param dot.scale Scale the size of the points, similar to cex
#' @param group.by Factor to group the cells by
#' @param plot.legend plots the legends
#' @param x.lab.rot Rotate x-axis labels
#' @param do.return Return ggplot2 object
#' @param gene.groups Add labeling bars to the top of the plot
#'
#' @return default, no return, only graphical output. If do.return=TRUE, returns a ggplot2 object
#'
#' @importFrom grDevices colorRampPalette
#' @importFrom tidyr gather separate unite
#' @importFrom dplyr %>% group_by summarize_each mutate ungroup rowwise
#'
#' @export
#'
#' @examples
#' # Create a simulated grouping variable
#' [email protected]$groups <- sample(
#' x = c("g1", "g2"),
#' size = length(x = [email protected]),
#' replace = TRUE
#' )
#' SplitDotPlotGG(pbmc_small, grouping.var = "groups", genes.plot = [email protected][1:5])
#'
SplitDotPlotGG <- function(
object,
grouping.var,
genes.plot,
gene.groups,
cols.use = c("blue", "red"),
col.min = -2.5,
col.max = 2.5,
dot.min = 0,
dot.scale = 6,
group.by,
plot.legend = FALSE,
do.return = FALSE,
x.lab.rot = FALSE
) {
if (!missing(x = group.by)) {
object <- SetAllIdent(object = object, id = group.by)
}
grouping.data <- FetchData(
object = object,
vars.all = grouping.var
)[names(x = object@ident), 1]
ncolor <- length(x = cols.use)
ngroups <- length(x = unique(x = grouping.data))
if (ncolor < ngroups) {
stop(
paste(
"Not enough colors supplied for number of grouping variables. Need",
ngroups,
"got",
ncolor,
"colors"
)
)
} else if (ncolor > ngroups) {
cols.use <- cols.use[1:ngroups]
}
idents.old <- levels(x = object@ident)
idents.new <- paste(object@ident, grouping.data, sep = "_")
colorlist <- cols.use
names(x = colorlist) <- levels(x = grouping.data)
object@ident <- factor(
x = idents.new,
levels = unlist(x = lapply(
X = idents.old,
FUN = function(x) {
lvls <- list()
for (i in seq_along(along.with = levels(x = grouping.data))) {
lvls[[i]] <- paste(x, levels(x = grouping.data)[i], sep = "_")
}
return(unlist(x = lvls))
}
)),
ordered = TRUE
)
data.to.plot <- data.frame(FetchData(object = object, vars.all = genes.plot))
data.to.plot$cell <- rownames(x = data.to.plot)
data.to.plot$id <- object@ident
data.to.plot %>%
gather(key = genes.plot, value = expression, -c(cell, id)) -> data.to.plot
data.to.plot %>%
group_by(id, genes.plot) %>%
summarize(
avg.exp = ExpMean(x = expression),
pct.exp = PercentAbove(x = expression, threshold = 0)
) -> data.to.plot
data.to.plot %>%
ungroup() %>%
group_by(genes.plot) %>%
mutate(avg.exp = scale(x = avg.exp)) %>%
mutate(avg.exp.scale = as.numeric(x = cut(
x = MinMax(data = avg.exp, max = col.max, min = col.min),
breaks = 20
))) -> data.to.plot
data.to.plot %>%
separate(col = id, into = c('ident1', 'ident2'), sep = "_") %>%
rowwise() %>%
mutate(
palette.use = colorlist[[ident2]],
ptcolor = colorRampPalette(colors = c("grey", palette.use))(20)[avg.exp.scale]
) %>%
unite('id', c('ident1', 'ident2'), sep = '_') -> data.to.plot
data.to.plot$genes.plot <- factor(
x = data.to.plot$genes.plot,
levels = rev(x = sub(pattern = "-", replacement = ".", x = genes.plot))
)
data.to.plot$pct.exp[data.to.plot$pct.exp < dot.min] <- NA
data.to.plot$id <- factor(x = data.to.plot$id, levels = levels(object@ident))
palette.use <- unique(x = data.to.plot$palette.use)
if (!missing(x = gene.groups)) {
names(x = gene.groups) <- genes.plot
data.to.plot %>%
mutate(gene.groups = gene.groups[genes.plot]) -> data.to.plot
}
data.to.plot$pct.exp <- data.to.plot$pct.exp * 100
p <- ggplot(data = data.to.plot, mapping = aes(x = genes.plot, y = id)) +
geom_point(mapping = aes(size = pct.exp, color = ptcolor)) +
scale_radius(range = c(0, dot.scale)) +
scale_color_identity() +
theme(axis.title.x = element_blank(), axis.title.y = element_blank())
if (!missing(x = gene.groups)) {
p <- p +
facet_grid(
facets = ~gene.groups,
scales = "free_x",
space = "free_x",
switch = "y"
) +
theme(
panel.spacing = unit(x = 1, units = "lines"),
strip.background = element_blank(),
strip.placement = "outside"
)
}
if (x.lab.rot) {
p <- p + theme(axis.text.x = element_text(angle = 90, vjust = 0.5))
}
if (!plot.legend) {
p <- p + theme(legend.position = "none")
} else if (plot.legend) {
# Get legend from plot
plot.legend <- cowplot::get_legend(plot = p)
# Get gradient legends from both palettes
palettes <- list()
for (i in seq_along(along.with = colorlist)) {
palettes[[names(colorlist[i])]] <- colorRampPalette(colors = c("grey", colorlist[[i]]))(20)
}
gradient.legends <- mapply(
FUN = GetGradientLegend,
palette = palettes,
group = names(x = palettes),
SIMPLIFY = FALSE,
USE.NAMES = FALSE
)
# Remove legend from p
p <- p + theme(legend.position = "none")
# Arrange legends using plot_grid
legends <- cowplot::plot_grid(
plotlist = gradient.legends,
plot.legend,
ncol = 1,
rel_heights = c(1, rep.int(x = 0.5, times = length(x = gradient.legends))),
scale = rep(0.5, length(gradient.legends)), align = "hv"
)
# Arrange plot and legends using plot_grid
p <- cowplot::plot_grid(
p, legends,
ncol = 2,
rel_widths = c(1, 0.3),
scale = c(1, 0.8)
)
}
suppressWarnings(print(p))
if (do.return) {
return(p)
}
}
#' Visualize 'features' on a dimensional reduction plot
#'
#' Colors single cells on a dimensional reduction plot according to a 'feature'
#' (i.e. gene expression, PC scores, number of genes detected, etc.)
#'
#' @param object Seurat object
#' @param features.plot Vector of features to plot
#' @param min.cutoff Vector of minimum cutoff values for each feature, may specify quantile in the form of 'q##' where '##' is the quantile (eg, 1, 10)
#' @param max.cutoff Vector of maximum cutoff values for each feature, may specify quantile in the form of 'q##' where '##' is the quantile (eg, 1, 10)
#' @param dim.1 Dimension for x-axis (default 1)
#' @param dim.2 Dimension for y-axis (default 2)
#' @param cells.use Vector of cells to plot (default is all cells)
#' @param pt.size Adjust point size for plotting
#' @param cols.use The two colors to form the gradient over. Provide as string vector with
#' the first color corresponding to low values, the second to high. Also accepts a Brewer
#' color scale or vector of colors. Note: this will bin the data into number of colors provided.
#' @param pch.use Pch for plotting
#' @param overlay Plot two features overlayed one on top of the other
#' @param do.hover Enable hovering over points to view information
#' @param data.hover Data to add to the hover, pass a character vector of features to add. Defaults to cell name and identity. Pass 'NULL' to remove extra data.
#' @param do.identify Opens a locator session to identify clusters of cells
#' @param reduction.use Which dimensionality reduction to use. Default is
#' "tsne", can also be "pca", or "ica", assuming these are precomputed.
#' @param use.imputed Use imputed values for gene expression (default is FALSE)
#' @param nCol Number of columns to use when plotting multiple features.
#' @param no.axes Remove axis labels
#' @param no.legend Remove legend from the graph. Default is TRUE.
#' @param coord.fixed Use a fixed scale coordinate system (for spatial coordinates). Default is FALSE.
#' @param dark.theme Plot in a dark theme
#' @param do.return return the ggplot2 object
#' @param vector.friendly FALSE by default. If TRUE, points are flattened into a PNG, while axes/labels retain full vector resolution. Useful for producing AI-friendly plots with large numbers of cells.
#' @param png.file Use specific name for temporary png file
#' @param png.arguments Set width, height, and DPI for ggsave
#'
#' @importFrom RColorBrewer brewer.pal.info
#'
#' @return No return value, only a graphical output
#'
#' @export
#'
#' @examples
#' FeaturePlot(object = pbmc_small, features.plot = 'PC1')
#'
FeaturePlot <- function(
object,
features.plot,
min.cutoff = NA,
max.cutoff = NA,
dim.1 = 1,
dim.2 = 2,
cells.use = NULL,
pt.size = 1,
cols.use = c("yellow", "red"),
pch.use = 16,
overlay = FALSE,
do.hover = FALSE,
data.hover = 'ident',
do.identify = FALSE,
reduction.use = "tsne",