-
Notifications
You must be signed in to change notification settings - Fork 16
/
plot_fns.R
executable file
·6607 lines (5559 loc) · 251 KB
/
plot_fns.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
#' Plot dataRes object
#'
#' For plotting an S3 object of type dataRes
#'
#' @param dataRes_obj object of class dataRes, created by the
#' \code{\link{edata_summary}} function
#' @param metric character string indicating which metric to use in plot:
#' 'mean', 'median', 'sd, 'pct_obs', 'min', or 'max'
#' @param density logical value, defaults to FALSE. If TRUE, a density plot of
#' the specified metric is returned.
#' @param ncols integer value specifying the number columns for the histogram
#' facet_wrap. This argument is used when \code{metric} is not null. The
#' default is NULL.
#' @param interactive logical value. If TRUE, produces an interactive plot.
#' @param x_lab character string specifying the x-axis label when the metric
#' argument is NULL. The default is NULL in which case the x-axis label will
#' be "count".
#' @param x_lab_sd character string used for the x-axis label for the
#' mean/standard deviation plot when the \code{metric} argument is not NULL.
#' @param x_lab_median character string used for the x-axis label for the
#' mean/median plot when the \code{metric} argument is not NULL.
#' @param y_lab character string specifying the y-axis label. The default is
#' NULL in which case the y-axis label will be the metric selected for the
#' \code{metric} argument.
#' @param y_lab_sd character string used for the y-axis label for the
#' mean/standard deviation plot when the \code{metric} argument is not NULL.
#' @param y_lab_median character string used for the y-axis label for the
#' mean/median plot when the \code{metric} argument is not NULL.
#' @param x_lab_size integer value indicating the font size for the x-axis. The
#' default is 11.
#' @param y_lab_size integer value indicating the font size for the y-axis. The
#' default is 11.
#' @param x_lab_angle integer value indicating the angle of x-axis labels
#' @param title_lab character string specifying the plot title when the
#' \code{metric} argument is NULL.
#' @param title_lab_sd character string used for the plot title for the
#' mean/standard deviation plot when the \code{metric} argument is not NULL.
#' @param title_lab_median character string used for the plot title for the
#' mean/median plot when the \code{metric} argument is not NULL.
#' @param title_lab_size integer value indicating the font size of the plot
#' title. The default is 14.
#' @param legend_lab character string specifying the legend title.
#' @param legend_position character string specifying the position of the
#' legend. Can be one of "right", "left", "top", or "bottom". The default is
#' "right".
#' @param point_size integer specifying the size of the points. The default is
#' 2.
#' @param bin_width integer indicating the bin width in a histogram. The default
#' is 0.5.
#' @param bw_theme logical value. If TRUE, uses the ggplot2 black and white
#' theme.
#' @param palette character string indicating the name of the RColorBrewer
#' palette to use. For a list of available options see the details section in
#' \code{\link[RColorBrewer]{RColorBrewer}}.
#'
#' @details This function can only create plots for dataRes objects whose 'by' =
#' 'molecule' and 'groupvar' attribute is non NULL
#'
#' @return ggplot2 plot object if interactive is FALSE, or plotly plot object if
#' interactive is TRUE
#'
#' @examples
#' library (pmartRdata)
#' mylipid <- edata_transform(omicsData = lipid_pos_object, data_scale = "log2")
#' result <- edata_summary(omicsData = mylipid,
#' by = "molecule",
#' groupvar = "Virus")
#' plot(result)
#'
#' @rdname plot-dataRes
#'
#' @export
#'
plot.dataRes <- function (dataRes_obj, metric = NULL, density = FALSE,
ncols = NULL, interactive = FALSE, x_lab = NULL,
x_lab_sd = NULL, x_lab_median = NULL, y_lab = NULL,
y_lab_sd = NULL, y_lab_median = NULL, x_lab_size = 11,
y_lab_size = 11, x_lab_angle = NULL, title_lab = NULL,
title_lab_sd = NULL, title_lab_median = NULL,
title_lab_size = 14, legend_lab = NULL,
legend_position = "right", point_size = 2,
bin_width = 1, bw_theme = TRUE, palette = NULL) {
# Preliminaries --------------------------------------------------------------
# check that attr(dataRes_obj, "by") == "molecule"
if(attr(dataRes_obj, "by") != "molecule") {
# My name is Evan Martin. You killed my plot. Prepare to die.
stop (paste("can only plot a dataRes object if its 'by' attribute is equal",
"to 'molecule'",
sep = " "))
}
# check that attr(dataRes_obj, "groupvar") is not NULL
if(is.null(attr(dataRes_obj, "groupvar"))) {
# My name is Evan Martin. You killed my plot. Prepare to die.
stop (paste("can only plot a dataRes object if its 'groupvar' attribute is",
"not NULL",
sep = " "))
}
# Check if the data is on a log scale. If it is not the histograms will not
# work properly when metric = mean, sd, ... because of the wide range of
# abundance values.
if (attr(dataRes_obj, "data_scale") == "abundance") {
# My name is Evan Martin. You killed my plot. Prepare to die.
stop ("Data must be on the log scale to plot.")
}
# Make sure palette is one of the RColorBrewer options if it is not NULL.
if (!is.null(palette)) {
if (!(palette %in% c("YlOrRd", "YlOrBr", "YlGnBu", "YlGn", "Reds","RdPu",
"Purples", "PuRd", "PuBuGn", "PuBu", "OrRd","Oranges",
"Greys", "Greens", "GnBu", "BuPu","BuGn","Blues",
"Set3", "Set2", "Set1", "Pastel2", "Pastel1", "Paired",
"Dark2", "Accent", "Spectral", "RdYlGn", "RdYlBu",
"RdGy", "RdBu", "PuOr","PRGn", "PiYG", "BrBG"))) {
# INCONCEIVABLE!!!
stop ("palette must be an RColorBrewer palette")
}
}
# extract molecule name
edata_cname = attr(dataRes_obj, "cnames")$edata_cname
# Make labels for various aspects of the plot. (Super tedious!!!)
xLabelSd <- if (is.null(x_lab_sd)) "mean" else x_lab_sd
yLabelSd <- if (is.null(y_lab_sd)) "sd" else y_lab_sd
xLabelMedian <- if (is.null(x_lab_median)) "mean" else x_lab_median
yLabelMedian <- if (is.null(y_lab_median)) "median" else y_lab_median
plotTitleSd <- if (is.null(title_lab_sd))
"Mean x Standard Deviation" else
title_lab_sd
plotTitleMedian <- if (is.null(title_lab_median))
"Mean x Median" else
title_lab_median
legendLabel <- if (is.null(legend_lab)) "Group" else legend_lab
# Build beautiful plots ------------------------------------------------------
if (is.null(metric)) {
# scatterplots
# subseting dataRes_obj object
mean <- dataRes_obj$mean
median <- dataRes_obj$median
sd <- dataRes_obj$sd
# melting data frames from dataRes object
mean_melt <- reshape2::melt(mean, id.vars = edata_cname)
names(mean_melt)[3] <- "mean"
sd_melt <- reshape2::melt(sd, id.vars = edata_cname)
names(sd_melt)[3] <- "sd"
median_melt <- reshape2::melt(median, id.vars = edata_cname)
names(median_melt)[3] <- "median"
data_mean_sd <- merge(mean_melt,
sd_melt,
by = c(edata_cname, "variable"))
data_mean_median <- merge(mean_melt,
median_melt,
by = c(edata_cname, "variable"))
q <- ggplot2::ggplot(data_mean_sd,
ggplot2::aes(x = mean,
y = sd,
color = variable)) +
ggplot2::geom_point(size = point_size) +
ggplot2::xlab(xLabelSd) +
ggplot2::ylab(yLabelSd) +
ggplot2::ggtitle(plotTitleSd)
p <- ggplot2::ggplot(data_mean_median,
ggplot2::aes(x = mean,
y = median,
color = variable)) +
ggplot2::geom_point(size = point_size) +
ggplot2::xlab(xLabelMedian) +
ggplot2::ylab(yLabelMedian) +
ggplot2::ggtitle(plotTitleMedian)
# Want the black and white theme? As you wish.
if (bw_theme) {
q <- q + ggplot2::theme_bw()
p <- p + ggplot2::theme_bw()
}
# Create a generic theme that will be used for both plot.
the_theme <- ggplot2::theme(
plot.title = ggplot2::element_text(size = title_lab_size),
axis.title.x = ggplot2::element_text(size = x_lab_size),
axis.title.y = ggplot2::element_text(size = y_lab_size),
axis.text.x = ggplot2::element_text(angle = x_lab_angle, hjust = 1),
legend.position = legend_position
)
# Add information to the plot from theme. Must be done after theme_bw()
# otherwise the black and white theme overwrites everything that was
# specified.
q <- q +
ggplot2::labs(color = legendLabel) +
the_theme
p <- p +
ggplot2::labs(color = legendLabel) +
the_theme
# Want a plot with beautiful colors? As you wish.
if (!is.null(palette)) {
# Use the ColorBrewer color and create the legend title
p <- p +
ggplot2::scale_color_brewer(palette = palette,
name = legendLabel)
q <- q +
ggplot2::scale_color_brewer(palette = palette,
name = legendLabel)
}
# Want an interactive plot? As you wish.
if (interactive) {
q <- plotly::ggplotly(q)
p <- plotly::ggplotly(p)
plotly::subplot(q, p, nrows = 1)
} else {
# Combine the plots into one plot when interactive is FALSE.
patchwork:::wrap_plots(q, p)
}
} else if (!is.null(metric)) {
if (!(metric %in% c('mean', 'median','sd', 'pct_obs', 'min', 'max'))) {
# There is a shortage of perfect plots in the world. It is a shame to ruin
# this one.
stop ("metric must be one of mean, median, sd, pct_obs, min or max")
}
if (!is.logical(density)) stop ("density must be either TRUE or FALSE")
# if density == F, will plot faceted histograms.
if (density == FALSE) {
# More tedious label creating .... (deep sigh).
xlabel <- if (is.null(x_lab)) metric else x_lab
ylabel <- if (is.null(y_lab)) "count" else y_lab
plotTitle <- if (is.null(title_lab))
paste("Histograms for ", metric, sep = "") else
title_lab
# subsetting dataRes object
data = dataRes_obj[[metric]]
data_melt = reshape2::melt(data, id.vars = edata_cname)
r <- ggplot2::ggplot(data_melt,
ggplot2::aes(x = value,
fill = variable)) +
ggplot2::geom_histogram(binwidth = bin_width, colour = "white") +
ggplot2::facet_wrap(~variable, ncol = ncols)
# Create a density plot. Following code runs when density = TRUE.
} else {
# More tedious label creating .... (defeated sigh).
xlabel <- if (is.null(x_lab)) metric else x_lab
ylabel <- if (is.null(y_lab)) "density" else y_lab
plotTitle <- if (is.null(title_lab))
paste("Density plots for ", metric, sep = "") else
title_lab
# if density == T, will plot geom_density
data = dataRes_obj[[metric]]
data_melt = reshape2::melt(data, id.vars = edata_cname)
r <- ggplot2::ggplot(data_melt,
ggplot2::aes(x = value,
colour = variable)) +
ggplot2::geom_density()
}
# Want the black and white theme? As you wish.
if (bw_theme) r <- r + ggplot2::theme_bw() +
ggplot2::theme(strip.background = ggplot2::element_rect(fill = "white"))
# Add the remaining labels and text sizes/orientation to the plot.
r <- r +
ggplot2::ggtitle(plotTitle) +
ggplot2::xlab(xlabel) +
ggplot2::ylab(ylabel) +
ggplot2::labs(color = legendLabel) +
ggplot2::theme(
plot.title = ggplot2::element_text(size = title_lab_size),
axis.title.x = ggplot2::element_text(size = x_lab_size),
axis.title.y = ggplot2::element_text(size = y_lab_size),
axis.text.x = ggplot2::element_text(angle = x_lab_angle, hjust = 1),
legend.position = legend_position
)
# Want a plot with gorgeous colors? As you wish.
if (!is.null(palette)) {
# Use the ColorBrewer color and create the legend title
r <- r +
ggplot2::scale_fill_brewer(palette = palette,
name = legendLabel)
}
# Want an interactive plot? As you wish.
if (interactive) r <- plotly::ggplotly(r)
return (r)
}
}
#' Plot isobaricnormRes object
#'
#' Creates box plots for an S3 object of type 'isobaricnormRes'
#'
#' @param isobaricnormRes_obj an object of type isobaricnormRes, created by
#' \code{\link{normalize_isobaric}} with apply_norm = FALSE
#' @param order logical value. If TRUE the samples will be ordered by the column
#' of f_data containing the experiment/plate information.
#' @param interactive logical value. If TRUE produces an interactive plot.
#' @param x_lab character string specifying the x-axis label
#' @param y_lab character string specifying the y-axis label
#' @param x_lab_size integer value indicating the font size for the x-axis. The
#' default is 11.
#' @param y_lab_size integer value indicating the font size for the y-axis. The
#' default is 11.
#' @param x_lab_angle integer value indicating the angle of x-axis labels.
#' @param title_lab character string specifying the plot title.
#' @param title_lab_size integer value indicating the font size of the plot
#' title. The default is 14.
#' @param legend_lab character string specifying the legend title.
#' @param legend_position character string specifying the position of the
#' legend. Can be one of "right", "left", "top", "bottom", or "none". The
#' default is "none".
#' @param bw_theme logical value. If TRUE uses the ggplot2 black and white
#' theme.
#' @param palette character string indicating the name of the RColorBrewer
#' palette to use. For a list of available options see the details section in
#' \code{\link[RColorBrewer]{RColorBrewer}}.
#'
#' @return ggplot2 plot object if interactive is FALSE, or plotly plot object if
#' interactive is TRUE
#'
#' @examples
#' library(pmartRdata)
#' myiso <- edata_transform(omicsData = isobaric_object, data_scale = "log2")
#' myiso_norm <- normalize_isobaric(myiso, exp_cname = "Plex",
#' apply_norm = FALSE,
#' refpool_cname = "Virus",
#' refpool_notation = "Pool")
#' plot(result)
#'
#' @importFrom rlang .data
#'
#' @rdname plot-isobaricnormRes
#'
#' @export
#'
plot.isobaricnormRes <- function (isobaricnormRes_obj, order = FALSE,
interactive = FALSE, x_lab = NULL,
y_lab = NULL, x_lab_size = 11,
y_lab_size = 11, x_lab_angle = NULL,
title_lab = NULL, title_lab_size = 14,
legend_lab = NULL, legend_position = "none",
bw_theme = TRUE, palette = NULL) {
# Preliminaries --------------------------------------------------------------
# Check if input is an isobaricnormRes class object.
if (!inherits(isobaricnormRes_obj, "isobaricnormRes")) {
stop ("object must be of class 'isobaricnormRes'")
}
# Make sure palette is one of the RColorBrewer options if it is not NULL.
if (!is.null(palette)) {
if (!(palette %in% c("YlOrRd", "YlOrBr", "YlGnBu", "YlGn", "Reds","RdPu",
"Purples", "PuRd", "PuBuGn", "PuBu", "OrRd","Oranges",
"Greys", "Greens", "GnBu", "BuPu","BuGn","Blues",
"Set3", "Set2", "Set1", "Pastel2", "Pastel1", "Paired",
"Dark2", "Accent", "Spectral", "RdYlGn", "RdYlBu",
"RdGy", "RdBu", "PuOr","PRGn", "PiYG", "BrBG"))) {
# INCONCEIVABLE!!!
stop ("palette must be an RColorBrewer palette")
}
}
# extracting attributes from isobaricnormRes_obj
exp_cname = attr(isobaricnormRes_obj, "isobaric_info")$exp_cname
fdata_cname = attr(isobaricnormRes_obj, "cnames")$fdata_cname
edata_cname <- attr(isobaricnormRes_obj, "cnames")$edata_cname
# Transform the isobaricnormRes data frames into a format usable by ggplot2.
tall_data <- prime_iso(isonormRes = isobaricnormRes_obj,
exp_cname = exp_cname,
fdata_cname = fdata_cname,
edata_cname = edata_cname)
# Do all the tedious plot label crap.
xlabel <- if (is.null(x_lab)) "Reference Sample" else x_lab
ylabel <- if (is.null(y_lab)) "Log Abundance" else y_lab
plot_title <- if (is.null(title_lab))
"Reference Sample Profile" else
title_lab
legendLabel <- if (is.null(legend_lab)) "Sample" else legend_lab
# Create pretty plots --------------------------------------------------------
# If order is TRUE order the box plots by experiment name/value.
if (order == TRUE) {
xlabel <- if (is.null(x_lab)) exp_cname else x_lab
p <- ggplot2::ggplot(data = tall_data,
ggplot2::aes(x = .data[[exp_cname]],
y = values,
fill = .data[[exp_cname]]))
# Otherwise separate the box plots by sample name.
} else {
p <- ggplot2::ggplot(data = tall_data,
ggplot2::aes(x = .data[[fdata_cname]],
y = values,
fill = .data[[exp_cname]]))
}
# Want your plot to have a black and white background? As you wish.
# The black and white theme needs to come before the code that creates the box
# plot. If the theme_bw code follows the code that creates the box plot it
# will add the legend back to the graph (if legend_position = "none").
if (bw_theme == TRUE) p <- p + ggplot2::theme_bw()
# Create the box plot with all of the users input.
p <- p +
ggplot2::geom_boxplot() +
ggplot2::ggtitle(plot_title) +
ggplot2::xlab(xlabel) +
ggplot2::ylab(ylabel) +
ggplot2::labs(color = legendLabel) +
ggplot2::theme(
plot.title = ggplot2::element_text(size = title_lab_size),
axis.title.x = ggplot2::element_text(size = x_lab_size),
axis.title.y = ggplot2::element_text(size = y_lab_size),
axis.text.x = ggplot2::element_text(angle = x_lab_angle),
legend.position = legend_position
)
# Want to use beautiful non-default colors? As you wish.
if (!is.null(palette)) {
# Use the ColorBrewer color and create the legend title
p <- p +
ggplot2::scale_fill_brewer(palette = palette,
name = legendLabel)
}
# Want an interactive plot? As you wish.
if (interactive) p <- plotly::ggplotly(p)
return (p)
}
# Takes the isobaricnormRes object and returns a data frame in the correct
# format for plotting in ggplot2.
prime_iso <- function (isonormRes, exp_cname,
fdata_cname, edata_cname) {
# Find the column in e_data pertaining to the peptide IDs.
id_col <- which(names(isonormRes$e_data) == edata_cname)
# Stack the columns of e_data. This will include the sample names as an
# additional column.
tall_data <- stack(isonormRes$e_data[, -id_col])
# Change the name of the column containing sample names to match the
# corresponding column name in f_data.
names(tall_data)[2] <- fdata_cname
# Include the experiment column in tall_data.
tall_data <- dplyr::inner_join(tall_data,
isonormRes$f_data[, c(fdata_cname, exp_cname)],
by = fdata_cname)
# Extract the indices for each column in tall_data.
exp_cname_ind <- which(names(tall_data) == exp_cname)
fdata_cname_ind <- which(names(tall_data) == fdata_cname)
values_col_ind <- which(names(tall_data) == "values")
# Convert the experiment column into a factor.
tall_data[[exp_cname]] <- factor(tall_data[[exp_cname]])
# Return the tall data!
return (tall_data)
}
#' Plot nmrnormRes Object
#'
#' Creates a scatter plot for an S3 object of type 'nmrnormRes'
#'
#' @param nmrnormRes_obj an object of type nmrnormRes, created by
#' \code{\link{normalize_nmr}}
#' @param nmrData An nmrData object.
#' @param order_by A character string specifying a column in f_data by which to
#' order the samples.
#' @param color_by A character string specifying a column in f_data by which to
#' color the points.
#' @param interactive logical value. If TRUE produces an interactive plot.
#' @param x_lab character string specifying the x-axis label
#' @param y_lab character string specifying the y-axis label
#' @param x_lab_size integer value indicating the font size for the x-axis. The
#' default is 11.
#' @param y_lab_size integer value indicating the font size for the y-axis. The
#' default is 11.
#' @param x_lab_angle integer value indicating the angle of x-axis labels.
#' @param title_lab character string specifying the plot title.
#' @param title_lab_size integer value indicating the font size of the plot
#' title. The default is 14.
#' @param legend_lab character string specifying the legend title.
#' @param legend_position character string specifying the position of the
#' legend. Can be one of "right", "left", "top", "bottom", or "none". The
#' default is "none".
#' @param point_size integer specifying the size of the points. The default is
#' 2.
#' @param bw_theme logical value. If TRUE uses the ggplot2 black and white
#' theme.
#' @param palette character string indicating the name of the RColorBrewer
#' palette to use. For a list of available options see the details section in
#' \code{\link[RColorBrewer]{RColorBrewer}}.
#'
#' @return ggplot2 plot object if interactive is FALSE, or plotly plot object if
#' interactive is TRUE
#'
#' @examples
#' library(pmartRdata)
#' mynmr <- edata_transform(omicsData = nmr_identified_object, data_scale = "log2")
#' mynmrnorm <- normalize_nmr(omicsData = mynmr,
#' apply_norm = FALSE,
#' metabolite_name = "unkm1.53")
#' plot(mynmrnorm)
#'
#' mynmrnorm2 <- normalize_nmr(omicsData = mynmr,
#' apply_norm = FALSE,
#' sample_property_cname = "Concentration")
#' plot(mynmrnorm2)
#'
#' @rdname plot-nmrnormRes
#' @export
#'
plot.nmrnormRes <- function (nmrnormRes_obj, nmrData = NULL, order_by = NULL,
color_by = NULL, interactive = FALSE,
x_lab = NULL, y_lab = NULL, x_lab_size = 11,
y_lab_size = 11, x_lab_angle = 90,
title_lab = NULL, title_lab_size = 14,
legend_lab = NULL, legend_position = "none",
point_size = 2, bw_theme = TRUE, palette = NULL) {
# Preliminaries --------------------------------------------------------------
if (!inherits(nmrnormRes_obj, "nmrnormRes")) {
# My name is Evan Martin. You defiled pmart. Prepare to die.
stop("object must be of class 'nmrnormRes'")
}
if (!is.null(order_by)) {
# Farm boy, make sure an nmrData object is provided. As you wish.
if (is.null(nmrData)) {
# To the pain!
stop ("An nmrData object must be provided if order_by is not NULL.")
}
# Farm boy, make sure order_by exists in f_data. As you wish.
if (!order_by %in% names(nmrData$f_data)) {
# Do you hear that user? Those are the shrieking eels!
stop ("order_by must be a column in f_data.")
}
}
if (!is.null(color_by)) {
# Farm boy, make sure an nmrData object is provided. As you wish.
if (is.null(nmrData)) {
# To the pain!
stop ("An nmrData object must be provided if color_by is not NULL.")
}
# Farm boy, make sure color_by exists in f_data. As you wish.
if (!color_by %in% names(nmrData$f_data)) {
# Fezzik rip his arms off. Oh, you mean these column names.
stop ("color_by must be a column in f_data.")
}
}
# extracting attributes from nmrnormRes_obj
sample_property_cname <- attr(nmrnormRes_obj,
"nmr_info")$sample_property_cname
metabolite_name <- attr(nmrnormRes_obj, "nmr_info")$metabolite_name
fdata_cname <- attr(nmrnormRes_obj, "cnames")$fdata_cname
# organize nmrnormRes_obj
data <- data.frame(Sample = nmrnormRes_obj$Sample,
value = nmrnormRes_obj$value)
# Check if order_by is NULL and update the plot data object accordingly.
if (!is.null(order_by)) {
# Reorder the rows of data so the plot will be displayed in the correct
# order. Dread Pirate Roberts only likes plots that are ordered. What Dread
# Pirate Roberts doesn't like doesn't get plotted. Savvy?
#
# ggplot thinks it knows what is best for everyone in every situation. I
# disagree. However, we must follow ggplot convention. ggplot orders the
# data how they want to unless you explicitly give them the order you want.
# The code below is telling ggplot to shove it and to plot it in the order
# we want. BAM!!
data$Sample <- factor(
data$Sample,
levels = data$Sample[order(nmrData$f_data[, order_by])],
ordered = TRUE
)
}
# Check if color_by is NULL and update the plot data accordingly.
if (!is.null(color_by)) {
# Create factors to color by according to the input of color_by.
color_levels <- unique(factor(nmrData$f_data[[color_by]]))
# Farm boy, add a variable specifying the color for each point.
data$Color <- factor(nmrData$f_data[[color_by]],
levels = color_levels)
}
# Make sure palette is one of the RColorBrewer options if it is not NULL.
if (!is.null(palette)) {
if (!(palette %in% c("YlOrRd", "YlOrBr", "YlGnBu", "YlGn", "Reds","RdPu",
"Purples", "PuRd", "PuBuGn", "PuBu", "OrRd","Oranges",
"Greys", "Greens", "GnBu", "BuPu","BuGn","Blues",
"Set3", "Set2", "Set1", "Pastel2", "Pastel1", "Paired",
"Dark2", "Accent", "Spectral", "RdYlGn", "RdYlBu",
"RdGy", "RdBu", "PuOr","PRGn", "PiYG", "BrBG"))) {
# INCONCEIVABLE!!!
stop ("palette must be an RColorBrewer palette")
}
}
# Do all the tedious plot label crap.
xlabel <- if (is.null(x_lab)) "Sample ID" else x_lab
legendLabel <- if (is.null(legend_lab)) "Sample" else legend_lab
# Create y-axis and plot title labels when a reference metabolite is used.
if (!is.null(metabolite_name)) {
ylabel <- if (is.null(y_lab)) metabolite_name else y_lab
plot_title <- if (is.null(title_lab))
"Reference Metabolite Profile" else
title_lab
# Create y-axis and plot title labels when the sample property is used.
} else if (!is.null(sample_property_cname)) {
ylabel <- if (is.null(y_lab)) sample_property_cname else y_lab
plot_title <- if (is.null(title_lab))
"Sample Property Profile" else
title_lab
}
# Generate dazzling plots ----------------------------------------------------
# Create the plot skeleton according to the color_by argument.
if (!is.null(color_by)) {
p <- ggplot2::ggplot(data = data,
ggplot2::aes(x = Sample,
y = value,
color = Color))
# Check if palette is NULL or not. Hopefully it isn't so the plot will be
# created with colors other than the super hideous default ggplot2 colors.
if (!is.null(palette)) {
# Create a color from the color brewer package if a palette is provided.
colas <- RColorBrewer::brewer.pal(5, palette)
}
} else {
p <- ggplot2::ggplot(data = data,
ggplot2::aes(x = Sample,
y = value))
}
# Want your plot to have a black and white background? As you wish. The black
# and white theme needs to come before the code that creates the scatter plot.
# If the theme_bw code follows the code that creates the scatter plot it will
# add the legend back to the graph (if legend_position = "none").
if (bw_theme == TRUE) p <- p + ggplot2::theme_bw()
# Add the points and labels to the dazzling plot.
p <- p +
ggplot2::geom_point(size = point_size) +
ggplot2::ggtitle(plot_title) +
ggplot2::xlab(xlabel) +
ggplot2::ylab(ylabel) +
ggplot2::labs(color = legendLabel) +
ggplot2::theme(
plot.title = ggplot2::element_text(size = title_lab_size),
axis.title.x = ggplot2::element_text(size = x_lab_size),
axis.title.y = ggplot2::element_text(size = y_lab_size),
axis.text.x = ggplot2::element_text(angle = x_lab_angle, hjust = 1),
legend.position = legend_position
)
# Farm boy, make me a plot with beautiful colors? As you wish.
if (!is.null(palette)) {
# Use the ColorBrewer color and create the legend title
p <- p +
ggplot2::scale_color_brewer(palette = palette,
name = legendLabel)
}
# Farm boy, make me an interactive plot. As you wish.
if (interactive) p <- plotly::ggplotly(p)
return (p)
}
#' Plot SPANSRes Object
#'
#' For plotting an S3 object of type 'SPANSRes'
#'
#' @param SPANSRes_obj an object of the class 'SPANSRes', created by
#' \code{\link{spans_procedure()}}
#' @param interactive logical value. If TRUE produces an interactive plot.
#' @param x_lab character string specifying the x-axis label.
#' @param y_lab character string specifying the y-axis label.
#' @param x_lab_size integer value indicating the font size for the x-axis.
#' The default is 11.
#' @param y_lab_size integer value indicating the font size for the y-axis.
#' The default is 11.
#' @param x_lab_angle integer value indicating the angle of x-axis labels.
#' The default is NULL.
#' @param title_lab character string specifying the plot title
#' @param title_lab_size integer value indicating the font size of the plot
#' title. The default is 14.
#' @param legend_lab character string specifying the legend title
#' @param legend_position character string specifying the position of the
#' legend. Can be one of "right", "left", "top", "bottom", or "none". The
#' default is "none".
#' @param color_low character string specifying the color of the gradient for
#' low values.
#' @param color_high character string specifying the color of the gradient for
#' high values
#' @param bw_theme logical value. If TRUE uses the ggplot2 black and white theme.
#'
#' @return ggplot2 plot object if interactive is FALSE, or plotly plot object if
#' interactive is TRUE
#'
#' @examples
#' library(pmartRdata)
#' mypep <- edata_transform(omicsData = pep_object, data_scale = "log2")
#' mypep <- group_designation(omicsData = mypep, main_effects = "Phenotype")
#' myspans <- spans_procedure(omicsData = mypep)
#' plot(myspans)
#'
#' @rdname plot-SPANSRes
#'
#' @export
#'
plot.SPANSRes <- function (SPANSRes_obj, interactive = FALSE,
x_lab = NULL, y_lab = NULL, x_lab_size = 11,
y_lab_size = 11, x_lab_angle = NULL,
title_lab = NULL, title_lab_size = 14,
legend_lab = NULL, legend_position = "right",
color_low = NULL, color_high = NULL,
bw_theme = TRUE) {
# Preliminaries --------------------------------------------------------------
if (!inherits(SPANSRes_obj, "SPANSRes")) {
# Suffer the wrath of Dread Pirate Roberts!!!!!
stop("object must be of class 'SPANSRes'")
}
# plotting object with numeric SPANS_score, the normalization method, and a
# modified string specifying the subset method + parameters for that method
SPANSRes_obj <- SPANSRes_obj %>%
dplyr::mutate(ss_par = paste(subset_method, parameters, sep = " | "),
SPANS_score = as.numeric(SPANS_score)) %>%
dplyr::left_join(attr(SPANSRes_obj, "method_selection_pvals"),
by = c("subset_method",
"normalization_method",
"parameters"))
# Farm boy, fix all the problems. As you wish. Filter rows with the highest
# SPANS score. This subsetted/filtered data frame will be used to add points
# to the plot for the best scoring methods. The best methods are those with
# the highest SPANS_score. The slice_max function will select ALL rows where
# the highest score occurs.
da_best <- SPANSRes_obj %>%
dplyr::slice_max(SPANS_score)
# Do all the tedious plot label crap.
xlabel <- if (is.null(x_lab)) "Normalization Method" else x_lab
ylabel <- if (is.null(y_lab)) "Subset Parameters" else y_lab
plot_title <- if (is.null(title_lab)) NULL else title_lab
legendLabel <- if (is.null(legend_lab)) "Score" else legend_lab
# Produce magnificent plots --------------------------------------------------
p <- ggplot2::ggplot(data = SPANSRes_obj) +
ggplot2::geom_tile(ggplot2::aes(x = normalization_method,
y = ss_par,
alpha = 1),
color = 'black') +
ggplot2::geom_tile(ggplot2::aes(x = normalization_method,
y = ss_par,
fill = SPANS_score),
color = 'black') +
ggplot2::geom_point(data = da_best,
ggplot2::aes(x = normalization_method,
y = ss_par,
shape = '1')) +
ggplot2::scale_alpha_continuous(name = 'Not Scored',
labels = '') +
ggplot2::scale_shape_discrete(name = 'Best Scores',
labels = '') +
ggplot2::scale_fill_gradient(
low = if (is.null(color_low)) "#132B43" else color_low,
high = if (is.null(color_high)) "#56B1F7" else color_high,
) +
ggplot2::ggtitle(plot_title) +
ggplot2::xlab(xlabel) +
ggplot2::ylab(ylabel)
# Want the black and white theme? As you wish.
if (bw_theme) p <- p + ggplot2::theme_bw()
p <- p +
ggplot2::labs(fill = legendLabel) +
ggplot2::theme(
plot.title = ggplot2::element_text(size = title_lab_size),
axis.title.x = ggplot2::element_text(size = x_lab_size),
axis.title.y = ggplot2::element_text(size = y_lab_size),
axis.text.x = ggplot2::element_text(angle = x_lab_angle),
legend.position = legend_position,
panel.border = ggplot2::element_blank(),
panel.grid.major = ggplot2::element_blank(),
panel.grid.minor = ggplot2::element_blank(),
axis.line = ggplot2::element_blank(),
axis.ticks = ggplot2::element_blank()
)
# Want an interactive plot? As you wish.
if (interactive) {
p <- plotly::plot_ly(
SPANSRes_obj,
x = ~normalization_method,
y = ~ss_par,
z = ~SPANS_score,
hoverinfo = 'text',
text = ~paste('</br> F(-Log10(HSmPV)):',
F_log_HSmPV,
'</br> F(Log10(NSmPV)): ',
F_log_NSmPV,
'</br> Scale p-value: ',
scale_p_value,
'</br> Location p-value',
location_p_value),
colors = grDevices::colorRamp(
c(if (is.null(color_low)) "#132B43" else color_low,
if (is.null(color_high)) "#56B1F7" else color_high)
),
type = "heatmap") %>%
plotly::add_trace(x = da_best$normalization_method,
y = da_best$ss_par,
type = 'scatter',
mode = "markers",
marker = list(color = "black"),
name = "Top SPANS scores",
inherit = FALSE) %>%
plotly::colorbar(title = "SPANS score") %>%
plotly::layout(plot_bgcolor = 'black',
xaxis = list(title = "Normalization Method"),
yaxis = list(title = "Subset Method"),
showlegend = TRUE
)
}
return (p)
}
#' Plot naRes Object
#'
#' For plotting an S3 object of type 'naRes'
#'
#' @param naRes_obj list of two data frames, one containing the number of
#' missing values by sample, and the other containing missing values by
#' molecule
#' @param omicsData object of class 'pepData', 'proData', 'metabData',
#' 'lipidData', nmrData', or 'seqData', created by \code{\link{as.pepData}},
#' \code{\link{as.proData}}, \code{\link{as.metabData}},
#' \code{\link{as.lipidData}}, \code{\link{as.nmrData}}, or \code{\link{as.seqData}}, respectively.
#' @param plot_type character string specifying which type of plot to produce.
#' The two options are 'bar' or 'scatter'.
#' @param order_by A character string specifying a column in f_data by which to
#' order the samples.
#' @param color_by A character string specifying a column in f_data by which to
#' color the bars or the points depending on the \code{plot_type}.
#' @param interactive logical value. If TRUE produces an interactive plot.
#' @param x_lab_bar character string used for the x-axis label for the bar
#' plot
#' @param x_lab_scatter character string used for the x-axis label for the
#' scatter plot
#' @param y_lab_bar character string used for the y-axis label for the bar
#' plot
#' @param y_lab_scatter character string used for the y-axis label for the
#' scatter plot
#' @param x_lab_size integer value indicating the font size for the x-axis.
#' The default is 11.
#' @param y_lab_size integer value indicating the font size for the y-axis.
#' The default is 11.
#' @param x_lab_angle integer value indicating the angle of x-axis labels.
#' @param title_lab_bar character string used for the plot title when
#' \code{plot_type} is 'bar'.
#' @param title_lab_scatter character string used for the plot title when
#' \code{plot_type} is 'scatter'.
#' @param title_lab_size integer value indicating the font size of the plot
#' title. The default is 14.
#' @param legend_lab_bar character string specifying the legend title when
#' creating a bar plot.
#' @param legend_lab_scatter character string specifying the legend title when
#' creating a scatter plot.
#' @param legend_position character string specifying the position of the
#' legend. Can be one of "right", "left", "top", or "bottom". The default is