-
Notifications
You must be signed in to change notification settings - Fork 0
/
subfunctions_general_update.r
2535 lines (1944 loc) · 91.4 KB
/
subfunctions_general_update.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
# updatelog
# 20180925: fixed bug for recode_for_sankey, see details in the function
# 20180622: add a function for data matrix normalization, with a lot of method built in
# 20180305: add function to plot a composition bar
# 20180305: add function from taxid to tax table
# 20180128: add a function to turn factor into colors
# 20180130: add a multiplot function in case it is not availabe in the
# 20180130: add a handy function to plot the density plot, histogram in a plot, a lot of options available
# 20180115: add a mew function to plot the maxquant summary, check the the example for the required data format
# 20180110: revised version of matrix_missingvalue_filtering, a new function name and
# 20180109: revised/ a function to tidy proteingroups
# 20180109: revised/add a function to filter proteingroups by reverse, and concaminant
# 20180105: add a function from sthda to add grid on the scattter3d
# 20180104: add a function for changing color transparency
# 20171219: add a withCosoleRedirect function to direct the error messge to the browser
# 20171218: add a abundance support to compare to list: compare_two_vectorlist_with_value
# 20171216: specify package name to recode
# 20171212: add three functions, remove_allNA_rows, remove_allNA_columns, remove_1st_column
# special plot for maxquant result QC, to plot selected plot using data.frame with the follwing columns
# 1st column as sample names,
# 2nd column as values to plot
# columns after are meta information, usually the grouping information
# see example for the format
# this function has a newly desgined struction, to flexibly plot as required, instead of plotting all
# this is achieved by using a list structure to store the plot as required
# ggplot(data_frame) +
# geom_point(aes_string(col_names[1], col_names[2],
# shape = shape_factor,
# color = shape_factor
# ),
# size = 4,
# alpha = 0.5
# )
# this is a function to test if a variable is defined or not
is.defined <- function(sym) {
sym <- deparse(substitute(sym))
env <- parent.frame()
exists(sym, env)
}
# new function, only for normalization
# method(norm_choice) list:
# Divide_by_sum, Divide_by_mean,Substract_by_mean, center_scale, QUANTILE, PARETO_SCALING, range_to_0-1, range_to_-1-1, rank
# PLUS(ABS(MIN)): adding to each data element the minimum present in the data matrix, in absolute value.
# PARETO SCALING: each feature is centred to have mean 0 and scaled by the square root of the standard deviation of the feature's values;
# SQRT: square root of each data element;
# MANORM: scaling the values in each feature, dividing by the mean of the feature.
matrix_normalization <- function(x, margin = 2,norm_choice = "center_scale"){
install.packages.auto(preprocessCore) # for function normalize.quantiles
if(margin == 2){
x<- as.matrix(x)
}else if(margin == 1){
x<- t(as.matrix(x))
}else {
stop("margin has to be 1 for rowwise or 2 for columnwise")
}
if (norm_choice == 'Divide_by_sum'){
x <- x/matrix(rep(colSums(x),each = nrow(x)),nrow = dim(x)[1],ncol = dim(x)[2]) #dividing by the column sum
} else if (norm_choice == 'Divide_by_mean'){
x <- x/matrix(rep(colMeans(x),each = nrow(x)),nrow = dim(x)[1],ncol = dim(x)[2]) #dividing by the column sum
} else if (norm_choice == 'Substract_by_mean'){
x <- x-matrix(rep(colMeans(x),each = nrow(x)),nrow = dim(x)[1],ncol = dim(x)[2]) #dividing by the column sum
} else if (norm_choice == 'center_scale'){
x <- scale(x)
} else if (norm_choice == 'QUANTILE'){
x <- normalize.quantiles(x)
} else if (norm_choice == 'PARETO_SCALING'){
x_center <- x-matrix(rep(colMeans(x),each=nrow(x)),nrow=dim(x)[1],ncol=dim(x)[2])
x <- x_center/matrix(rep(sqrt(apply(x_center, 2, sd)),each = nrow(x)),nrow = dim(x)[1],ncol = dim(x)[2])
} else if (norm_choice == "range_to_0-1"){
x <- (x-min(x))/(max(x)-min(x))
} else if (norm_choice == "range_to_-1-1"){
x <- 2*(x-min(x))/(max(x)-min(x))-1
} else if(norm_choice == "rank"){
x <- apply(m, 2, rank)
}
# can add more options here, refer to Persues
# transpose matrix when for rowwise process
if(margin == 1){
x<- t(x)
}
return(x)
#example
# m <- matrix(1:20, nrow = 4)
# matrix_normalization(m,norm_choice = "center_only_column" )
}
# since the colorbrewer only has limited number of colors, this function can generate defined number of colors based on the colorbrewer
ColorGenerator <- function(ncolors = 10,
Rcolorbrewer_schemes = "div", # this only works when Rcolorbrewer is selected, c("seq","qual","div")
RcolorBrewer_theme = "Spectral" # this only works when the right Rcolorbrewer and schemes are selected
# For scheme "seq", check the available options by: rownames(brewer.pal.info[brewer.pal.info$category == "seq",])
# for scheme "qual", check by: rownames(brewer.pal.info[brewer.pal.info$category == "qual",])
# for scheme "div", check by: rownames(brewer.pal.info[brewer.pal.info$category == "div",])
){
install.packages.auto("RColorBrewer")
# get the max number of colors in the spectra
max_color <- brewer.pal.info[which(rownames(brewer.pal.info) == RcolorBrewer_theme),1]
# get the full series of the defined colorbrewer_colors
my_colbrew_colors <- brewer.pal(max_color,RcolorBrewer_theme)
# return the color generated
colorRampPalette(my_colbrew_colors)(ncolors)
}
# data_frame, has one column as labeling, and two columns to be ploted as x and y,
# additional colums could be used as color and shap mapping
# df <- dplyr::select(mtcars, wt, mpg, vs)
# df <- data.frame(label = row.names(df),df)
# #df$vs <- as.character(df$vs)
# data_frame <- df
#
#
ANCOM_rev <- function (OTUdat, sig = 0.05, multcorr = 3, tau = 0.02, theta = 0.1,
repeated = FALSE)
{
num_col <- ncol(OTUdat)
if (repeated == FALSE) {
colnames(OTUdat)[num_col] <- "Group" # change the last group column name
num_OTU <- ncol(OTUdat) - 1
sub_drop <- data.frame(nm_drop = "N/A")
sub_keep <- data.frame(nm_keep = "All subjects")
colnames(sub_drop) <- "Subjects removed"
colnames(sub_keep) <- "Subjects retained"
n_summary <- paste0("No subjects entirely removed (not a repeated-measures design)")
}
else {
colnames(OTUdat)[num_col - 1] <- "Group"
colnames(OTUdat)[num_col] <- "ID"
OTUdat$ID <- factor(OTUdat$ID)
num_OTU <- ncol(OTUdat) - 2
crossTab <- table(OTUdat$Group, OTUdat$ID) == 0
id_drop <- apply(crossTab, 2, FUN = function(x) any(x))
nm_drop <- names(which(id_drop))
idx_drop <- OTUdat$ID %in% nm_drop
OTUdat <- OTUdat[idx_drop == FALSE, ]
if (nrow(OTUdat) == 0) {
stop("Too many missing values in data, all subjects dropped")
}
OTUdat$ID <- droplevels(OTUdat$ID)
num_dropped <- sum(id_drop)
num_retain <- length(id_drop) - num_dropped
sub_drop <- data.frame(nm_drop = paste(nm_drop, collapse = ", "))
sub_keep <- data.frame(nm_keep = paste(levels(OTUdat$ID),
collapse = ", "))
colnames(sub_drop) <- "Subjects removed"
colnames(sub_keep) <- "Subjects retained"
n_summary <- paste0("Analysis used ", num_retain, " subjects (",
num_dropped, " were removed due to incomplete data)")
}
OTUdat$Group <- factor(OTUdat$Group) # force the group factor into
##
OTUdat <- OTUdat[which(is.na(OTUdat$Group) == FALSE), ]
# OTUdat <- data.frame(OTUdat[which(is.na(OTUdat$Group) ==
# FALSE), ], row.names = NULL)
message("Doing ANCOM analysis...")
W.detected <- ancom.detect(OTUdat, num_OTU, sig, multcorr, ncore = detectCores())
message("ANCOM analysis is done...")
W_stat <- W.detected
if (num_OTU < 10) {
detected <- colnames(OTUdat)[which(W.detected > num_OTU - 1)]
}
else {
if (max(W.detected)/num_OTU >= theta) {
c.start <- max(W.detected)/num_OTU
cutoff <- c.start - c(0.05, 0.1, 0.15, 0.2, 0.25)
prop_cut <- rep(0, length(cutoff))
for (cut in 1:length(cutoff)) {
prop_cut[cut] <- length(which(W.detected >= num_OTU *
cutoff[cut]))/length(W.detected)
}
del <- rep(0, length(cutoff) - 1)
for (ii in 1:(length(cutoff) - 1)) {
del[ii] <- abs(prop_cut[ii] - prop_cut[ii + 1])
}
if (del[1] < tau & del[2] < tau & del[3] < tau) {
nu = cutoff[1]
}
else if (del[1] >= tau & del[2] < tau & del[3] <
tau) {
nu = cutoff[2]
}
else if (del[2] >= tau & del[3] < tau & del[4] <
tau) {
nu = cutoff[3]
}
else {
nu = cutoff[4]
}
up_point <- min(W.detected[which(W.detected >= nu *
num_OTU)])
W.detected[W.detected >= up_point] <- 99999
W.detected[W.detected < up_point] <- 0
W.detected[W.detected == 99999] <- 1
detected <- colnames(OTUdat)[which(W.detected ==
1)]
}
else {
W.detected <- 0
detected <- "No significant OTUs detected"
}
}
results <- list(W = W_stat, detected = detected, dframe = OTUdat,
repeated = repeated, n_summary = n_summary, sub_drop = sub_drop,
sub_keep = sub_keep)
class(results) <- "ancom"
return(results)
}
plot_ancom_rev <- function (object, ncols = -1, select_plot_ids = NULL) # ncols = -1 means defalut 3 column
{
# this function is revised from the orignal one,
# one option is added to only take subset of the detected items to plot
# another modification is using melt function, instead of using a for loop to change the structure of the data.frame
# and also put some color for the grouping
# One of the thing I do not really understand is the part of using weight
# it does not have to that comnplicated. for the aim of taking the selected items out of the
# original data.frame
# anyway, did not bother to rewrite the whole function
if (!(class(object) == "ancom")) {
stop("'object' is not of class ancom")
}
repeated <- object$repeated
Group <- OTU <- ID <- NULL
dframe <- object$dframe
# force the last column name as "Group"
if (repeated == FALSE) {
colnames(dframe)[ncol(dframe)] <- "Group"
}else {
colnames(dframe)[ncol(dframe) - 1] <- "Group"
}
Sig_OTU <- object$detected
# if no significant items detected, generate a falk figure
if (Sig_OTU[1] == "No significant OTUs detected") {
plot(1:5, 1:5, col = "white", xaxt = "n", yaxt = "n",
xlab = "", ylab = "", frame.plot = FALSE)
text(3, 3, labels = "No significant OTUs detected")
}else { # take out the weight
if (repeated == FALSE) {
W_check <- data.frame(colnames(dframe)[-ncol(dframe)], object$W, row.names = NULL)
colnames(W_check) <- c("OTU_ID", "W")
} else {
W_check <- data.frame(colnames(dframe)[-c(ncol(dframe) - 1, ncol(dframe))], object$W, row.names = NULL)
colnames(W_check) <- c("OTU_ID", "W")
}
###
if(is.null(select_plot_ids)){
W_check <- W_check[which(W_check$OTU_ID %in% Sig_OTU), ]
}else if(length(select_plot_ids)>0 && any(select_plot_ids %in% W_check$OTU_ID)){
select_plot_ids <- select_plot_ids[select_plot_ids %in% W_check$OTU_ID]
W_check <- W_check[which(W_check$OTU_ID %in% select_plot_ids), ]
}else{
W_check <- W_check[which(W_check$OTU_ID %in% Sig_OTU), ]
}
W_check <- W_check[order(-W_check$W), ]
nplot <- nrow(W_check)
# get the sub data.frame.
t <-dframe[,colnames(dframe) %in% c(as.character(W_check$OTU_ID),"Group")]
pltDat <-reshape2::melt(t, id = "Group")
colnames(pltDat) <- c("Group","OTU_name", "OTU" )
pltDat$OTU <- log(pltDat$OTU + 1)
pltDat$OTU_name <- factor(pltDat$OTU_name, Sig_OTU)
if (ncols < 1) {
ncols <- min(3, nplot)
}
gplot <- ggplot(pltDat, aes(x = factor(Group), y = OTU, fill = Group)) +
facet_wrap(~OTU_name, ncol = ncols, scales = "free_y") +
geom_boxplot()
# return the plot directly
gplot + labs(x = "Group", y = "Log of Abundance") +
theme(panel.background = element_rect(fill = "white",
colour = "black"), panel.grid = element_blank(),
strip.text = element_text(size = rel(1.25)),
strip.background = element_rect(fill = "grey90",
color = "black"), axis.title = element_text(size = rel(1.25),
color = "black"), axis.text = element_text(size = rel(1.05),
color = "black"), legend.position = "none",
legend.background = element_rect(colour = "black",
fill = "white"), legend.key = element_rect(fill = "white"),
legend.title = element_text(size = 15), legend.text = element_text(size = 12))
}
}
ggplot_dual_axis = function(plot1, plot2, which.axis = "x") {
# Update plot with transparent panel
plot2 = plot2 + theme(panel.background = element_rect(fill = NA))
library(grid)
library(gtable)
grid.newpage()
# Increase right margin if which.axis == "y"
if(which.axis == "y") plot1 = plot1 + theme(plot.margin = unit(c(0.7, 1.5, 0.4, 0.4), "cm"))
# Extract gtable
g1 = ggplot_gtable(ggplot_build(plot1))
g2 = ggplot_gtable(ggplot_build(plot2))
# Overlap the panel of the second plot on that of the first
pp = c(subset(g1$layout, name == "panel", se = t:r))
g = gtable_add_grob(g1, g2$grobs[[which(g2$layout$name=="panel")]], pp$t, pp$l, pp$b, pp$l)
# Steal axis from second plot and modify
axis.lab = ifelse(which.axis == "x", "axis-b", "axis-l")
ia = which(g2$layout$name == axis.lab)
ga = g2$grobs[[ia]]
ax = ga$children[[2]]
# Switch position of ticks and labels
if(which.axis == "x") ax$heights = rev(ax$heights) else ax$widths = rev(ax$widths)
ax$grobs = rev(ax$grobs)
if(which.axis == "x")
ax$grobs[[2]]$y = ax$grobs[[2]]$y - unit(1, "npc") + unit(0.15, "cm") else
ax$grobs[[1]]$x = ax$grobs[[1]]$x - unit(1, "npc") + unit(0.15, "cm")
# Modify existing row to be tall enough for axis
if(which.axis == "x") g$heights[[2]] = g$heights[g2$layout[ia,]$t]
# Add new row or column for axis label
if(which.axis == "x") {
g = gtable_add_grob(g, ax, 2, 4, 2, 4)
g = gtable_add_rows(g, g2$heights[1], 1)
g = gtable_add_grob(g, g2$grob[[6]], 2, 4, 2, 4)
} else {
g = gtable_add_cols(g, g2$widths[g2$layout[ia, ]$l], length(g$widths) - 1)
g = gtable_add_grob(g, ax, pp$t, length(g$widths) - 1, pp$b)
g = gtable_add_grob(g, g2$grob[[7]], pp$t, length(g$widths), pp$b - 1)
}
# Draw it
grid.draw(g)
}
# plto taxon barplot by level, from a taxon expresion matrix and taxon linage
taxon_barplot_by_level <-function(df_taxon_expression,
df_taxon_lineage,
level,
plot_NA = FALSE,
use_percentage = TRUE,
draw_connection_line = FALSE,
BarWidth = 1,
line_size = 1
){
df_taxon_expression <- as.matrix(df_taxon_expression) # only matrix can have dupilicate ids
df_taxon_lineage <- as.data.frame(df_taxon_lineage)
if(!(level %in% colnames(df_taxon_lineage))){
message(paste0(level, "does not exist in df_taxon_lineage, please check the input and try again "))
stop()
}
# change the matrix row names as the corresponding taxon node name
rownames(df_taxon_expression) <- df_taxon_lineage[[level]]
if(!plot_NA){
# remove rows with row names as NAs, which means that this
if(length(which(is.na(rownames(df_taxon_expression)))) > 0){
df_taxon_expression <- df_taxon_expression[-which(is.na(rownames(df_taxon_expression))),]
}
}else{
rownames(df_taxon_expression)[which(is.na(rownames(df_taxon_expression)))] <- "NA"
}
# combine rows with the same row names
df_for_plot <- aggregate(df_taxon_expression, list(rownames(df_taxon_expression)), sum)
# organize
rownames(df_for_plot) <- df_for_plot[,1]
df_for_plot <- df_for_plot[,-1]
compositionbar_plot(df = df_for_plot,
use_percentage = use_percentage,
draw_connection_line = draw_connection_line,
legend_label = level,
BarWidth = BarWidth,
line_size = line_size
)
## example
# otumat = matrix(sample(1:100, 100, replace = TRUE), nrow = 10, ncol = 10)
# rownames(otumat) <- paste0("OTU", 1:nrow(otumat))
# colnames(otumat) <- paste0("Sample", 1:ncol(otumat))
# taxmat = matrix(sample(letters, 70, replace = TRUE), nrow = nrow(otumat), ncol = 7)
# rownames(taxmat) <- rownames(otumat)
# colnames(taxmat) <- c("Domain", "Phylum", "Class", "Order", "Family", "Genus", "Species")
#
# taxon_barplot_by_level(df_taxon_expression = otumat,
# df_taxon_lineage = taxmat,
# plot_NA = TRUE,
# level = "Family")
}
# plot a compostion bar from a matrix directly, with lines connected
compositionbar_plot <- function(df,
draw_connection_line = TRUE,
use_percentage = FALSE,
legend_label = "Legend",
BarWidth = 0.5, # 0~1, 0 is no width; 1 is full
line_size = 1 # only works when draw_connection_line is true
){
if(use_percentage){
my_df <-table2lPercents_by_col(df)
}else{
my_df <- df
}
my_df_m <- reshape2::melt(t(my_df))
colnames(my_df_m)[2] <- legend_label
if(draw_connection_line){
# data prepare
y_start <- apply(my_df,2, cumsum)
y_end <- y_start[,-1]
y_end <- cbind(y_end, "new" = NA)
colnames(y_end) <- colnames(y_start)
my_df_y_start_m <-reshape2::melt(t(y_start))
my_df_y_end_m <-reshape2::melt(t(y_end))
# this is the data for plot
my_df_forplot <- cbind.data.frame(my_df_m, "y_start" = my_df_y_start_m$value, "y_end" = my_df_y_end_m$value )
my_df_forplot$x_start <- as.numeric(my_df_forplot$Var1) + 0.5*BarWidth
my_df_forplot$x_end <- as.numeric(my_df_forplot$Var1)+ (1-0.5*BarWidth)
# ploting
compositionbar_plot <-ggplot(my_df_forplot, aes_string("Var1", "value", group=legend_label, fill = legend_label, colour = legend_label)) +
geom_bar(stat="identity", width = BarWidth,
position = position_stack(reverse = TRUE)) +
geom_segment(aes_string(x = "x_start", xend = "x_end",
y = "y_start", yend = "y_end",
color = legend_label),
size = line_size,
linetype = "solid"
)
}else{
my_df_forplot <- my_df_m
# ploting
compositionbar_plot <-ggplot(my_df_forplot, aes_string("Var1", "value", group=legend_label, fill = legend_label, colour = legend_label)) +
geom_bar(stat="identity", width = BarWidth,
position = position_stack(reverse = TRUE))
}
# prettier
# compositionbar_plot <- ggplot2_prettier(compositionbar_plot,
# maintitle = "Composition bar",
# xlab = "Sample",
# ylab = "Composition",
# axis.text.angle.x = as.numeric(90),
# axis.text.angle.y = 0,
# vertical = FALSE)
return(compositionbar_plot)
## example
# my_df <- matrix(1:20, nrow = 4)
# colnames(my_df) <- paste0("col_",LETTERS[1:5])
# rownames(my_df) <- paste0("row_",c("a","f", "z", "k"))
# compositionbar_plot(df = my_df, use_percentage = TRUE)
#
}
taxID_to_taxtable_gut <- function(ids, ranks_keep = c("phylum","class","order","family","genus","species")){
# readin the preindexed database taxon information
frequent_taxon_id_rank_lineage<- read.delim(".//data//taxon//taxon_id_rank_lineage_preindexed.tsv", header = TRUE, row.names = 1)
frequent_taxon_id_rank_lineage$id <- rownames(frequent_taxon_id_rank_lineage)
ranks_keep <- c("phylum","class","order","family","genus","species")
index_colmn <- match(ranks_keep,colnames(frequent_taxon_id_rank_lineage))
# get the taxon ranks
index_row <- match(ids, frequent_taxon_id_rank_lineage$id)
found_in_database <- frequent_taxon_id_rank_lineage[na.omit(index_row),index_colmn]
return(found_in_database)
## example
# ids <- sample(frequent_taxon_id_rank_lineage$id,10)
# ta <- taxID_to_taxtable_gut(ids)
}
# avaliable colorschemes from Rcolor Brewer qulity colors
# "Accent" "Dark2" "Paired" "Pastel1" "Pastel2" "Set1" "Set2" "Set3"
factor2color <- function(factor_input, Rcolorbrewerscheme = "Accent"){
install.packages.auto("RColorBrewer")
colors <- as.factor(factor_input)
max_color <- brewer.pal.info[which(rownames(brewer.pal.info) == Rcolorbrewerscheme),1]
if(nlevels(colors) <= max_color){
levels(colors) <- brewer.pal(nlevels(colors),Rcolorbrewerscheme)
}else{
levels(colors) <- rainbow(nlevels(colors))
}
return(as.vector(colors))
# example:
# f <- as.factor(sample(LETTERS[1:3], 10, replace = TRUE))
# factor2color(f, "Accent")
}
# log
#
# advanced_scatterplot(data_frame = mtcars,
# x_index = 1,# column index/location
# y_index = 3,# column index/location
#
# point_shape_index = NULL, # column index/location
# point_shape_manual = c(15, 16, 17, 18),
#
# point_color_index = NULL, # column index/location
# point_color_manual = rainbow(10), # if point_color_index is null, only use the first color, otherwise
# point_color_type = "group", # c("graidnet", "group"), if group, will force to factor
#
# point_size_index = NULL,
# point_size_manual = 4, # will be overide by point_size_index
# point_alpha = 0.5,
#
# overlay_polygon = FALSE,
# polygon_type = "convex", # or "ellipse"
# polygon_index = NULL, # draw polygon overlap, will choose
# polygon_alpha = 0.5,
# ellipse_confidience = 0.95, # only works when ellipse is choose for polygon_type
# polygon_fill_color_manual = rainbow(10), # null means auto color, otherwise provide list of color values
#
# label_text_index = 8, # to do this section
# label_color_index = 8,
# label_color_manual = rainbow(10)[2:3],
# label_size_index = NULL,
# label_size_manual = 4,
#
# equal_xy = FALSE
#
# )
advanced_scatterplot <- function(data_frame, # df, with at least three columns, 1 as labeling, 2 as x y mapping
x_index = NULL,# column index/location
y_index = NULL,# column index/location
point_shape_index = NULL, # column index/location
point_shape_manual = c(15, 16, 17, 18),
point_color_index = NULL, # column index/location
point_color_manual = rainbow(10), # if point_color_index is null, only use the first color, otherwise
point_color_type = "group", # c("graidnet", "group"), if group, will force to factor
point_size_index = NULL,
point_size_manual = 4, # will be overide by point_size_index
point_alpha = 0.5,
overlay_polygon = FALSE,
polygon_type = "convex", # or "ellipse"
polygon_index = NULL, # draw polygon overlap, will choose
polygon_alpha = 0.5,
ellipse_confidience = 0.95, # only works when ellipse is choose for polygon_type
polygon_fill_color_manual = rainbow(10), # null means auto color, otherwise provide list of color values
label_text_index = NULL, # to do this section
label_color_index = NULL,
label_color_manual = rainbow(10),
label_size_index = NULL,
label_size_manual = 4,
equal_xy = FALSE # if equal xy axix
# to do: add more support to plot modeling curve, intensity etc.
){
install.packages.auto(ggrepel)
# get the colum name list, easy to index the location
if(is.null(colnames(data_frame))){ # if there is no name, give a name
colnames(data_frame) <- paste0("col_", 1:ncol(data_frame))
}
col_names <- colnames(data_frame) # get the names
# check xy index
if(x_index >length(col_names)){
stop("x_index is out of range" )
}
if(y_index >length(col_names)){
stop("y_index is out of range" )
}
#___________________________
# check point shape index
if(is.null(point_shape_index)){ # if no shape mapping, there should be only 1 shape
# in case there are more than one shapes given, better to have just one shape
if(length(point_shape_manual) > 1){
point_shape_manual <- point_shape_manual[1]
}
}else{
if(point_shape_index > ncol(data_frame)){
message("shape index is out of range")
point_shape_index <- NULL
if(length(point_shape_manual) > 1){
point_shape_manual <- point_shape_manual[1]
}
}else{
# in case this column is continuous numerics, force to factors, and this will overide color gradient settngs,
# if the color gradient set to the same column, and will only show as group
data_frame[[point_shape_index]] <- as.factor(data_frame[[point_shape_index]])
}
}
#_________________________________________
# check point color index
if(is.null(point_color_index)){ #if no color map, only one color
if(length(point_color_manual) > 1){
point_color_manual <- point_color_manual[1]
}
}else{ # if there is color mapping, either gradient or group (factor)
if(point_color_index > ncol(data_frame)){
message("color index is out of range")
point_color_index <- NULL
if(length(point_color_manual) > 1){
point_color_manual <- point_color_manual[1]
}
}else{
# in case this column is continuous numerics, force it to factor
if(point_color_type == "group"){
data_frame[[point_color_index]] <- as.factor(data_frame[[point_color_index]])
}else if(point_color_type == "gradient" && point_color_index == point_shape_index){
# if point shape and point color set to the same index, only use group mode
point_color_type = "group"
}
}
}
#_________________________________________
# check point size
if(!is.null(point_size_index)){
if( point_size_index > ncol(data_frame) |point_size_index < 0){
message("point sizes index is out of range, set to null")
point_size_index <- NULL
}
}
#______________________________________________
#check label text
# check if shape_map set correctly
if(!is.null(label_text_index)){
if(label_text_index > ncol(data_frame)){
message("label index is out of range, set to null")
label_text_index <- NULL
}
#data_frame[[label_text_index]] <- as.character(data_frame[[label_text_index]])
}
#_________________________________________________
# check label text color
if(is.null(label_color_index)){
if(length(label_color_manual) > 1){
label_color_manual <- label_color_manual[1]
}
}else{
if(label_color_index > ncol(data_frame) | label_color_index < 0){
message("color index is out of range, set to null")
label_color_index <- NULL
if(length(label_color_manual) > 1){
label_color_manual <- label_color_manual[1]
}
}
# here force to factor, no need to map gradient to label text color
data_frame[[label_color_index]] <- as.factor(data_frame[[label_color_index]])
}
# check label size
if(!is.null(label_size_index) && label_size_index > ncol(data_frame)){
message("label size index is out of range, set to null")
label_size_index <- NULL
}
#_____________________________________________________________________________________________________
# start plotting
# maping data
this_plot <- ggplot(data = data_frame, aes_string(x = col_names[x_index],
y = col_names[y_index]))
# plot polygon layer first, behind the points
if(overlay_polygon && !is.null(polygon_index) ){
if( polygon_index < 0 || polygon_index > length(col_names)){
message("polygon_index is out of range, cannot render polygon")
}else{
data_frame_for_polygon <- data_frame
data_frame_for_polygon[[polygon_index]] <- as.factor(data_frame_for_polygon[[polygon_index]])
switch(polygon_type,
"convex" = {
df_polygan_convex <- data_frame_for_polygon[,c(x_index,y_index,polygon_index)] # genearate a new df for polygon
splitData <- split(df_polygan_convex, df_polygan_convex[[3]])
# find the convex
appliedData <- lapply(splitData, function(df){
df[chull(df), ] # chull really is useful, even outside of contrived examples.
})
combinedData <- do.call(rbind, appliedData)
# plot the polygon here
this_plot <- this_plot + geom_polygon(data = combinedData, # This is also a nice example of how to plot
aes_string(x = col_names[x_index],
y = col_names[y_index],
fill = col_names[polygon_index]), # two superimposed geoms
alpha = polygon_alpha)
},
"ellipse" = {
this_plot <- this_plot + stat_ellipse(data = data_frame_for_polygon,
aes_string(fill = col_names[polygon_index]),
level = ellipse_confidience,
alpha = polygon_alpha,
geom = "polygon")
}
)
# manual coloring of the polygon
if(!is.null(polygon_color_manual)){
this_plot <- this_plot + scale_fill_manual(values = polygon_color_manual)
}
}
}
#________________________________________________________________________________
#plot geom_points here
#
# plot the points here
if(is.null(point_color_index)){ # without mapping color, that is single color
if(is.null(point_shape_index)){ # without point shape mapping
if(is.null(point_size_index)){
this_plot <- this_plot + geom_point(shape = point_shape_manual, # use manual shapes
size = point_size_manual, # use manul size
color = point_color_manual, # use manual colors
alpha = point_alpha)
}else{
this_plot <- this_plot + geom_point(aes_string(size =col_names[point_size_index]),
shape = point_shape_manual,# use manual size
color = point_color_manual, # use manual colors
alpha = point_alpha)
}
}else{ # with point shape mapping
if(is.null(point_size_index)){
this_plot <- this_plot + geom_point(aes_string(shape = col_names[point_shape_index]),
size = point_size_manual, # use manul size
color = point_color_manual, # use manual colors
alpha = point_alpha) +
scale_shape_manual(values = point_shape_manual)
}else{
this_plot <- this_plot + geom_point(aes_string(size = col_names[point_size_index],
shape = col_names[point_shape_index] ),
color = point_color_manual, # use manual colors
alpha = point_alpha) +
scale_shape_manual(values = point_shape_manual)
}
}
}else{ # if mapping color
switch(point_color_type,
"group" = {
if(is.null(point_shape_index)){ # without point shape mapping
if(is.null(point_size_index)){
this_plot <- this_plot + geom_point(aes_string(color = col_names[point_color_index]),
shape = point_shape_manual, # use manual shapes
size = point_size_manual, # use manul size
alpha = point_alpha) +
scale_color_manual(values = point_color_manual) # use manual colors as groups
}else{
this_plot <- this_plot + geom_point(aes_string(color = col_names[point_color_index],
size =col_names[point_size_index]),
shape = point_shape_manual,# use manul size
alpha = point_alpha) +
scale_color_manual(values = point_color_manual) # use manual colors as groups
}
}else{ # with point shape mapping
if(is.null(point_size_index)){
this_plot <- this_plot + geom_point(aes_string(color = col_names[point_color_index],
shape = col_names[point_shape_index] ),
size = point_size_manual, # use manul size
alpha = point_alpha) +
scale_shape_manual(values = point_shape_manual) + # use manual shapes
scale_color_manual(values = point_color_manual) # use manual colors as groups
}else{
this_plot <- this_plot + geom_point(aes_string(color = col_names[point_color_index],
size = col_names[point_size_index],
shape = col_names[point_shape_index] ),
alpha = point_alpha) +
scale_shape_manual(values = point_shape_manual)+ # use manual shapes
scale_color_manual(values = point_color_manual) # use manual colors as groups
}
}
},
"gradient" = {
if(is.null(point_shape_index)){ # without point shape mapping
if(is.null(point_size_index)){
this_plot <- this_plot + geom_point(aes_string(color = col_names[point_color_index]),
shape = point_shape_manual, # use manual shapes
size = point_size_manual, # use manul size
alpha = point_alpha) +
scale_color_gradientn(values = point_color_manual) # use manual colors as groups
}else{
this_plot <- this_plot + geom_point(aes_string(color = col_names[point_color_index],
size =col_names[point_size_index]),
shape = point_shape_manual,# use manul size
alpha = point_alpha) +
scale_color_gradientn(values = point_color_manual) # use manual colors as groups
}
}else{ # with point shape mapping
if(is.null(point_size_index)){
this_plot <- this_plot + geom_point(aes_string(color = col_names[point_color_index],
shape = col_names[point_shape_index] ),
size = point_size_manual, # use manul size
alpha = point_alpha) +
scale_shape_manual(values = point_shape_manual) + # use manual shapes
scale_color_gradientn(values = point_color_manual) # use manual colors as groups
}else{
this_plot <- this_plot + geom_point(aes_string(color = col_names[point_color_index],
size = col_names[point_size_index],
shape = col_names[point_shape_index] ),
alpha = point_alpha) +
scale_shape_manual(values = point_shape_manual)+ # use manual shapes
scale_color_gradientn(values = point_color_manual) # use manual colors as groups
}
}
}
)
}
# some other generic options: equal scaling of x and y
if(equal_xy){
this_plot <- this_plot + coord_equal()
}
# repel labeling
if(!is.null(label_text_index)){
if(is.null(label_color_index)){
if(is.null(label_size_index)){
this_plot <- this_plot +
geom_text_repel(aes_string(col_names[x_index],
col_names[y_index],
label = col_names[label_text_index]),
color = label_color_manual,
size = label_size_manual
)
}else{
this_plot <- this_plot +
geom_text_repel(aes_string(col_names[x_index],
col_names[y_index],
label = col_names[label_text_index],
size = col_names[label_size_index]),
color = label_color_manual
)
}
}else{
if(is.null(label_size_index)){
this_plot <- this_plot +
geom_text_repel(aes_string(col_names[x_index],
col_names[y_index],
color = col_names[label_color_index],
label = col_names[label_text_index]),
size = label_size_manual) +
scale_color_manual(values=label_color_manual) # manual color
}else{
this_plot <- this_plot +
geom_text_repel(aes_string(col_names[x_index],
col_names[y_index],
color = col_names[label_color_index],