/
plotting.R
1463 lines (1318 loc) · 59 KB
/
plotting.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
############################################
# Aesthetics constants -----
############################################
.all_aes_names <- c("x", "y", "color", "shape", "size", "fill", "group")
.all_aes_values <- c("X", "Y", "ColorBy", "ShapeBy", "SizeBy", "FillBy", "GroupBy")
names(.all_aes_values) <- .all_aes_names
############################################
# Title and labels constants -----
############################################
.all_labs_names <- c(.all_aes_names, "title", "subtitle")
############################################
# Lasso constants -----
############################################
# Default behaviour
.lassoStartShape <- 22
.lassoWaypointShape <- 20
# If shape is being used for data aesthetics, fall back on size
.lassoStartSize <- 1.5
.lassoWaypointSize <- 0.25
#' Choose the plot type
#'
#' Define and execute commands to prepare X and/or Y for plotting, depending on whether they are categorical or continuous.
#' This mostly involves coercing categorical variables to factors.
#'
#' @param envir Environment containing a \code{plot.data} data.frame with \code{X} and \code{Y} fields.
#'
#' @return
#' A character vector is returned containing commands to perform calculations for each plot type
#' (or \code{NULL}, if no commands need to be executed).
#' All commands are also evaluated within \code{envir} to modify \code{plot.data}.
#'
#' A \code{plot.type} string is added to \code{envir}, indicating the type of plot that should be created
#' based on whether the x- and/or y-axes are categorical or continuous.
#'
#' @details
#' \code{envir} is effectively passed by reference, as the setup commands are executed in the environment by this function.
#'
#' @author Aaron Lun
#' @rdname INTERNAL_choose_plot_type
#' @seealso
#' \code{\link{.violin_setup}},
#' \code{\link{.square_setup}},
#' \code{\link{.generateDotPlotData}}
.choose_plot_type <- function(envir) {
group_X <- .is_groupable(envir$plot.data$X)
group_Y <- .is_groupable(envir$plot.data$Y)
if (!group_Y && !group_X) {
mode <- "scatter"
specific <- NULL
} else if (!group_Y) {
mode <- "violin"
specific <- .violin_setup(envir$plot.data, horizontal=FALSE)
} else if (!group_X) {
mode <- "violin_horizontal"
specific <- .violin_setup(envir$plot.data, horizontal=TRUE)
if (exists("plot.data.all", envir)) { # flipping plot.data.all as well, otherwise it becomes chaotic in .violin_plot().
specific <- c(specific,
"tmp <- plot.data.all$X;
plot.data.all$X <- plot.data.all$Y;
plot.data.all$Y <- tmp;")
}
} else {
mode <- "square"
specific <- .square_setup(envir$plot.data)
}
.textEval(specific, envir)
envir$plot.type <- mode
return(specific)
}
############################################
# Internal functions: downsampler ----
############################################
#' Downsampling commands
#'
#' Define and execute commands to downsample points for speed.
#'
#' @param param_choices An instance of a \linkS4class{DotPlot} class.
#' @param envir Environment containing a \code{plot.data} data.frame with \code{X} and \code{Y} fields.
#' @param priority Logical scalar indicating whether a \code{.priority} variable was generated by \code{\link{.prioritizeDotPlotData}}.
#' @param rescaled Logical scalar indicating whether a \code{.rescaled} variable was generated by \code{\link{.prioritizeDotPlotData}}.
#'
#' @details
#' Density-dependent downsampling for speed is performed in this function, based on \code{\link{subsetPointsByGrid}}.
#' \code{envir} is effectively passed by reference, as the setup commands are executed in the environment by this function.
#' A \code{plot.data.pre} data.frame is also added to \code{envir} to keep the pre-subsetted information, e.g., for use in \code{.violin_plot}.
#'
#' \code{priority} and \code{rescaled} are used to adjust the priority and resolution of downsampling.
#' See \code{?link{.prioritizeDotPlotData}} for details.
#'
#' @return
#' A character vector is returned containing commands to perform downsampling.
#' All commands are evaluated within \code{envir}.
#'
#' @author Aaron Lun
#' @rdname INTERNAL_downsample_points
#' @seealso
#' \code{\link{subsetPointsByGrid}}
.downsample_points <- function(param_choices, envir, priority=FALSE, rescaled=FALSE) {
if (slot(param_choices, .plotPointDownsample)) {
xtype <- "X"
ytype <- "Y"
plot_type <- envir$plot.type
if (plot_type == "square") {
xtype <- "jitteredX"
ytype <- "jitteredY"
} else if (plot_type == "violin" || plot_type == "violin_horizontal") {
xtype <- "jitteredX"
}
res <- slot(param_choices, .plotPointSampleRes)
subset.args <- sprintf("resolution=%i", res)
if (priority) {
if (rescaled) {
subset.args <- paste0(subset.args, "*.rescaled")
}
subset.args <- paste0(subset.args, ", grouping=.priority")
}
## If we color by sample name in a column-based plot, or by feature name
## in a row-based plot, we make sure to keep the selected column/row in
## the downsampling
color_choice <- slot(param_choices, .colorByField)
always_keep <- ""
if ((color_choice == .colorBySampNameTitle && is(param_choices, "ColumnDotPlot")) ||
(color_choice == .colorByFeatNameTitle && is(param_choices, "RowDotPlot"))) {
always_keep <- " | as.logical(plot.data$ColorBy)"
}
downsample_cmds <- c(
"plot.data.pre <- plot.data;",
sprintf(".subsetted <- subsetPointsByGrid(plot.data$%s, plot.data$%s, %s)", xtype, ytype, subset.args),
sprintf("plot.data <- plot.data[.subsetted%s,,drop=FALSE];", always_keep),
""
)
.textEval(downsample_cmds, envir)
downsample_cmds
} else {
NULL
}
}
############################################
# Internal functions: scatter plotter ----
############################################
#' Produce a scatter plot
#'
#' Generate (but not evaluate) commands to create a scatter plot of numeric X/Y.
#'
#' @param plot_data A data.frame containing all of the plotting information,
#' returned by \code{\link{.generateDotPlotData}} in \code{envir$plot.data}.
#' @param param_choices An instance of a \linkS4class{DotPlot} class.
#' @param x_lab A character label for the X axis.
#' Set to \code{NULL} to have no x-axis label.
#' @param y_lab A character label for the Y axis.
#' Set to \code{NULL} to have no y-axis label.
#' @param color_lab A character label for the color scale.
#' Set to \code{NULL} to have no color label.
#' @param shape_lab A character label for the shape scale.
#' Set to \code{NULL} to have no shape label.
#' @param size_lab A character label for the size scale.
#' Set to \code{NULL} to have no size label.
#' @param title A character title for the plot.
#' Set to \code{NULL} to have no title.
#' @param by_row A logical scalar specifying whether the plot deals with row-level metadata.
#' @param is_subsetted A logical scalar specifying whether \code{plot_data} was subsetted during \code{\link{.process_selectby_choice}}.
#' @param is_downsampled A logical scalar specifying whether \code{plot_data} was downsampled.
#'
#' @return A character vector of commands to be parsed and evaluated by \code{\link{.generateDotPlot}} to produce the scatter plot.
#'
#' @details
#' As described in \code{?\link{.generateDotPlot}}, the \code{.scatter_plot} function should only contain commands to generate the final ggplot object.
#'
#' \code{plot.data.all} will be used to define the plot boundaries when selecting points to restrict (see \code{?\link{.process_selectby_choice}}).
#' If there is no restriction and we are downsampling for speed, \code{plot.data.pre} will be used to define the boundaries.
#'
#' @author Kevin Rue-Albrecht, Aaron Lun.
#' @rdname INTERNAL_scatter_plot
#'
#' @seealso
#' \code{\link{.generateDotPlot}}
#'
#' @importFrom ggplot2 ggplot coord_cartesian theme_bw theme element_text geom_density_2d
.scatter_plot <- function(plot_data, param_choices,
x_lab, y_lab, color_lab, shape_lab, size_lab, title,
by_row=FALSE, is_subsetted=FALSE, is_downsampled=FALSE)
{
plot_cmds <- list()
plot_cmds[["ggplot"]] <- "dot.plot <- ggplot() +"
# Adding points to the plot.
color_set <- !is.null(plot_data$ColorBy)
shape_set <- slot(param_choices, .shapeByField) != .shapeByNothingTitle
size_set <- slot(param_choices, .sizeByField) != .sizeByNothingTitle
new_aes <- .buildAes(color=color_set, shape=shape_set, size=size_set,
alt=c(color=.set_colorby_when_none(param_choices)))
plot_cmds[["points"]] <- .create_points(param_choices, !is.null(plot_data$SelectBy),
new_aes, color_set, size_set)
# Defining the color commands.
color_scale_cmd <- .colorDotPlot(param_choices, plot_data$ColorBy)
guides_cmd <- .create_guides_command(param_choices, plot_data$ColorBy)
# Adding axes labels.
plot_cmds[["labs"]] <- .buildLabs(x=x_lab, y=y_lab, color=color_lab, shape=shape_lab, size=size_lab, title=title)
# Defining boundaries if zoomed.
bounds <- slot(param_choices, .zoomData)
if (length(bounds)) {
plot_cmds[["coord"]] <- sprintf(
"coord_cartesian(xlim=c(%s, %s), ylim=c(%s, %s), expand=FALSE) +", # FALSE, to get a literal zoom.
deparse(bounds["xmin"]), deparse(bounds["xmax"]),
deparse(bounds["ymin"]), deparse(bounds["ymax"])
)
} else {
full_data <- ifelse(is_subsetted, "plot.data.all", ifelse(is_downsampled, "plot.data.pre", "plot.data"))
plot_cmds[["coord"]] <- sprintf("coord_cartesian(xlim=range(%s$X, na.rm=TRUE),
ylim=range(%s$Y, na.rm=TRUE), expand=TRUE) +", full_data, full_data)
}
if (slot(param_choices, .contourAdd)) {
plot_cmds[["contours"]] <- sprintf("geom_density_2d(aes(x=X, y=Y), plot.data, colour='%s') +", slot(param_choices, .contourColor))
}
# Retain axes when no points are present.
if (nrow(plot_data) == 0 && is_subsetted) {
plot_cmds[["select_blank"]] <- "geom_blank(data=plot.data.all, inherit.aes=FALSE, aes(x=X, y=Y)) +"
}
# Adding further aesthetic elements.
plot_cmds[["scale_color"]] <- color_scale_cmd
plot_cmds[["guides"]] <- guides_cmd
plot_cmds[["theme_base"]] <- "theme_bw() +"
font_size <- slot(param_choices, .plotFontSize)
plot_cmds[["theme_custom"]] <- sprintf(
"theme(legend.position='%s', legend.box='vertical', legend.text=element_text(size=%s), legend.title=element_text(size=%s),
axis.text=element_text(size=%s), axis.title=element_text(size=%s), title=element_text(size=%s))",
tolower(slot(param_choices, .plotLegendPosition)),
font_size * .plotFontSizeLegendTextDefault,
font_size * .plotFontSizeLegendTitleDefault,
font_size * .plotFontSizeAxisTextDefault,
font_size * .plotFontSizeAxisTitleDefault,
font_size * .plotFontSizeTitleDefault)
unlist(plot_cmds)
}
############################################
# Internal functions: violin plotter ----
############################################
#' Produce a violin plot
#'
#' Generate (but not evaluate) the commands required to produce a vertical or
#' horizontal violin plot.
#'
#' @param plot_data A data.frame containing all of the plotting information, returned by \code{\link{.generateDotPlotData}} in \code{envir$plot.data}.
#' @param param_choices An instance of a \linkS4class{DotPlot} class.
#' @param x_lab A character label for the X axis.
#' Set to \code{NULL} to have no x-axis label.
#' @param y_lab A character label for the Y axis.
#' Set to \code{NULL} to have no y-axis label.
#' @param color_lab A character label for the color scale.
#' Set to \code{NULL} to have no color label.
#' @param shape_lab A character label for the shape scale.
#' Set to \code{NULL} to have no shape label.
#' @param size_lab A character label for the size scale.
#' Set to \code{NULL} to have no size label.
#' @param title A character title for the plot.
#' Set to \code{NULL} to have no title.
#' @param horizontal A logical value that indicates whether violins should be drawn horizontally
#' (i.e., Y axis categorical and X axis continuous).
#' @param by_row A logical scalar specifying whether the plot deals with row-level metadata.
#' @param is_subsetted A logical scalar specifying whether \code{plot_data} was subsetted during \code{\link{.process_selectby_choice}}.
#' @param is_downsampled A logical scalar specifying whether \code{plot_data} was downsampled.
#'
#' @return
#' For \code{\link{.violin_setup}}, a character vector of commands to be parsed
#' and evaluated by \code{\link{.generateDotPlotData}} to set up the
#' required fields.
#'
#' For \code{.violin_plot}, a character vector of commands to be parsed
#' and evaluated by \code{\link{.generateDotPlot}} to produce the violin plot.
#'
#' @details
#' Any commands to modify \code{plot.data} in preparation for creating a violin plot should be placed in \code{\link{.violin_setup}},
#' to be called by \code{\link{.generateDotPlotData}}.
#' This includes swapping of X and Y variables when \code{horizontal=TRUE}, and adding of horizontal/vertical jitter to points.
#'
#' As described in \code{?\link{.generateDotPlot}}, the \code{.violin_plot} function should only contain commands to generate the final ggplot object.
#'
#' \code{plot.data.all} will be used to define the y-axis boundaries (or x-axis boundaries when \code{horizontal=TRUE}).
#' This ensures consistent plot boundaries when selecting points to restrict (see \code{?\link{.process_selectby_choice}}),
#' or when downsampling for speed (see \code{?\link{.generateDotPlot}}.
#'
#' Similarly, \code{envir$plot.data.pre} will be used to create the violins (see \code{\link{.generateDotPlot}}).
#' This ensures consistent violins when downsampling for speed - otherwise the violins will be computed from the downsampled set of points.
#'
#' @author Kevin Rue-Albrecht, Aaron Lun, Charlotte Soneson.
#' @rdname INTERNAL_violin_plot
#'
#' @seealso
#' \code{\link{.generateDotPlotData}},
#' \code{\link{.generateDotPlot}}
#'
#' @importFrom ggplot2 ggplot geom_violin coord_cartesian theme_bw theme
#' coord_flip scale_x_discrete scale_y_discrete
.violin_plot <- function(plot_data, param_choices,
x_lab, y_lab, color_lab, shape_lab, size_lab, title,
by_row=FALSE, is_subsetted=FALSE, is_downsampled=FALSE, horizontal=FALSE)
{
plot_cmds <- list()
plot_cmds[["ggplot"]] <- "dot.plot <- ggplot() +" # do NOT put aes here, it does not play nice with shiny brushes.
plot_cmds[["violin"]] <- sprintf(
"geom_violin(%s, alpha=0.2, data=%s, scale='width', width=0.8) +",
.buildAes(color=FALSE, group=TRUE),
ifelse(is_downsampled, "plot.data.pre", "plot.data")
)
# Adding the points to the plot (with/without point selection).
color_set <- !is.null(plot_data$ColorBy)
shape_set <- slot(param_choices, .shapeByField) != .shapeByNothingTitle
size_set <- slot(param_choices, .sizeByField) != .sizeByNothingTitle
new_aes <- .buildAes(color=color_set, shape=shape_set, size=size_set,
alt=c(x="jitteredX", color=.set_colorby_when_none(param_choices)))
plot_cmds[["points"]] <- .create_points(param_choices, !is.null(plot_data$SelectBy),
new_aes, color_set, size_set)
# Defining the color commands.
color_scale_cmd <- .colorDotPlot(param_choices, plot_data$ColorBy, x_aes="jitteredX")
guides_cmd <- .create_guides_command(param_choices, plot_data$ColorBy)
# Adding axis labels.
if (horizontal) {
tmp <- y_lab
y_lab <- x_lab
x_lab <- tmp
}
plot_cmds[["labs"]] <- .buildLabs(x=x_lab, y=y_lab, color=color_lab, shape=shape_lab, size=size_lab, title=title)
# Defining boundaries if zoomed. This requires some finesse to deal with horizontal plots,
# where the point selection is computed on the flipped coordinates.
bounds <- slot(param_choices, .zoomData)
if (horizontal) {
coord_cmd <- "coord_flip"
if (length(bounds)) {
names(bounds) <- c(xmin="ymin", xmax="ymax", ymin="xmin", ymax="xmax")[names(bounds)]
}
} else {
coord_cmd <- "coord_cartesian"
}
if (length(bounds)) {
# Ensure zoom preserves the data points and width ratio of visible groups
bounds["xmin"] <- ceiling(bounds["xmin"]) - 0.5
bounds["xmax"] <- floor(bounds["xmax"]) + 0.5
plot_cmds[["coord"]] <- sprintf(
"%s(xlim=c(%s, %s), ylim=c(%s, %s), expand=FALSE) +", # FALSE, to get a literal zoom.
coord_cmd, deparse(bounds["xmin"]), deparse(bounds["xmax"]),
deparse(bounds["ymin"]), deparse(bounds["ymax"])
)
} else {
plot_cmds[["coord"]] <- sprintf("%s(ylim=range(%s$Y, na.rm=TRUE), expand=TRUE) +",
coord_cmd, ifelse(is_subsetted, "plot.data.all", ifelse(is_downsampled, "plot.data.pre", "plot.data"))
)
}
plot_cmds[["scale_color"]] <- color_scale_cmd
plot_cmds[["guides"]] <- guides_cmd
# Retain axes when no points are generated.
if (nrow(plot_data) == 0 && is_subsetted) {
plot_cmds[["select_blank"]] <- "geom_blank(data=plot.data.all, inherit.aes=FALSE, aes(x=X, y=Y)) +"
}
# Preserving the x-axis range when no zoom is applied.
# This applies even for horizontal violin plots, as this command is executed internally before coord_flip().
scale_x_cmd <- "scale_x_discrete(drop=FALSE%s) +"
if (!length(bounds)) {
scale_x_extra <- ""
} else {
# Restrict axis ticks to visible levels
scale_x_extra <- sprintf(
", breaks=levels(plot.data$X)[%i:%i]",
ceiling(bounds["xmin"]), floor(bounds["xmax"]))
}
plot_cmds[["scale_x"]] <- sprintf(scale_x_cmd, scale_x_extra)
plot_cmds[["theme_base"]] <- "theme_bw() +"
font_size <- slot(param_choices, .plotFontSize)
plot_cmds[["theme_custom"]] <- sprintf(
"theme(legend.position='%s', legend.text=element_text(size=%s),
legend.title=element_text(size=%s), legend.box='vertical',
axis.text.x=element_text(angle=90, size=%s, hjust=1, vjust=0.5),
axis.text.y=element_text(size=%s),
axis.title=element_text(size=%s), title=element_text(size=%s))",
tolower(slot(param_choices, .plotLegendPosition)),
font_size * .plotFontSizeLegendTextDefault,
font_size * .plotFontSizeLegendTitleDefault,
font_size * .plotFontSizeAxisTextDefault,
font_size * .plotFontSizeAxisTextDefault,
font_size * .plotFontSizeAxisTitleDefault,
font_size * .plotFontSizeTitleDefault)
unlist(plot_cmds)
}
#' @rdname INTERNAL_violin_plot
.violin_setup <- function(plot_data, horizontal=FALSE) {
setup_cmds <- list()
# Switching X and Y axes if we want a horizontal violin plot.
if (horizontal) {
setup_cmds[["swap"]] <- c("tmp <- plot.data$X;
plot.data$X <- plot.data$Y;
plot.data$Y <- tmp;")
}
setup_cmds[["group"]] <- "plot.data$GroupBy <- plot.data$X;"
# Handling the specification of the jitter-by-group argument.
groupvar <- ""
if (!is.null(plot_data$FacetRow) || !is.null(plot_data$FacetColumn)) {
groupvar <- character(0)
if (!is.null(plot_data$FacetRow)) {
groupvar <- c(groupvar, "FacetRow=plot.data$FacetRow")
}
if (!is.null(plot_data$FacetColumn)) {
groupvar <- c(groupvar, "FacetColumn=plot.data$FacetColumn")
}
groupvar <- paste0("\n list(", paste(groupvar, collapse=", "), "),")
}
# Figuring out the jitter. This is done ahead of time to guarantee the
# same results regardless of the subset used for point selection. Note adjust=1
# for consistency with geom_violin (differs from geom_quasirandom default).
setup_cmds[["seed"]] <- "set.seed(100);"
setup_cmds[["calcX"]] <- sprintf(
"plot.data$jitteredX <- iSEE::jitterViolinPoints(plot.data$X, plot.data$Y, %s
width=0.4, varwidth=FALSE, adjust=1,
method='quasirandom', nbins=NULL);", groupvar)
unlist(setup_cmds)
}
############################################
# Internal functions: rectangle plotter ----
############################################
#' Produce a square plot
#'
#' Generate (but not evaluate) the commands required to produce a square plot.
#'
#' @param plot_data A data.frame containing all of the plotting information,
#' returned by \code{\link{.generateDotPlotData}} in \code{envir$plot.data}.
#' @param param_choices An instance of a \linkS4class{DotPlot} class.
#' @param x_lab A character label for the X axis.
#' Set to \code{NULL} to have no x-axis label.
#' @param y_lab A character label for the Y axis.
#' Set to \code{NULL} to have no y-axis label.
#' @param color_lab A character label for the color scale.
#' Set to \code{NULL} to have no color label.
#' @param title A character title for the plot.
#' Set to \code{NULL} to have no title.
#' @param by_row Ignored argument, only provided for consistency with \code{.scatter_plot}.
#' @param is_subsetted A logical scalar specifying whether \code{plot_data} was subsetted during \code{\link{.process_selectby_choice}}.
#' @param is_downsampled Ignored argument, only provided for consistency with \code{.scatter_plot}.
#' @param shape_lab A character label for the shape scale.
#' Set to \code{NULL} to have no shape label.
#' @param size_lab A character label for the size scale.
#' Set to \code{NULL} to have no size label.
#'
#' @return
#' For \code{\link{.square_setup}}, a character vector of commands to be parsed and evaluated by \code{\link{.generateDotPlotData}} to set up the required fields.
#'
#' For \code{.square_plot}, a character vector of commands to be parsed and evaluated by \code{\link{.generateDotPlot}} to produce the square plot.
#'
#' @details
#' Any commands to modify \code{plot.data} in preparation for creating a square plot should be placed in \code{\link{.square_setup}}.
#' This function will subsequently be called by \code{\link{.generateDotPlotData}}.
#'
#' The square plot is set up so that the widths on the x-axis are constant when there is only one y-axis level.
#' This means that the dimensions of the squares on the y-axis are directly comparable, without any need to compare areas.
#' Similarly, the widths on the y-axis default are constant when there is only one x-axis level.
#'
#' As described in \code{?\link{.generateDotPlot}}, the \code{.square_plot} function should only contain commands to generate the final ggplot object.
#'
#' @author Kevin Rue-Albrecht, Aaron Lun, Charlotte Soneson.
#' @rdname INTERNAL_square_plot
#'
#' @seealso
#' \code{\link{.generateDotPlotData}},
#' \code{\link{.generateDotPlot}}
#'
#' @importFrom ggplot2 ggplot geom_tile coord_cartesian theme_bw theme
#' scale_x_discrete scale_y_discrete guides
.square_plot <- function(plot_data, param_choices,
x_lab, y_lab, color_lab, shape_lab, size_lab, title,
by_row=FALSE, is_subsetted=FALSE, is_downsampled=FALSE)
{
plot_cmds <- list()
plot_cmds[["ggplot"]] <- "dot.plot <- ggplot(plot.data) +"
plot_cmds[["tile"]] <-
"geom_tile(aes(x=X, y=Y, height=2*YWidth, width=2*XWidth, group=interaction(X, Y)),
summary.data, color='black', alpha=0, size=0.5) +"
# Adding the points to the plot (with/without point selection).
color_set <- !is.null(plot_data$ColorBy)
shape_set <- slot(param_choices, .shapeByField) != .shapeByNothingTitle
size_set <- slot(param_choices, .sizeByField) != .sizeByNothingTitle
new_aes <- .buildAes(color=color_set, shape=shape_set, size=size_set,
alt=c(x="jitteredX", y="jitteredY", color=.set_colorby_when_none(param_choices)))
plot_cmds[["points"]] <- .create_points(param_choices, !is.null(plot_data$SelectBy),
new_aes, color_set, size_set)
# Defining the color commands.
color_scale_cmd <- .colorDotPlot(param_choices, plot_data$ColorBy, x_aes="jitteredX", y_aes="jitteredY")
guides_cmd <- .create_guides_command(param_choices, plot_data$ColorBy)
# Adding the commands to color the points and the point selection area (NULL if undefined).
plot_cmds[["scale_color"]] <- color_scale_cmd
# Adding the commands to color the points and the point selection area (NULL if undefined).
plot_cmds[["guides"]] <- guides_cmd
# Creating labels.
plot_cmds[["labs"]] <- .buildLabs(x=x_lab, y=y_lab, color=color_lab, shape=shape_lab, size=size_lab, title=title)
# Defining boundaries if zoomed.
bounds <- slot(param_choices, .zoomData)
if (length(bounds)) {
# Ensure zoom preserves the data points and width ratio of visible groups
bounds["xmin"] <- ceiling(bounds["xmin"]) - 0.5
bounds["xmax"] <- floor(bounds["xmax"]) + 0.5
bounds["ymin"] <- ceiling(bounds["ymin"]) - 0.5
bounds["ymax"] <- floor(bounds["ymax"]) + 0.5
plot_cmds[["coord"]] <- sprintf(
"coord_cartesian(xlim=c(%s, %s), ylim=c(%s, %s), expand=FALSE) +",
deparse(bounds["xmin"]), deparse(bounds["xmax"]),
deparse(bounds["ymin"]), deparse(bounds["ymax"])
)
}
scale_x_cmd <- "scale_x_discrete(drop=FALSE%s) +"
scale_y_cmd <- "scale_y_discrete(drop=FALSE%s) +"
if (!length(bounds)) {
scale_x_extra <- ""
scale_y_extra <- ""
} else {
# Restrict axis ticks to visible levels
scale_x_extra <- sprintf(
", breaks=levels(plot.data$X)[%i:%i]",
ceiling(bounds["xmin"]), floor(bounds["xmax"]))
scale_y_extra <- sprintf(
", breaks=levels(plot.data$Y)[%i:%i]",
ceiling(bounds["ymin"]), floor(bounds["ymax"]))
}
plot_cmds[["scale_x"]] <- sprintf(scale_x_cmd, scale_x_extra)
plot_cmds[["scale_y"]] <- sprintf(scale_y_cmd, scale_y_extra)
# Retain axes when no points are present.
if (nrow(plot_data) == 0 && is_subsetted) {
plot_cmds[["select_blank"]] <- "geom_blank(data=plot.data.all, inherit.aes=FALSE, aes(x=X, y=Y)) +"
}
# Do not display the size legend (saves plot space, as well)
plot_cmds[["theme_base"]] <- "theme_bw() +"
font_size <- slot(param_choices, .plotFontSize)
plot_cmds[["theme_custom"]] <- sprintf("theme(legend.position='%s', legend.text=element_text(size=%s),
legend.title=element_text(size=%s), legend.box='vertical',
axis.text.x=element_text(angle=90, size=%s, hjust=1, vjust=0.5),
axis.text.y=element_text(size=%s),
axis.title=element_text(size=%s), title=element_text(size=%s))",
tolower(slot(param_choices, .plotLegendPosition)),
font_size * .plotFontSizeLegendTextDefault,
font_size * .plotFontSizeLegendTitleDefault,
font_size * .plotFontSizeAxisTextDefault,
font_size * .plotFontSizeAxisTextDefault,
font_size * .plotFontSizeAxisTitleDefault,
font_size * .plotFontSizeTitleDefault)
unlist(plot_cmds)
}
#' @rdname INTERNAL_square_plot
#' @importFrom stats runif
.square_setup <- function(plot_data) {
setup_cmds <- list()
# Handling the specification of the jitter-by-group argument.
groupvar <- ""
if (!is.null(plot_data$FacetRow) || !is.null(plot_data$FacetColumn)) {
groupvar <- character(0)
if (!is.null(plot_data$FacetRow)) {
groupvar <- c(groupvar, "FacetRow=plot.data$FacetRow")
}
if (!is.null(plot_data$FacetColumn)) {
groupvar <- c(groupvar, "FacetColumn=plot.data$FacetColumn")
}
groupvar <- paste0(",\n list(", paste(groupvar, collapse=", "), ")")
}
# Setting the seed to ensure reproducible results.
setup_cmds[["jitter"]] <- sprintf("set.seed(100);
j.out <- iSEE:::jitterSquarePoints(plot.data$X, plot.data$Y%s);
summary.data <- j.out$summary;
plot.data$jitteredX <- j.out$X;
plot.data$jitteredY <- j.out$Y;", groupvar)
unlist(setup_cmds)
}
############################################
# Internal functions: coloring ----
############################################
#' Set a default variable to color by
#'
#' Specify a variable in \code{plot.data} to color by when \code{ColorBy="None"}.
#' Typically used for plots that have some sensible default coloring scheme.
#'
#' @param x A \linkS4class{DotPlot} instance.
#'
#' @return A string containing the variable name, if \code{ColorBy="None"}; otherwise \code{NULL}.
#'
#' @details
#' This function is simply a utility to avoid having to write the conditionals in each of the plotting functions above.
#'
#' @author Aaron Lun
#'
#' @rdname INTERNAL_set_colorby_when_none
.set_colorby_when_none <- function(x) {
if (slot(x, .colorByField)==.colorByNothingTitle) {
.colorByNoneDotPlotField(x)
} else {
NULL
}
}
#' Choose between discrete and continuous color scales
#'
#' Generates a ggplot \code{color_scale} command depending on the number of
#' levels in the coloring variable.
#'
#' @param command A string containing an ExperimentColorMap accessor.
#' @param choice An argument to pass to the accessor in \code{command} to
#' specify the colormap to use.
#' @param colorby A vector of values to color points by, taken from
#' \code{plot.data$ColorBy} in upstream functions.
#'
#' @return A string containing an appropriate ggplot \code{color_scale}
#' command.
#'
#' @details
#' The appropriate ggplot coloring command will depend on whether
#' \code{colorby} is categorical or not.
#' If it is, \code{\link{scale_color_manual}} is used with the appropriate
#' number of levels.
#' Otherwise, \code{\link{scale_color_gradientn}} is used.
#' The \code{discrete=} argument of the accessor in \code{command} will also
#' be set appropriately.
#'
#' @author Kevin Rue-Albrecht, Aaron Lun, Charlotte Soneson.
#' @rdname INTERNAL_create_color_scale
#' @seealso
#' \code{\link{.colorDotPlot,RowDotPlot-method}},
#' \code{\link{.colorDotPlot,ColumnDotPlot-method}}
#'
#' @importFrom ggplot2 scale_color_manual scale_fill_manual
#' scale_color_gradientn scale_fill_gradientn
.create_color_scale <- function(command, choice, colorby) {
discrete_color <- is.factor(colorby)
if (discrete_color) {
ncolors <- nlevels(colorby)
} else {
ncolors <- 21L
}
cm_cmd <- sprintf(
"%s(colormap, %s, discrete=%s)(%i)",
command, choice, discrete_color, ncolors)
if (discrete_color){
return(c(
sprintf(
"scale_color_manual(values=%s, na.value='grey50', drop=FALSE) +",
cm_cmd),
sprintf(
"scale_fill_manual(values=%s, na.value='grey50', drop=FALSE) +",
cm_cmd)))
} else {
return(c(
sprintf(
"scale_color_gradientn(colors=%s, na.value='grey50', limits=range(plot.data$ColorBy, na.rm=TRUE)) +",
cm_cmd)#,
# sprintf(
# "scale_fill_gradientn(colors=%s, na.value='grey50') +",
# cm_cmd)
))
}
}
#' Override point size in the plot legend
#'
#' Conditionally generates a ggplot `guides` command if a custom point size is requested for the plot legend,
#' when the coloring covariate is discrete.
#'
#' @param x A [DotPlot-class] instance.
#' @param colorby A vector of values to color points by, taken from
#' \code{plot.data$ColorBy} in upstream functions.
#'
#' @return A string containing an appropriate ggplot \code{color_scale}
#' command, or `NULL`.
#'
#' @details
#' The appropriate ggplot coloring command will depend on whether
#' \code{colorby} is categorical or not.
#' If it is, and the point size for the legend and the plot are different ,
#' the function returns a `ggplot2::guides()` command that overrides the point size of the legend with the requested value.
#' Otherwise, `NULL` is returned.
#'
#' @author Kevin Rue-Albrecht
#' @rdname INTERNAL_create_guides_command
#'
#' @importFrom ggplot2 guides guide_legend
.create_guides_command <- function(x, colorby) {
discrete_color <- is.factor(colorby)
legend_size <- slot(x, .legendPointSize)
point_size <- slot(x, .plotPointSize)
custom_point_size <- !identical(legend_size, point_size)
if (custom_point_size && discrete_color) {
sprintf(
"guides(colour = guide_legend(override.aes = list(size=%i)), fill = guide_legend(override.aes = list(size=%i))) +",
legend_size, legend_size
)
} else {
NULL
}
}
############################################
# Internal functions: Point selection ----
############################################
#' Add points to plot
#'
#' Generate ggplot commands to control the appearance of data points while
#' accounting for a point selection effect, if active.
#'
#' @param param_choices An instance of a \linkS4class{DotPlot} class.
#' @param selected A logical scalar indicating whether any points were
#' selected on the transmitting plot, via a Shiny brush or lasso path.
#' @param aes A string containing the ggplot aesthetic instructions.
#' @param color A logical scalar indicating whether coloring information is
#' already included in the \code{aes}.
#' @param size A logical scaler indicating whether sizing information is already
#' included in the \code{aes}.
#'
#' @return A character vector containing ggplot commands to add points
#' to the plot.
#'
#' @details
#' Addition of point commands is done via \code{geom_point} on the
#' X/Y coordinates (in the \code{plot.data} of the evaluation environment).
#' This involves some work to highlight selected data points.
#' Any color specifications are passed in via \code{aes}.
#'
#' A separate \code{selected} argument is necessary here, despite the fact
#' that most point selection information can be retrieved from
#' \code{param_choices},
#' This is because \code{param_choices} does not contain any information on
#' whether the transmitter actually contains a selection of points.
#' If no Shiny select or closed lasso path is defined in the transmitter,
#' \code{selected=FALSE} and the default appearance of the points is used.
#'
#' @author Kevin Rue-Albrecht, Aaron Lun.
#' @rdname INTERNAL_create_points
#' @seealso
#' \code{.scatter_plot},
#' \code{.violin_plot},
#' \code{.square_plot}
#'
#' @importFrom ggplot2 geom_point geom_blank
.create_points <- function(param_choices, selected, aes, color, size) {
plot_cmds <- list()
# If there is already coloring information available in the aes, don't add an
# additional color= statement to the geom_point() command, since this will
# overrule the one given in aes().
if (color || !is.null(.set_colorby_when_none(param_choices))) {
default_color <- ""
} else {
default_color <- sprintf(", color='%s'", slot(param_choices, .colorByDefaultColor))
}
## If there is already size information available in the aes, don't add an
## additional size=statement to the geom_point() command.
if (size) {
common_size <- ""
} else {
common_size <- sprintf(", size=%s", slot(param_choices, .plotPointSize))
}
if (selected && (select_alpha <- slot(param_choices, .selectTransAlpha)) < 1) {
plot_cmds[["select_other"]] <- sprintf(
"geom_point(%s, subset(plot.data, !SelectBy), alpha=%.2f%s%s) +",
aes, select_alpha, default_color, common_size
)
plot_cmds[["select_alpha"]] <- sprintf(
"geom_point(%s, subset(plot.data, SelectBy)%s%s) +",
aes, default_color, common_size
)
} else {
plot_cmds[["point"]] <- sprintf(
"geom_point(%s, alpha=%s, plot.data%s%s) +",
aes, slot(param_choices, .plotPointAlpha), default_color,
common_size
)
}
unlist(plot_cmds)
}
############################################
# Internal functions: aesthetics ----
############################################
#' Generate ggplot aesthetic instructions
#'
#' @param x A \code{logical} that indicates whether to enable \code{x} in the
#' aesthetic instructions (default: \code{TRUE}).
#' @param y A \code{logical} that indicates whether to enable \code{y} in the
#' aesthetic instructions (default: \code{TRUE}).
#' @param color A \code{logical} that indicates whether to enable
#' \code{color} in the aesthetic instructions (default: \code{FALSE}).
#' @param shape A \code{logical} that indicates whether to enable
#' \code{shape} in the aesthetic instructions (default: \code{FALSE}).
#' @param size A \code{logical} that indicates whether to enable
#' \code{size} in the aesthetic instructions (default: \code{FALSE}).
#' @param fill A \code{logical} that indicates whether to enable
#' \code{fill} in the aesthetic instructions (default: \code{FALSE}).
#' @param group A \code{logical} that indicates whether to enable
#' \code{group} in the aesthetic instructions (default: \code{FALSE}).
#' @param alt Alternative aesthetics, supplied as a named character vector.
#'
#' @return Aesthetic instructions for \code{\link{ggplot}} as a character
#' value.
#'
#' @author Kevin Rue-Albrecht
#' @name aes-utils
#' @export
#'
#' @importFrom ggplot2 aes
#'
#' @examples
#' .buildAes()
.buildAes <- function(
x=TRUE, y=TRUE, color=FALSE, shape=FALSE, size=FALSE, fill=FALSE,
group=FALSE, alt=NULL) {
active_aes <- .all_aes_values[c(x, y, color, shape, size, fill, group)]
if (!is.null(alt)) {
active_aes <- c(active_aes, alt)
active_aes <- active_aes[!duplicated(names(active_aes), fromLast=TRUE)]
}
aes_specs <- mapply(
FUN=.make_single_aes, names(active_aes), active_aes, USE.NAMES=FALSE)
aes_specs <- paste(aes_specs, collapse=", ")
return(sprintf("aes(%s)", aes_specs))
}
#' Generate a single aesthetic instruction for ggplot
#'
#' @param name The name of a ggplot aesthetic.
#' @param value The name of a column in the plot data that will be mapped to
#' the aesthetic declared in \code{name}.
#'
#' @return A character value of the form \code{name=value}.
#'
#' @author Kevin Rue-Albrecht
#' @rdname INTERNAL_make_single_aes
#' @seealso
#' \code{\link{.buildAes}}.
.make_single_aes <- function(name, value){
sprintf("%s=%s", name, value)
}
#' Generate ggplot title and label instructions
#'
#' @param x The character label for the horizontal axis.
#' @param y x The character label for the vertical axis.
#' @param color The character title for the color scale legend.
#' @param shape The character title for the point shape legend.
#' @param size The character title for the point size legend.
#' @param fill The character title for the color fill legend.
#' @param group The character title for the group legend.
#' @param title The character title for the plot title.
#' @param subtitle The character title for the plot subtitle
#'
#' @details
#' If any argument is \code{NULL}, the corresponding label is not set.
#'
#' @return Title and label instructions for \code{\link{ggplot}} as a character value.
#'
#' @author Kevin Rue-Albrecht
#' @rdname labs-utils
#' @export
#'
#' @importFrom ggplot2 labs
#' @examples
#' cat(.buildLabs(y = "Title for Y axis", color = "Color label"))
.buildLabs <- function(x=NULL, y=NULL, color=NULL, shape=NULL, size=NULL, fill=NULL, group=NULL, title=NULL, subtitle=NULL){
labs_specs <- list(x, y, color, shape, size, fill, group, title, subtitle)
names(labs_specs) <- .all_labs_names
labs_specs <- labs_specs[lengths(labs_specs)>0L]
if (identical(length(labs_specs), 0L)){
return(NULL)
}
labs_specs <- mapply(FUN=.make_single_lab, names(labs_specs), labs_specs, USE.NAMES=FALSE)
labs_specs <- paste(labs_specs, collapse=", ")
return(sprintf("labs(%s) +", labs_specs))
}
#' Generate a single title or label instruction for ggplot
#'
#' @param name The name of a ggplot label.
#' @param value A character value for the title or label declared in
#' \code{name}.
#'
#' @return A character value of the form \code{name=value}.
#'
#' @author Kevin Rue-Albrecht
#' @rdname INTERNAL_make_single_lab
#' @seealso
#' \code{\link{.buildLabs}}.
.make_single_lab <- function(name, value){
sprintf("%s=%s", name, deparse(value))
}
############################################
# Internal functions: grouping ----
############################################
#' Coerce data to a specific type
#'
#' This function ensures that a specific column of the \code{plot.data} data.frame is either a numeric or factor.
#' If that is not the case, it returns a command (as a string) that coerces the column into the desired type.
#'
#' @param values Input vector that must be coerced to \code{numeric}.
#' @param field Column name in the \code{plot.data} data.frame that contains \code{values}.
#' @param max_levels Integer scalar specifying the maximum number unique values for \code{x} to be considered as categorical.
#' @param df String containing the variable name of the data.frame containing the plotting data.
#'
#' @return A command that coerces the plot data.frame column to the specified type, or \code{NULL} if no coercion is required.
#'
#' @author Kevin Rue-Albrecht
#' @rdname INTERNAL_coerce_type
#' @seealso
#' \code{\link{.generateDotPlot}}.
.coerce_type <- function(values, field, max_levels=Inf, df="plot.data") {
if (!.is_groupable(values, max_levels)) {
if (!is.numeric(values)) {
warning("covariate has too many unique values, coercing to numeric")
col_var <- sprintf("%s$%s", df, field)
if (!is.factor(values)) {
col_var <- sprintf("as.factor(%s)", col_var)
}
return(sprintf("%s$%s <- as.numeric(%s);", df, field, col_var))
}
} else {
if (!is.factor(values)) {
return(sprintf('%s[["%s"]] <- factor(%s[["%s"]]);', df, field, df, field))
}
}
return(NULL)
}