forked from satijalab/seurat
-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathplotting_internal.R
1640 lines (1617 loc) · 46.4 KB
/
plotting_internal.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
# Create a scatterplot with data from a ggplot2 scatterplot
#
# @param plot.data The original ggplot2 scatterplot data
# This is taken from ggplot2::ggplot_build
# @param dark.theme Plot using a dark theme
# @param smooth Use a smooth scatterplot instead of a standard scatterplot
# @param ... Extra parameters passed to graphics::plot or graphics::smoothScatter
#
#' @importFrom graphics axis plot smoothScatter
#
PlotBuild <- function(plot.data, dark.theme = FALSE, smooth = FALSE, ...) {
# Do we use a smooth scatterplot?
# Take advantage of functions as first class objects
# to dynamically choose normal vs smooth scatterplot
if (smooth) {
myplot <- smoothScatter
} else {
myplot <- plot
}
if (dark.theme) {
par(bg = 'black')
axes = FALSE
col.lab = 'white'
} else {
axes = 'TRUE'
col.lab = 'black'
}
myplot(
plot.data[, c(1, 2)],
col = plot.data$color,
pch = plot.data$pch,
cex = vapply(
X = plot.data$cex,
FUN = function(x) {
return(max(x / 2, 0.5))
},
FUN.VALUE = numeric(1)
),
axes = axes,
col.lab = col.lab,
col.main = col.lab,
...
)
if (dark.theme) {
axis(
side = 1,
at = NULL,
labels = TRUE,
col.axis = col.lab,
col = col.lab
)
axis(
side = 2,
at = NULL,
labels = TRUE,
col.axis = col.lab,
col = col.lab
)
}
}
# Convert a ggplot2 scatterplot to base R graphics
#
# @param plot A ggplot2 scatterplot
# @param do.plot Create the plot with base R graphics
# @param ... Extra parameters passed to PlotBuild
#
# @return A dataframe with the data that created the ggplot2 scatterplot
#
GGpointToBase <- function(plot, do.plot = TRUE, ...) {
plot.build <- ggplot2::ggplot_build(plot = plot)
build.data <- plot.build$data[[1]]
plot.data <- build.data[, c('x', 'y', 'colour', 'shape', 'size')]
names(x = plot.data) <- c(
plot.build$plot$labels$x,
plot.build$plot$labels$y,
'color',
'pch',
'cex'
)
if (do.plot) {
PlotBuild(plot.data = plot.data, ...)
}
return(plot.data)
}
# Locate points on a plot and return them
#
# @param plot A ggplot2 plot
# @param recolor Do we recolor the plot to highlight selected points?
# @param dark.theme Plot using a dark theme
# @param ... Exptra parameters to PlotBuild
#
# @return A dataframe of x and y coordinates for points selected
#
#' @importFrom graphics locator
#
PointLocator <- function(plot, recolor=TRUE, dark.theme = FALSE, ...) {
# Convert the ggplot object to a data.frame
plot.data <- GGpointToBase(plot = plot, dark.theme = dark.theme, ...)
npoints <- nrow(x = plot.data)
cat("Click around the cluster of points you wish to select\n")
cat("ie. select the vertecies of a shape around the cluster you\n")
cat("are interested in. Press <Esc> when finished (right click for R-terminal users)\n\n")
polygon <- locator(n = npoints, type = 'l')
polygon <- data.frame(polygon)
# pnt.in.poly returns a data.frame of points
points.all <- SDMTools::pnt.in.poly(
pnts = plot.data[, c(1, 2)],
poly.pnts = polygon
)
# Find the located points
points.located <- points.all[which(x = points.all$pip == 1), ]
# If we're recoloring, do the recolor
if(recolor) {
if (dark.theme) {
no = 'white'
} else {
no = 'black'
}
points.all$color <- ifelse(test = points.all$pip == 1, yes = 'red', no = no)
plot.data$color <- points.all$color
PlotBuild(plot.data = plot.data, dark.theme = dark.theme, ...)
}
return(points.located[, c(1, 2)])
}
# Plot a single feature
#
# @param data.use The data regarding the feature
# @param feature The feature to plot
# @param data.plot The data to be plotted
# @param pt.size Size of each point
# @param pch.use Shape of each point
# @param cols.use Colors to plot
# @param dim.codes Codes for the dimensions to plot in
# @param min.cutoff Minimum cutoff for data
# @param max.cutoff Maximum cutoff for data
# @param coord.fixed Use a fixed scale coordinate system (for spatial coordinates)
# @param no.axes Remove axes from plot
# @param no.legend Remove legend from plot
# @param dark.theme Plot in dark theme
#
# @return A ggplot2 scatterplot
#
#' @importFrom stats na.omit
#' @importFrom utils globalVariables
#
globalVariables(names = c('x', 'y', 'gene'), package = 'Seurat', add = TRUE)
SingleFeaturePlot <- function(
data.use,
feature,
data.plot,
pt.size,
pch.use,
cols.use,
dim.codes,
min.cutoff,
max.cutoff,
coord.fixed,
no.axes,
no.title = FALSE,
no.legend,
dark.theme,
vector.friendly = FALSE,
png.file = NULL,
png.arguments=c(10,10,100)
) {
#first, consider vector friendly case
if (vector.friendly) {
previous_call <- blank_call <- png_call <- match.call()
blank_call$pt.size <- -1
blank_call$vector.friendly <- FALSE
png_call$no.axes <- TRUE
png_call$no.legend <- TRUE
png_call$vector.friendly <- FALSE
png_call$no.title <- TRUE
blank_plot <- eval(blank_call, sys.frame(sys.parent()))
png_plot <- eval(png_call, sys.frame(sys.parent()))
png.file <- SetIfNull(x = png.file, default = paste0(tempfile(), ".png"))
ggsave(filename = png.file, plot = png_plot,
width = png.arguments[1],
height = png.arguments[2],
dpi = png.arguments[3])
to_return <- AugmentPlot(blank_plot, png.file)
file.remove(png.file)
return(to_return)
}
data.gene <- na.omit(object = data.frame(data.use[feature, ]))
# Check for quantiles
min.cutoff <- SetQuantile(cutoff = min.cutoff, data = data.gene)
max.cutoff <- SetQuantile(cutoff = max.cutoff, data = data.gene)
# Mask any values below the minimum and above the maximum values
data.gene <- sapply(
X = data.gene,
FUN = function(x) {
return(ifelse(test = x < min.cutoff, yes = min.cutoff, no = x))
}
)
data.gene <- sapply(
X = data.gene,
FUN = function(x) {
return(ifelse(test = x > max.cutoff, yes = max.cutoff, no = x))
}
)
data.plot$gene <- data.gene
# Stuff for break points
if (length(x = cols.use) == 1) {
brewer.gran <- brewer.pal.info[cols.use, ]$maxcolors
} else {
brewer.gran <- length(x = cols.use)
}
# Cut points
if (all(data.gene == 0)) {
data.cut <- 0
} else {
data.cut <- as.numeric(x = as.factor(x = cut(
x = as.numeric(x = data.gene),
breaks = brewer.gran
)))
}
data.plot$col <- as.factor(x = data.cut)
# Start plotting
p <- ggplot(data = data.plot, mapping = aes(x = x, y = y))
if (brewer.gran != 2) {
if (length(x = cols.use) == 1) {
p <- p + geom_point(
mapping = aes(color = col),
size = pt.size,
shape = pch.use
) + scale_color_brewer(palette = cols.use)
} else {
p <- p + geom_point(
mapping = aes(color = col),
size = pt.size,
shape = pch.use
) + scale_color_manual(values = cols.use)
}
} else {
if (all(data.plot$gene == data.plot$gene[1])) {
warning(paste0("All cells have the same value of ", feature, "."))
p <- p + geom_point(color = cols.use[1], size = pt.size, shape = pch.use)
} else {
p <- p + geom_point(
mapping = aes(color = gene),
size = pt.size,
shape = pch.use
) + scale_color_gradientn(
colors = cols.use,
guide = guide_colorbar(title = feature)
)
}
}
if (dark.theme) {
p <- p + DarkTheme()
}
if (no.axes) {
p <- p + theme(
axis.line = element_blank(),
axis.text.x = element_blank(),
axis.text.y = element_blank(),
axis.ticks = element_blank(),
axis.title.x = element_blank(),
axis.title.y = element_blank()
)
if (!no.title) p <- p + labs(title = feature, x ="", y="")
if (no.title) p <- p + labs(x ="", y="")
} else {
if (no.title) p <- p + labs(x = dim.codes[1], y = dim.codes[2])
if (!(no.title)) p <- p + labs(title = feature, x = dim.codes[1], y = dim.codes[2])
}
if (no.legend) {
p <- p + theme(legend.position = 'none')
}
if(coord.fixed) {
p <- p + coord_fixed()
}
return(p)
}
# Blend two feature plots together
#
# @param data.use The data regarding the feature
# @param features.plot The features to plot
# @param data.plot The data to be plotted
# @param pt.size Size of each point
# @param pch.use Shape of each point
# @param cols.use Colors to plot
# @param dim.codes Codes for the dimensions to plot in
# @param min.cutoff Minimum cutoff for data
# @param max.cutoff Maximum cutoff for data
# @param coord.fixed Use a fixed scale coordinate system (for spatial coordinates)
# @param no.axes Remove axes from plot
# @param no.legend Remove legend from plot
# @param dark.theme Plot in dark theme
#
#' @import RColorBrewer
#' @importFrom grDevices colors
#' @importFrom utils globalVariables
#
# @return A blended ggplot2 scatterplot
#
globalVariables(names = c('x', 'y'), package = 'Seurat', add = TRUE)
BlendPlot <- function(
data.use,
features.plot,
data.plot,
pt.size,
pch.use,
cols.use,
dim.codes,
min.cutoff,
max.cutoff,
coord.fixed,
no.axes,
no.legend,
dark.theme
) {
num.cols <- length(x = cols.use)
# Create a vector of colors that weren't provided
cols.not.provided <- colors(distinct = TRUE)
cols.not.provided <- cols.not.provided[!(grepl(
pattern = paste(cols.use, collapse = '|'),
x = cols.not.provided,
ignore.case = TRUE
))]
if (num.cols > 4) {
# If provided more than four colors, take only the first four
cols.use <- cols.use[c(1:4)]
} else if ((num.cols == 2) || (num.cols == 3)) {
# If two or three colors, use the last two as high values for blending
# and add to our vector of colors
blend <- BlendColors(cols.use[c(num.cols - 1, num.cols)])
cols.use <- c(cols.use, blend)
if (num.cols == 2) {
# If two colors, provided,
# we still need a low color
cols.use <- c(sample(x = cols.not.provided, size = 1), cols.use)
}
} else if ((num.cols == 1)) {
# If only one color provided
if (cols.use %in% rownames(x = brewer.pal.info)) {
# Was it a palette from RColorBrewer? If so, create
# our colors based on the palette
palette <- brewer.pal(n = 3, name = cols.use)
cols.use <- c(palette, BlendColors(palette[c(2, 3)]))
} else {
# If not, randomly create our colors
cols.high <- sample(x = cols.not.provided, size = 2, replace = FALSE)
cols.use <- c(cols.use, cols.high, BlendColors(cols.high))
}
} else if (num.cols <= 0) {
cols.use <- c('yellow','red', 'blue', BlendColors('red', 'blue'))
}
names(x = cols.use) <- c('low', 'high1', 'high2', 'highboth')
length.check <- vapply(
X = list(features.plot, min.cutoff, max.cutoff),
FUN = function(x) {
return(length(x = x) != 2)
},
FUN.VALUE = logical(length = 1)
)
if (any(length.check)) {
stop("An overlayed FeaturePlot only works with two features and requires two minimum and maximum cutoffs")
}
# Check for quantiles
min.cutoff <- c(
SetQuantile(cutoff = min.cutoff[1], data = data.gene[features.plot[1], ]),
SetQuantile(cutoff = min.cutoff[2], data = data.gene[features.plot[2], ])
)
max.cutoff <- c(
SetQuantile(cutoff = max.cutoff[1], data = data.gene[features.plot[1], ]),
SetQuantile(cutoff = max.cutoff[2], data = data.gene[features.plot[2], ])
)
data.gene <- stats::na.omit(object = data.frame(data.use[features.plot, ]))
cell.names <- colnames(x = data.gene)
# Minimum and maximum masking
data.gene <- matrix(
data = vapply(
X = data.gene,
FUN = function(x) ifelse(test = x < min.cutoff, yes = min.cutoff, no = x),
FUN.VALUE = c(1, 1)
),
nrow = 2
)
data.gene <- matrix(
data = vapply(
X = as.data.frame(x = data.gene),
FUN = function(x) ifelse(test = x > max.cutoff, yes = max.cutoff, no = x),
FUN.VALUE = c(1, 1)
),
nrow = 2
)
data.gene <- as.data.frame(x = data.gene)
rownames(x = data.gene) <- features.plot
colnames(x = data.gene) <- cell.names
# Stuff for break points
if(all(data.gene ==0)) {
data.cut <- 0
} else {
# Cut the expression of both features
cuts <- apply(
X = data.gene,
MARGIN = 1,
FUN = cut,
breaks = 2,
labels = FALSE
)
cuts.dim <- dim(x = cuts)
if (cuts.dim[1] > cuts.dim[2]){
cuts <- t(x = cuts)
}
# Apply colors dependent on if the cell expresses
# none, one, or both features
data.cut = apply(
X = cuts,
MARGIN = 2,
FUN = function(x) {
return(if ((x[1] == 1) && (x[2] == 2)) { # Expression in 2
'high2'
} else if ((x[1] == 2) && (x[2] == 1)) { # Expression in 1
'high1'
} else if ((x[1] == 2) && (x[2] == 2)) { # Expression in both
'highboth'
} else { # Expression in neither
'low'
})
}
)
data.cut <- as.factor(x = data.cut)
}
data.plot$colors <- data.cut
# Start plotting
legend.names <- c(
'high1' = paste('High', features.plot[1]),
'high2' = paste('High', features.plot[2]),
'highboth' = 'High both'
)
title <- paste0(features.plot, collapse = ' x ')
p <- ggplot(data = data.plot, mapping = aes(x = x, y = y))
p <- p + geom_point(
mapping = aes(color = colors),
size = pt.size,
shape = pch.use
)
p <- p + scale_color_manual(
values = cols.use,
limits = c('high1', 'high2', 'highboth'),
labels = legend.names,
guide = guide_legend(title = NULL, override.aes = list(size = 2))
)
# Deal with axes and legends
if (no.axes) {
p <- p + labs(title = title, x ="", y="") + theme(
axis.line = element_blank(),
axis.text.x = element_blank(),
axis.text.y = element_blank(),
axis.ticks = element_blank(),
axis.title.x = element_blank(),
axis.title.y = element_blank()
)
} else {
p <- p + labs(title = title, x = dim.codes[1], y = dim.codes[2])
}
if (no.legend){
p <- p + theme(legend.position = 'none')
}
if (dark.theme) {
p <- p + DarkTheme()
}
if(coord.fixed) {
p <- p + coord_fixed()
}
return(p)
}
# Blend two or more colors together
#
# @param ... Two or more colors to blend together
# These can be in a vector or standalone
# @param as.rgb Return in RGB form, otherwise return in hexadecimal form
#
# @return The blended color in RGB form (1 x 3 matrix) or hexadecimal form
#
BlendColors <- function(..., as.rgb = FALSE) {
# Assemble the arguments passed into a character vector
colors <- as.character(x = c(...))
if (length(x = colors) < 2) {
stop("Please provide two or more colors to blend")
}
# Check for hexadecimal values for automatic alpha blending
alpha.value <- 255
if (sum(sapply(X = colors, FUN = grepl, pattern = '^#')) != 0) {
hex <- colors[which(x = grepl(pattern = '^#', x = colors))]
hex.length <- sapply(X = hex, FUN = nchar)
# 9-character hexadecimal values specify alpha levels
if (9 %in% hex.length) {
hex.alpha <- hex[which(x = hex.length == 9)]
hex.vals <- sapply(X = hex.alpha, FUN = substr, start = 8, stop = 9)
dec.vals <- sapply(X = hex.vals, FUN = strtoi, base = 16)
dec.vals <- dec.vals / 255 # Convert to 0:1 scale for calculations
alpha.value <- dec.vals[1]
# Blend alpha levels, going top-down
for (val in dec.vals[-1]) {
alpha.value <- alpha.value + (val * (1 - alpha.value))
}
alpha.value <- alpha.value * 255 # Convert back to 0:255 scale
}
}
# Convert to a 3 by `length(colors)` matrix of RGB values
rgb.vals <- sapply(X = colors, FUN = grDevices::col2rgb)
if (nrow(x = rgb.vals) != 3) {
rgb.vals <- t(x = rgb.vals)
}
# Blend together using the additive method
# Basically, resulting colors are the mean of the component colors
blend <- apply(
X = rgb.vals,
MARGIN = 1,
FUN = mean
)
# If we're returning RGB values, convert to matrix, just like col2rgb
# Otherwise, return as hexadecimal; can be used directly for plotting
if (as.rgb) {
result <- matrix(
data = blend,
nrow = 3,
dimnames = list(c('red', 'green', 'blue'), 'blend')
)
} else {
result <- grDevices::rgb(
matrix(data = blend, ncol = 3),
alpha = alpha.value,
maxColorValue = 255
)
}
return(result)
}
# Find the quantile of a data
#
# Converts a quantile in character form to a number regarding some data
# String form for a quantile is represented as a number prefixed with 'q'
# For example, 10th quantile is 'q10' while 2nd quantile is 'q2'
#
# Will only take a quantile of non-zero data values
#
# @param cutoff The cutoff to turn into a quantile
# @param data The data to turn find the quantile of
#
#' @importFrom stats quantile
#
# @return The numerical representation of the quantile
#
SetQuantile <- function(cutoff, data) {
if (grepl(pattern = '^q[0-9]{1,2}$', x = as.character(x = cutoff), perl = TRUE)) {
this.quantile <- as.numeric(x = sub(
pattern = 'q',
replacement = '',
x = as.character(x = cutoff)
)) / 100
data <- unlist(x = data)
data <- data[data > 0]
cutoff <- quantile(x = data, probs = this.quantile)
}
return(as.numeric(x = cutoff))
}
# No Grid
#
# Remove the grid lines from a ggplot2 plot
#
# @param ... Extra parameters to be passed to theme()
# @import ggplot2
# @return A ggplot2 theme object
# @seealso \code{theme}
# @import ggplot2
# @export
#
NoGrid <- function(...) {
no.grid <- theme(
panel.grid.major = element_blank(),
panel.grid.minor = element_blank(),
...
)
return(no.grid)
}
# Reset Par
#
# Reset the graphing space to
# mfrow = c(1, 1)
#
# @param ... Extra parameters for par
#
ResetPar <- function(...) {
par(mfrow = c(1, 1), ...)
}
# Plot a single feature on a violin plot
#
# @param feature Feature to plot
# @param data Data to plot
# @param cell.ident Idents to use
# @param do.sort Sort identity classes (on the x-axis) by the average
# expression of the attribute being potted
# @param y.max Maximum Y value to plot
# @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 gene.names
# @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 remove.legend Remove the legend from the plot
#
# @return A ggplot-based violin plot
#
#' @importFrom stats rnorm
#' @importFrom utils globalVariables
#
globalVariables(names = 'ident', package = 'Seurat', add = TRUE)
SingleVlnPlot <- function(
feature,
data,
cell.ident,
do.sort,
y.max,
size.x.use,
size.y.use,
size.title.use,
adjust.use,
point.size.use,
cols.use,
gene.names,
y.log,
x.lab.rot,
y.lab.rot,
legend.position,
remove.legend
) {
feature.name <- colnames(data)
colnames(data) <- "feature"
feature <- "feature"
set.seed(seed = 42)
data$ident <- cell.ident
if (do.sort) {
data$ident <- factor(
x = data$ident,
levels = names(x = rev(x = sort(x = tapply(
X = data[, feature],
INDEX = data$ident,
FUN = mean
))))
)
}
if (y.log) {
noise <- rnorm(n = length(x = data[, feature])) / 200
data[, feature] <- data[, feature] + 1
} else {
noise <- rnorm(n = length(x = data[, feature])) / 100000
}
if (all(data[, feature] == data[, feature][1])) {
warning(paste0("All cells have the same value of ", feature, "."))
} else{
data[, feature] <- data[, feature] + noise
}
y.max <- SetIfNull(x = y.max, default = max(data[, feature]))
plot <- ggplot(
data = data,
mapping = aes(
x = factor(x = ident),
y = feature
)
) +
geom_violin(
scale = "width",
adjust = adjust.use,
trim = TRUE,
mapping = aes(fill = factor(x = ident))
) +
guides(fill = guide_legend(title = NULL)) +
xlab("Identity") +
NoGrid() +
ggtitle(feature) +
theme(plot.title = element_text(size = size.title.use, face = "bold"),
legend.position = legend.position,
axis.title.x = element_text(
face = "bold",
colour = "#990000",
size = size.x.use
),
axis.title.y = element_text(
face = "bold",
colour = "#990000",
size = size.y.use
)
)
if (point.size.use != 0) {
plot <- plot + geom_jitter(height = 0, size = point.size.use)
}
plot <- plot + ggtitle(feature.name)
if (y.log) {
plot <- plot + scale_y_log10()
} else {
plot <- plot + ylim(min(data[, feature]), y.max)
}
if (feature %in% gene.names) {
if (y.log) {
plot <- plot + ylab(label = "Log Expression level")
} else {
plot <- plot + ylab(label = "Expression level")
}
} else {
plot <- plot + ylab(label = "")
}
if (! is.null(x = cols.use)) {
plot <- plot + scale_fill_manual(values = cols.use)
}
if (x.lab.rot) {
plot <- plot + theme(axis.text.x = element_text(angle = 45, hjust = 1, size=size.x.use))
}
if (y.lab.rot) {
plot <- plot + theme(axis.text.x = element_text(angle = 90, size=size.y.use))
}
if (remove.legend) {
plot <- plot + theme(legend.position = "none")
}
return(plot)
}
# Plot a single feature on a ridge plot
#
# @param feature Feature to plot
# @param data Data to plot
# @param cell.ident Idents to use
# @param do.sort Sort identity classes (on the x-axis) by the average
# expression of the attribute being potted
# @param y.max Maximum Y value to plot
# @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 gene.names
# @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 remove.legend Remove the legend from the plot
#
# @return A ggplot-based violin plot
#
#' @importFrom stats rnorm
#' @importFrom utils globalVariables
#' @importFrom ggridges geom_density_ridges theme_ridges
#
globalVariables(names = 'ident', package = 'Seurat', add = TRUE)
SingleRidgePlot <- function(
feature,
data,
cell.ident,
do.sort,
y.max,
size.x.use,
size.y.use,
size.title.use,
cols.use,
gene.names,
y.log,
x.lab.rot,
y.lab.rot,
legend.position,
remove.legend
) {
set.seed(seed = 42)
feature.name <- colnames(data)
colnames(data) <- "feature"
feature <- "feature"
data$ident <- cell.ident
if (do.sort) {
data$ident <- factor(
x = data$ident,
levels = names(x = rev(x = sort(x = tapply(
X = data[, feature],
INDEX = data$ident,
FUN = mean
))))
)
}
if (y.log) {
noise <- rnorm(n = length(x = data[, feature])) / 200
data[, feature] <- data[, feature] + 1
} else {
noise <- rnorm(n = length(x = data[, feature])) / 100000
}
data[, feature] <- data[, feature] + noise
y.max <- SetIfNull(x = y.max, default = max(data[, feature]))
plot <- ggplot(
data = data,
mapping = aes(
x = feature,
y = factor(ident)
)
) +
geom_density_ridges(scale = 4, mapping = aes(fill = factor(x = ident))) +
theme_ridges() +
scale_y_discrete(expand = c(0.01, 0)) + # will generally have to set the `expand` option
scale_x_continuous(expand = c(0, 0)) # for both axes to remove unneeded padding
plot <- plot + theme(
legend.position = legend.position,
axis.title.x = element_text(
face = "bold",
colour = "#990000",
size = size.x.use
),
axis.title.y = element_text(
face = "bold",
colour = "#990000",
size = size.y.use
)
) +
guides(fill = guide_legend(title = NULL)) +
#geom_jitter(height = 0, size = point.size.use) +
ylab("Identity") +
NoGrid() +
ggtitle(feature) +
theme(plot.title = element_text(size = size.title.use, face = "bold"))
plot <- plot + ggtitle(feature.name)
if (y.log) {
plot <- plot + scale_x_log10()
} else {
#plot <- plot + xlim(min(data[, feature]), y.max)
}
if (feature %in% gene.names) {
if (y.log) {
plot <- plot + xlab(label = "Log Expression level")
} else {
plot <- plot + xlab(label = "Expression level")
}
} else {
plot <- plot + xlab(label = "")
}
if (!is.null(x = cols.use)) {
plot <- plot + scale_fill_manual(values = cols.use)
}
if (x.lab.rot) {
plot <- plot + theme(axis.text.x = element_text(angle = 90, vjust = 0.5))
}
if (y.lab.rot) {
plot <- plot + theme(axis.text.x = element_text(angle = 90))
}
if (remove.legend) {
plot <- plot + theme(legend.position = "none")
}
return(plot)
}
#remove legend title
no.legend.title <- theme(legend.title = element_blank())
#set legend text
SetLegendTextGG <- function(x = 12, y = "bold") {
return(theme(legend.text = element_text(size = x, face = y)))
}
#set legend point size
SetLegendPointsGG <- function(x = 6) {
return(guides(colour = guide_legend(override.aes = list(size = x))))
}
#set x axis features
SetXAxisGG <- function(x = 16, y = "#990000", z = "bold", x2 = 12) {
return(theme(
axis.title.x = element_text(face = z, colour = y, size = x),
axis.text.x = element_text(angle = 90, vjust = 0.5, size = x2)
))
}
#set y axis features
SetYAxisGG <- function(x = 16, y = "#990000", z = "bold", x2 = 12) {
return(theme(
axis.title.y = element_text(face = z, colour = y, size = x),
axis.text.y = element_text(angle = 90, vjust = 0.5, size = x2)
))
}
# Get a gradient legend for palette of colours
#
# @param palette A palette of colours in hexadecimal form
# @param group An index matching the palette
# This allows to give a name for the palette
#
# @return A grob object for the gradient legend
#
GetGradientLegend <- function(palette, group) {
# Plot for each palette a gradient legend
p <- ggplot(data = as.data.frame(palette), mapping = aes(x = NA, y = NA)) +
geom_point(mapping = aes(colour = 1:20)) +
scale_colour_gradientn(colours = palette, breaks = c(1, 20), label = c("Min", "Max"), name = group,
guide = guide_colourbar(title.position = "top", title.hjust = 0.5, title.vjust = 0.5)) +
theme(legend.direction = "horizontal")
# Get legend from plot
l <- cowplot::get_legend(plot = p)
# Return legend grob
return(l)
}
#heatmap.2, but does not draw a key.
#unclear if this is necessary, but valuable to have the function coded in for modifications
#
#' @importFrom graphics axis mtext rect abline text title hist lines
#' @importFrom stats median order.dendrogram as.dendrogram reorder density
#
heatmap2NoKey <- function (
x,
Rowv = TRUE,
Colv = if (symm) "Rowv" else TRUE,
distfun = dist,
hclustfun = hclust,
dendrogram = c("both", "row", "column", "none"),
symm = FALSE,
scale = c("none", "row", "column"),
na.rm = TRUE,
revC = identical(x = Colv, y = "Rowv"),
add.expr,
breaks,
symbreaks = min(x < 0, na.rm = TRUE) || scale != "none",
col = "heat.colors",
colsep,
rowsep,
sepcolor = "white",
sepwidth = c(0.05, 0.05),
cellnote,
notecex = 1,
notecol = "cyan",
na.color = par("bg"),
trace = c("column", "row", "both", "none"),
tracecol = "cyan",
hline = median(breaks),
vline = median(breaks),
linecol = tracecol,
margins = c(5, 5),
ColSideColors,
RowSideColors,
cexRow = 0.2 + 1 / log10(x = nr),
cexCol = 0.2 + 1 / log10(x = nc),
labRow = NULL,
labCol = NULL,
key = TRUE,
keysize = 1.5,
density.info = c("histogram", "density", "none"),
denscol = tracecol,
symkey = min(x < 0, na.rm = TRUE) || symbreaks,
densadj = 0.25,
main = NULL,
xlab = NULL,
ylab = NULL,
lmat = NULL,
lhei = NULL,
axRowCol="black",
lwid = NULL,
dimTitle = NULL,
pc_title = NULL,
...
) {
scale01 <- function(x, low = min(x), high = max(x)) {
return((x - low) / (high - low))
}
retval <- list()
scale <- if (symm && missing(x = scale)) {
"none"
} else {
match.arg(arg = scale)
}
dendrogram <- match.arg(arg = dendrogram)
trace <- match.arg(arg = trace)
density.info <- match.arg(density.info)
if (length(x = col) == 1 && is.character(x = col)) {
col <- get(col, mode = "function")
}
if (! missing(x = breaks) && (scale != "none")) {
warning(
"Using scale=\"row\" or scale=\"column\" when breaks are",
"specified can produce unpredictable results.",
"Please consider using only one or the other."
)
}
if (is.null(x = Rowv) || is.na(x = Rowv)) {
Rowv <- FALSE
}
if (is.null(x = Colv) || is.na(x = Colv)) {
Colv <- FALSE
} else if (Colv == "Rowv" && !isTRUE(x = Rowv)) {
Colv <- FALSE