-
Notifications
You must be signed in to change notification settings - Fork 37
/
Copy pathanimint.R
2174 lines (2045 loc) · 81.7 KB
/
animint.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
#' Convert a ggplot to a list.
#' @param meta environment with previously calculated plot data, and a new plot to parse, already stored in plot and plot.name.
#' @return nothing, info is stored in meta.
#' @export
#' @import ggplot2 plyr
parsePlot <- function(meta){
## adding data and mapping to each layer from base plot, if necessary
for(layer.i in seq_along(meta$plot$layers)) {
## if data is not specified, get it from plot
if(length(meta$plot$layers[[layer.i]]$data) == 0){
meta$plot$layers[[layer.i]]$data <- meta$plot$data
}
## if mapping is not specified, get it from plot
if(is.null(meta$plot$layers[[layer.i]]$mapping)){
meta$plot$layers[[layer.i]]$mapping <- meta$plot$mapping
}
}
meta$built <- ggplot2::ggplot_build(meta$plot)
plot.meta <- list()
## Export axis specification as a combination of breaks and
## labels, on the relevant axis scale (i.e. so that it can
## be passed into d3 on the x axis scale instead of on the
## grid 0-1 scale). This allows transformations to be used
## out of the box, with no additional d3 coding.
theme.pars <- ggplot2:::plot_theme(meta$plot)
## Interpret panel.margin as the number of lines between facets
## (ignoring whatever grid::unit such as cm that was specified).
## Now ggplot specifies panel.margin in 'pt' instead of 'lines'
pt.to.lines <- function(margin.value){
if(attributes(margin.value)$unit == "pt"){
margin.value <- round(as.numeric(margin.value) * (0.25/5.5), digits = 2)
}
as.numeric(margin.value)
}
plot.meta$panel_margin_lines <- pt.to.lines(theme.pars$panel.margin)
## No legend if theme(legend.postion="none").
plot.meta$legend <- if(theme.pars$legend.position != "none"){
getLegendList(meta$built)
}
## scan for legends in each layer.
for(layer.i in seq_along(meta$plot$layers)){
##cat(sprintf("%4d / %4d layers\n", layer.i, length(meta$plot$layers)))
## This is the layer from the original ggplot object.
L <- meta$plot$layers[[layer.i]]
## If any legends are specified, add showSelected aesthetic
for(legend.i in seq_along(plot.meta$legend)) {
one.legend <- plot.meta$legend[[legend.i]]
## the name of the selection variable used in this legend.
s.name <- one.legend$selector
is.variable.name <- is.character(s.name) && length(s.name) == 1
layer.has.variable <- s.name %in% names(L$data)
if(is.variable.name && layer.has.variable) {
## grabbing the variable from the data
var <- L$data[, s.name]
is.interactive.aes <-
grepl("showSelected|clickSelects", names(L$mapping))
is.legend.var <- L$mapping == s.name
## If s.name is used with another interactive aes, then do
## not add any showSelected aesthetic for it.
var.is.interactive <- any(is.interactive.aes & is.legend.var)
if(!var.is.interactive){
## only add showSelected aesthetic if the variable is
## used by the geom
type.vec <- one.legend$legend_type
if(any(type.vec %in% names(L$mapping))){
type.str <- paste(type.vec, collapse="")
a.name <- paste0("showSelectedlegend", type.str)
L$mapping[[a.name]] <- as.symbol(s.name)
}
}
## if selector.types has not been specified, create it
if(is.null(meta$selector.types)) {
meta$selector.types <- list()
}
## if selector.types is not specified for this variable, set
## it to multiple.
if(is.null(meta$selector.types[[s.name]])) {
meta$selector.types[[s.name]] <- "multiple"
meta$selectors[[s.name]]$type <- "multiple"
}
## if first is not specified, create it
if(is.null(meta$first)) {
meta$first <- list()
}
## if first is not specified, add all to first
if(is.null(meta$first[[s.name]])) {
u.vals <- unique(var)
}
## Tell this selector that it has a legend somewhere in the
## viz. (if the selector has no interactive legend and no
## clickSelects, then we show the widgets by default).
meta$selectors[[s.name]]$legend <- TRUE
}#length(s.name)
}#legend.i
}#layer.i
## need to call ggplot_build again because we've added to the plot.
## I'm sure that there is a way around this, but not immediately sure how.
## There's sort of a Catch-22 here because to create the interactivity,
## we need to specify the variable corresponding to each legend.
## To do this, we need to have the legend.
## And to have the legend, I think that we need to use ggplot_build
meta$built <- ggplot2::ggplot_build(meta$plot)
## TODO: implement a compiler that does not call ggplot_build at
## all, and instead does all of the relevant computations in animint
## code.
## 'strips' are really titles for the different facet panels
plot.meta$strips <- with(meta$built, getStrips(plot$facet, panel))
## the layout tells us how to subset and where to plot on the JS side
plot.meta$layout <- with(meta$built, flag_axis(plot$facet, panel$layout))
plot.meta$layout <- with(meta$built, train_layout(
plot$facet, plot$coordinates, plot.meta$layout, panel$ranges))
## extract panel background and borders from theme.pars
get_bg <- function(pars) {
# if pars is not an empty list - occurs when using element_blank()
if(length(pars) > 0) {
## if elements are not specified, they inherit from theme.pars$rect
for(i in 1:length(pars)) {
if(is.null(pars[[i]])) pars[[i]] <- unname(theme.pars$rect[[i]])
}
# convert fill to RGB if necessary
if(!(is.rgb(pars$fill))) pars$fill <- unname(toRGB(pars$fill))
# convert color to RGB if necessary
if(!(is.rgb(pars$colour))) pars$colour <- unname(toRGB(pars$colour))
# remove names (JSON file was getting confused)
pars <- lapply(pars, unname)
}
pars
}
# saving background info
plot.meta$panel_background <- get_bg(theme.pars$panel.background)
plot.meta$panel_border <- get_bg(theme.pars$panel.border)
### function to extract grid info
get_grid <- function(pars, major = T) {
# if pars is not an empty list - occurs when using element_blank()
if(length(pars) > 0) {
## if elements are not specified, they inherit from
## theme.pars$panel.grid then from theme.pars$line
for(i in names(pars)) {
if(is.null(pars[[i]])) pars[[i]] <-
if(!is.null(theme.pars$panel.grid[[i]])) {
theme.pars$panel.grid[[i]]
} else {
theme.pars$line[[i]]
}
}
# convert colour to RGB if necessary
if(!is.rgb(pars$colour)) pars$colour <- unname(toRGB(pars$colour))
# remove names (JSON file was getting confused)
pars <- lapply(pars, unname)
}
## x and y locations
if(major) {
pars$loc$x <- as.list(meta$built$panel$ranges[[1]]$x.major_source)
pars$loc$y <- as.list(meta$built$panel$ranges[[1]]$y.major_source)
} else {
pars$loc$x <- as.list(meta$built$panel$ranges[[1]]$x.minor_source)
pars$loc$y <- as.list(meta$built$panel$ranges[[1]]$y.minor_source)
## remove minor lines when major lines are already drawn
pars$loc$x <- pars$loc$x[
!(pars$loc$x %in% plot.meta$grid_major$loc$x)
]
pars$loc$y <- pars$loc$y[
!(pars$loc$y %in% plot.meta$grid_major$loc$y)
]
}
pars
}
# extract major grid lines
plot.meta$grid_major <- get_grid(theme.pars$panel.grid.major)
# extract minor grid lines
plot.meta$grid_minor <- get_grid(theme.pars$panel.grid.minor, major = F)
## Flip labels if coords are flipped - transform does not take care
## of this. Do this BEFORE checking if it is blank or not, so that
## individual axes can be hidden appropriately, e.g. #1.
if("CoordFlip"%in%attr(meta$plot$coordinates, "class")){
temp <- meta$plot$labels$x
meta$plot$labels$x <- meta$plot$labels$y
meta$plot$labels$y <- temp
}
is.blank <- function(el.name){
x <- ggplot2::calc_element(el.name, meta$plot$theme)
"element_blank"%in%attr(x,"class")
}
# Instead of an "axis" JSON object for each plot,
# allow for "axis1", "axis2", etc. where
# "axis1" corresponds to the 1st PANEL
ranges <- meta$built$panel$ranges
n.axis <- length(ranges)
axes <- setNames(vector("list", n.axis),
paste0("axis", seq_len(n.axis)))
plot.meta <- c(plot.meta, axes)
# translate axis information
for (xy in c("x", "y")) {
s <- function(tmp) sprintf(tmp, xy)
# one axis name per plot (ie, a xtitle/ytitle is shared across panels)
plot.meta[[s("%stitle")]] <- if(is.blank(s("axis.title.%s"))){
""
} else {
scale.i <- which(meta$plot$scales$find(xy))
lab.or.null <- if(length(scale.i) == 1){
meta$plot$scales$scales[[scale.i]]$name
}
if(is.null(unlist(lab.or.null))){
meta$plot$labels[[xy]]
}else{
lab.or.null
}
}
# theme settings are shared across panels
axis.text <- theme.pars[[s("axis.text.%s")]]
## TODO: also look at axis.text! (and text?)
anchor <- hjust2anchor(axis.text$hjust)
angle <- if(is.numeric(axis.text$angle)){
-axis.text$angle
}
if(is.null(angle)){
angle <- 0
}
if(is.null(anchor)){
anchor <- if(angle == 0){
"middle"
}else{
"end"
}
}
plot.meta[[s("%sanchor")]] <- as.character(anchor)
plot.meta[[s("%sangle")]] <- as.numeric(angle)
# translate panel specific axis info
ctr <- 0
for (axis in names(axes)) {
ctr <- ctr + 1
range <- ranges[[ctr]]
plot.meta[[axis]][[xy]] <- as.list(range[[s("%s.major_source")]])
plot.meta[[axis]][[s("%slab")]] <- if(is.blank(s("axis.text.%s"))){
NULL
} else {
as.list(range[[s("%s.labels")]])
}
plot.meta[[axis]][[s("%srange")]] <- range[[s("%s.range")]]
plot.meta[[axis]][[s("%sline")]] <- !is.blank(s("axis.line.%s"))
plot.meta[[axis]][[s("%sticks")]] <- !is.blank(s("axis.ticks.%s"))
}
}
# grab the unique axis labels (makes rendering simpler)
axis.info <- plot.meta[grepl("^axis[0-9]+$", names(plot.meta))]
plot.meta$xlabs <- as.list(unique(unlist(lapply(axis.info, "[", "xlab"))))
plot.meta$ylabs <- as.list(unique(unlist(lapply(axis.info, "[", "ylab"))))
if("element_blank"%in%attr(theme.pars$plot.title, "class")){
plot.meta$title <- ""
} else {
plot.meta$title <- meta$plot$labels$title
}
## Set plot width and height from animint.* options if they are
## present.
plot.meta$options <- list()
theme <- meta$plot$theme
for(wh in c("width", "height")){
awh <- paste0("animint.", wh)
plot.meta$options[[wh]] <- if(awh %in% names(theme)){
theme[[awh]]
}else{
400
}
}
update_axes <- "animint.update_axes"
if(update_axes %in% names(theme)){
plot.meta$options$update_axes <- theme[[update_axes]]
}
meta$plots[[meta$plot.name]] <- plot.meta
list(
ggplot=meta$plot,
built=meta$built)
}
hjust2anchor <- function(hjust){
if(is.null(hjust))return(NULL)
stopifnot(is.numeric(hjust))
trans <-
c("0"="start",
"0.5"="middle",
"1"="end")
hjust.str <- as.character(hjust)
is.valid <- hjust.str %in% names(trans)
if(all(is.valid)){
## as.character removes names.
as.character(trans[hjust.str])
}else{
print(hjust[!is.valid])
stop("animint only supports hjust values 0, 0.5, 1")
}
}
#' Save a layer to disk, save and return meta-data.
#' @param l one layer of the ggplot object.
#' @param d one layer of calculated data from ggplot2::ggplot_build(p).
#' @param meta environment of meta-data.
#' @return list representing a layer, with corresponding aesthetics, ranges, and groups.
#' @export
saveLayer <- function(l, d, meta){
# carson's approach to getting layer types
ggtype <- function (x, y = "geom") {
sub(y, "", tolower(class(x[[y]])[1]))
}
ranges <- meta$built$panel$ranges
g <- list(geom=ggtype(l))
g$classed <-
sprintf("geom%d_%s_%s",
meta$geom.count, g$geom, meta$plot.name)
## For each geom, save the nextgeom to preserve drawing order.
if(is.character(meta$prev.class)){
meta$geoms[[meta$prev.class]]$nextgeom <- g$classed
}
meta$geom.count <- meta$geom.count + 1
## needed for when group, etc. is an expression:
g$aes <- sapply(l$mapping, function(k) as.character(as.expression(k)))
## use un-named parameters so that they will not be exported
## to JSON as a named object, since that causes problems with
## e.g. colour.
## 'colour', 'size' etc. have been moved to aes_params
g$params <- c(l$geom_params, l$stat_params, l$aes_params, l$extra_params)
for(p.name in names(g$params)){
if("chunk_vars" %in% names(g$params) && is.null(g$params[["chunk_vars"]])){
g$params[["chunk_vars"]] <- character()
}
names(g$params[[p.name]]) <- NULL
## Ignore functions.
if(is.function(g$params[[p.name]])){
g$params[[p.name]] <- NULL
}
}
## Make a list of variables to use for subsetting. subset_order is the
## order in which these variables will be accessed in the recursive
## JavaScript array structure.
## subset_order IS in fact useful with geom_segment! For example, in
## the first plot in the breakpointError example, the geom_segment has
## the following exported data in plot.json
## "subset_order": [
## "showSelected",
## "showSelected2"
## ],
## This information is used to parse the recursive array data structure
## that allows efficient lookup of subsets of data in JavaScript. Look at
## the Firebug DOM browser on
## http://sugiyama-www.cs.titech.ac.jp/~toby/animint/breakpoints/index.html
## and navigate to plot.Geoms.geom3.data. You will see that this is a
## recursive array that can be accessed via
## data[segments][bases.per.probe] which is an un-named array
## e.g. [{row1},{row2},...] which will be bound to the <line> elements by
## D3. The key point is that the subset_order array stores the order of the
## indices that will be used to select the current subset of data (in
## this case showSelected=segments, showSelected2=bases.per.probe). The
## currently selected values of these variables are stored in
## plot.Selectors.
s.aes <- selector.aes(g$aes)
meta$selector.aes[[g$classed]] <- s.aes
## Do not copy group unless it is specified in aes, and do not copy
## showSelected variables which are specified multiple times.
group.not.specified <- ! "group" %in% names(g$aes)
n.groups <- length(unique(NULL))
need.group <- c("violin", "step", "hex")
group.meaningless <- g$geom %in% c(
"abline", "blank",
##"crossbar", "pointrange", #documented as unsupported
## "rug", "dotplot", "quantile", "smooth", "boxplot",
## "bin2d", "map"
"errorbar", "errorbarh",
##"bar", "histogram", #?
"hline", "vline",
"jitter", "linerange",
"point",
"rect", "segment")
dont.need.group <- ! g$geom %in% need.group
remove.group <- group.meaningless ||
group.not.specified && 1 < n.groups && dont.need.group
do.not.copy <- c(
if(remove.group)"group",
s.aes$showSelected$ignored,
s.aes$clickSelects$ignored)
copy.cols <- ! names(d) %in% do.not.copy
g.data <- d[copy.cols]
is.ss <- names(g$aes) %in% s.aes$showSelected$one
show.vars <- g$aes[is.ss]
pre.subset.order <- as.list(names(show.vars))
is.cs <- names(g$aes) %in% s.aes$clickSelects$one
update.vars <- g$aes[is.ss | is.cs]
update.var.names <- if(0 < length(update.vars)){
data.frame(variable=names(update.vars), value=NA)
}
interactive.aes <- with(s.aes, {
rbind(clickSelects$several, showSelected$several,
update.var.names)
})
## Construct the selector.
for(row.i in seq_along(interactive.aes$variable)){
aes.row <- interactive.aes[row.i, ]
is.variable.value <- !is.na(aes.row$value)
selector.df <- if(is.variable.value){
selector.vec <- g.data[[paste(aes.row$variable)]]
data.frame(value.col=aes.row$value,
selector.name=unique(paste(selector.vec)))
}else{
value.col <- paste(aes.row$variable)
data.frame(value.col,
selector.name=update.vars[[value.col]])
}
for(sel.i in 1:nrow(selector.df)){
sel.row <- selector.df[sel.i,]
value.col <- paste(sel.row$value.col)
selector.name <- paste(sel.row$selector.name)
## If this selector was defined by .variable .value aes, then we
## will not generate selectize widgets.
meta$selectors[[selector.name]]$is.variable.value <- is.variable.value
## If this selector has no defined type yet, we define it once
## and for all here, so we can use it later for chunk
## separation.
if(is.null(meta$selectors[[selector.name]]$type)){
selector.type <- meta$selector.types[[selector.name]]
if(is.null(selector.type))selector.type <- "single"
stopifnot(is.character(selector.type))
stopifnot(length(selector.type)==1)
stopifnot(selector.type %in% c("single", "multiple"))
meta$selectors[[selector.name]]$type <- selector.type
}
## If this selector does not have any clickSelects then we show
## the selectize widgets by default.
for(look.for in c("showSelected", "clickSelects")){
if(grepl(look.for, aes.row$variable)){
meta$selectors[[selector.name]][[look.for]] <- TRUE
}
}
## We also store all the values of this selector in this layer,
## so we can accurately set levels after all geoms have been
## compiled.
value.vec <- unique(g.data[[value.col]])
key <- paste(g$classed, row.i, sel.i)
meta$selector.values[[selector.name]][[key]] <-
list(values=paste(value.vec), update=g$classed)
}
}
is.show <- grepl("showSelected", names(g$aes))
has.show <- any(is.show)
## Error if non-identity stat is used with showSelected, since
## typically the stats will delete the showSelected column from the
## built data set. For example geom_bar + stat_bin doesn't make
## sense with clickSelects/showSelected, since two
## clickSelects/showSelected values may show up in the same bin.
stat.type <- class(l$stat)[[1]]
if(has.show && stat.type != "StatIdentity"){
show.names <- names(g$aes)[is.show]
data.has.show <- show.names %in% names(g.data)
signal <- if(all(data.has.show))warning else stop
print(l)
signal(
"showSelected does not work with ",
stat.type,
", problem: ",
g$classed)
}
## Warn if non-identity position is used with animint aes.
position.type <- class(l$position)[[1]]
if(has.show && position.type != "PositionIdentity"){
print(l)
warning("showSelected only works with position=identity, problem: ",
g$classed)
}
##print("before pre-processing")
## Pre-process some complex geoms so that they are treated as
## special cases of basic geoms. In ggplot2, this processing is done
## in the draw method of the geoms.
if(g$geom=="abline"){
## loop through each set of slopes/intercepts
## TODO: vectorize this code!
for(i in 1:nrow(g.data)) {
# "Trick" ggplot coord_transform into transforming the slope and intercept
g.data[i, "x"] <- ranges[[ g.data$PANEL[i] ]]$x.range[1]
g.data[i, "xend"] <- ranges[[ g.data$PANEL[i] ]]$x.range[2]
g.data[i, "y"] <- g.data$slope[i] * g.data$x[i] + g.data$intercept[i]
g.data[i, "yend"] <- g.data$slope[i] * g.data$xend[i] + g.data$intercept[i]
# make sure that lines don't run off the graph
if(g.data$y[i] < ranges[[ g.data$PANEL[i] ]]$y.range[1] ) {
g.data$y[i] <- ranges[[ g.data$PANEL[i] ]]$y.range[1]
g.data$x[i] <- (g.data$y[i] - g.data$intercept[i]) / g.data$slope[i]
}
if(g.data$yend[i] > ranges[[ g.data$PANEL[i] ]]$y.range[2]) {
g.data$yend[i] <- ranges[[ g.data$PANEL[i] ]]$y.range[2]
g.data$xend[i] <- (g.data$yend[i] - g.data$intercept[i]) / g.data$slope[i]
}
}
## ggplot2 defaults to adding a group aes for ablines!
## Remove it since it is meaningless.
g$aes <- g$aes[names(g$aes)!="group"]
g.data <- g.data[! names(g.data) %in% c("slope", "intercept")]
g$geom <- "segment"
} else if(g$geom=="point"){
# Fill set to match ggplot2 default of filled in circle.
# Check for fill in both data and params
fill.in.data <- ("fill" %in% names(g.data) && any(!is.na(g.data[["fill"]])))
fill.in.params <- "fill" %in% names(g$params)
fill.specified <- fill.in.data || fill.in.params
if(!fill.specified & "colour" %in% names(g.data)){
g.data[["fill"]] <- g.data[["colour"]]
}
} else if(g$geom=="text"){
## convert hjust to anchor.
hjustRemove <- function(df.or.list){
df.or.list$anchor <- hjust2anchor(df.or.list$hjust)
df.or.list[names(df.or.list) != "hjust"]
}
vjustWarning <- function(vjust.vec){
not.supported <- vjust.vec != 0
if(any(not.supported)){
bad.vjust <- unique(vjust.vec[not.supported])
print(bad.vjust)
warning("animint only supports vjust=0")
}
}
if ("hjust" %in% names(g$params)) {
g$params <- hjustRemove(g$params)
} else if ("hjust" %in% names(g.data)) {
g.data <- hjustRemove(g.data)
}
if("vjust" %in% names(g$params)) {
vjustWarning(g$params$vjust)
} else if ("vjust" %in% names(g$aes)) {
vjustWarning(g.data$vjust)
}
} else if(g$geom=="ribbon"){
# Color set to match ggplot2 default of fill with no outside border.
if("fill"%in%names(g.data) & !"colour"%in%names(g.data)){
g.data[["colour"]] <- g.data[["fill"]]
}
} else if(g$geom=="density" | g$geom=="area"){
g$geom <- "ribbon"
} else if(g$geom=="tile" | g$geom=="raster" | g$geom=="histogram" ){
# Color set to match ggplot2 default of tile with no outside border.
if(!"colour"%in%names(g.data) & "fill"%in%names(g.data)){
g.data[["colour"]] <- g.data[["fill"]]
# Make outer border of 0 size if size isn't already specified.
if(!"size"%in%names(g.data)) g.data[["size"]] <- 0
}
g$geom <- "rect"
} else if(g$geom=="bar"){
is.xy <- names(g.data) %in% c("x", "y")
g.data <- g.data[!is.xy]
g$geom <- "rect"
} else if(g$geom=="bin2d"){
stop("bin2d is not supported in animint. Try using geom_tile() and binning the data yourself.")
} else if(g$geom=="boxplot"){
stop("boxplots are not supported. Workaround: rects, lines, and points")
## TODO: boxplot support. But it is hard since boxplots are drawn
## using multiple geoms and it is not straightforward to deal with
## that using our current JS code. There is a straightforward
## workaround: combine working geoms (rects, lines, and points).
g.data$outliers <- sapply(g.data$outliers, FUN=paste, collapse=" @ ")
# outliers are specified as a list... change so that they are specified
# as a single string which can then be parsed in JavaScript.
# there has got to be a better way to do this!!
} else if(g$geom=="violin"){
g.data$xminv <- with(g.data, x - violinwidth * (x - xmin))
g.data$xmaxv <- with(g.data, x + violinwidth * (xmax - x))
newdata <- plyr::ddply(g.data, "group", function(df){
rbind(plyr::arrange(transform(df, x=xminv), y),
plyr::arrange(transform(df, x=xmaxv), -y))
})
newdata <- plyr::ddply(newdata, "group", function(df) rbind(df, df[1,]))
g.data <- newdata
g$geom <- "polygon"
} else if(g$geom=="step"){
datanames <- names(g.data)
g.data <- plyr::ddply(g.data, "group", function(df) ggplot2:::stairstep(df))
g$geom <- "path"
} else if(g$geom=="contour" | g$geom=="density2d"){
g$aes[["group"]] <- "piece"
g$geom <- "path"
} else if(g$geom=="freqpoly"){
g$geom <- "line"
} else if(g$geom=="quantile"){
g$geom <- "path"
} else if(g$geom=="hex"){
g$geom <- "polygon"
## TODO: for interactivity we will run into the same problems as
## we did with histograms. Again, if we put several
## clickSelects/showSelected values in the same hexbin, then
## clicking/hiding hexbins doesn't really make sense. Need to stop
## with an error if showSelected/clickSelects is used with hex.
g$aes[["group"]] <- "group"
dx <- ggplot2::resolution(g.data$x, FALSE)
dy <- ggplot2::resolution(g.data$y, FALSE) / sqrt(3) / 2 * 1.15
hex <- as.data.frame(hexbin::hexcoords(dx, dy))[,1:2]
hex <- rbind(hex, hex[1,]) # to join hexagon back to first point
g.data$group <- as.numeric(interaction(g.data$group, 1:nrow(g.data)))
## this has the potential to be a bad assumption -
## by default, group is identically 1, if the user
## specifies group, polygons aren't possible to plot
## using d3, because group will have a different meaning
## than "one single polygon".
# CPS (07-24-14) what about this? --
# http://tdhock.github.io/animint/geoms/polygon/index.html
newdata <- plyr::ddply(g.data, "group", function(df){
df$xcenter <- df$x
df$ycenter <- df$y
cbind(x=df$x+hex$x, y=df$y+hex$y, df[,-which(names(df)%in%c("x", "y"))])
})
g.data <- newdata
# Color set to match ggplot2 default of tile with no outside border.
if(!"colour"%in%names(g.data) & "fill"%in%names(g.data)){
g.data[["colour"]] <- g.data[["fill"]]
# Make outer border of 0 size if size isn't already specified.
if(!"size"%in%names(g.data)) g.data[["size"]] <- 0
}
}
## Some geoms need their data sorted before saving to tsv.
if(g$geom %in% c("ribbon", "line")){
g.data <- g.data[order(g.data$x), ]
}
## Check g.data for color/fill - convert to hexadecimal so JS can parse correctly.
for(color.var in c("colour", "color", "fill")){
if(color.var %in% names(g.data)){
g.data[,color.var] <- toRGB(g.data[,color.var])
}
if(color.var %in% names(g$params)){
g$params[[color.var]] <- toRGB(g$params[[color.var]])
}
}
has.no.fill <- g$geom %in% c("path", "line")
zero.size <- any(g.data$size == 0, na.rm=TRUE)
if(zero.size && has.no.fill){
warning(sprintf("geom_%s with size=0 will be invisible",g$geom))
}
## TODO: coord_transform maybe won't work for
## geom_dotplot|rect|segment and polar/log transformations, which
## could result in something nonlinear. For the time being it is
## best to just ignore this, but you can look at the source of
## e.g. geom-rect.r in ggplot2 to see how they deal with this by
## doing a piecewise linear interpolation of the shape.
# Flip axes in case of coord_flip
# Switches column names. Eg. xmin to ymin, yntercept to xintercept etc.
switch_axes <- function(col.names){
for(elem in seq_along(col.names)){
if(grepl("^x", col.names[elem])){
col.names[elem] <- sub("^x", "y", col.names[elem])
} else if(grepl("^y", col.names[elem])){
col.names[elem] <- sub("^y", "x", col.names[elem])
}
}
col.names
}
if(inherits(meta$plot$coordinates, "CoordFlip")){
names(g.data) <- switch_axes(names(g.data))
}
## Output types
## Check to see if character type is d3's rgb type.
is.linetype <- function(x){
x <- tolower(x)
namedlinetype <-
x%in%c("blank", "solid", "dashed",
"dotted", "dotdash", "longdash", "twodash")
xsplit <- sapply(x, function(i){
sum(is.na(strtoi(strsplit(i,"")[[1]],16)))==0
})
namedlinetype | xsplit
}
g$types <- sapply(g.data, function(x) {
type <- paste(class(x), collapse="-")
if(type == "character"){
if(sum(!is.rgb(x))==0){
"rgb"
}else if(sum(!is.linetype(x))==0){
"linetype"
}else {
"character"
}
}else{
type
}
})
g$types[["group"]] <- "character"
## convert ordered factors to unordered factors so javascript
## doesn't flip out.
ordfactidx <- which(g$types=="ordered-factor")
for(i in ordfactidx){
g.data[[i]] <- factor(as.character(g.data[[i]]))
g$types[[i]] <- "factor"
}
## Get unique values of time variable.
time.col <- NULL
if(is.list(meta$time)){ # if this is an animation,
g.time.list <- list()
for(c.or.s in names(s.aes)){
cs.info <- s.aes[[c.or.s]]
for(a in cs.info$one){
if(g$aes[[a]] == meta$time$var){
g.time.list[[a]] <- g.data[[a]]
time.col <- a
}
}
for(row.i in seq_along(cs.info$several$value)){
cs.row <- cs.info$several[row.i,]
c.name <- paste(cs.row$variable)
is.time <- g.data[[c.name]] == meta$time$var
g.time.list[[c.name]] <- g.data[is.time, paste(cs.row$value)]
}
}
u.vals <- unique(unlist(g.time.list))
if(length(u.vals)){
meta$timeValues[[paste(g$classed)]] <- sort(u.vals)
}
}
## Make the time variable the first subset_order variable.
if(length(time.col)){
pre.subset.order <- pre.subset.order[order(pre.subset.order != time.col)]
}
## Determine which showSelected values to use for breaking the data
## into chunks. This is a list of variables which have the same
## names as the selectors. E.g. if chunk_order=list("year") then
## when year is clicked, we may need to download some new data for
## this geom.
subset.vec <- unlist(pre.subset.order)
if("chunk_vars" %in% names(g$params)){ #designer-specified chunk vars.
designer.chunks <- g$params$chunk_vars
if(!is.character(designer.chunks)){
stop("chunk_vars must be a character vector; ",
"use chunk_vars=character() to specify 1 chunk")
}
not.subset <- !designer.chunks %in% g$aes[subset.vec]
if(any(not.subset)){
stop("invalid chunk_vars ",
paste(designer.chunks[not.subset], collapse=" "),
"; possible showSelected variables: ",
paste(g$aes[subset.vec], collapse=" "))
}
is.chunk <- g$aes[subset.vec] %in% designer.chunks
chunk.cols <- subset.vec[is.chunk]
nest.cols <- subset.vec[!is.chunk]
}else{ #infer a default, either 0 or 1 chunk vars:
if(length(meta$selectors)==0){
## no selectors, just make 1 chunk.
nest.cols <- subset.vec
chunk.cols <- NULL
}else{
selector.types <- sapply(meta$selectors, "[[", "type")
selector.names <- g$aes[subset.vec]
subset.types <- selector.types[selector.names]
can.chunk <- subset.types != "multiple"
names(can.chunk) <- subset.vec
## Guess how big the chunk files will be, and reduce the number of
## chunks if there are any that are too small.
tmp <- tempfile()
some.lines <- rbind(head(g.data), tail(g.data))
write.table(some.lines, tmp,
col.names=FALSE,
quote=FALSE, row.names=FALSE, sep="\t")
bytes <- file.info(tmp)$size
bytes.per.line <- bytes/nrow(some.lines)
bad.chunk <- function(){
if(all(!can.chunk))return(NULL)
can.chunk.cols <- subset.vec[can.chunk]
maybe.factors <- g.data[, can.chunk.cols, drop=FALSE]
for(N in names(maybe.factors)){
maybe.factors[[N]] <- paste(maybe.factors[[N]])
}
rows.per.chunk <- table(maybe.factors)
bytes.per.chunk <- rows.per.chunk * bytes.per.line
if(all(4096 < bytes.per.chunk))return(NULL)
## If all of the tsv chunk files are greater than 4KB, then we
## return NULL here to indicate that the current chunk
## variables (indicated in can.chunk) are fine.
## In other words, the compiler will not break a geom into
## chunks if any of the resulting chunk tsv files is estimated
## to be less than 4KB (of course, if the layer has very few
## data overall, the compiler creates 1 file which may be less
## than 4KB, but that is fine).
dim.byte.list <- list()
if(length(can.chunk.cols) == 1){
dim.byte.list[[can.chunk.cols]] <- sum(bytes.per.chunk)
}else{
for(dim.i in seq_along(can.chunk.cols)){
dim.name <- can.chunk.cols[[dim.i]]
dim.byte.list[[dim.name]] <-
apply(bytes.per.chunk, -dim.i, sum)
}
}
selector.df <-
data.frame(chunks.for=length(rows.per.chunk),
chunks.without=sapply(dim.byte.list, length),
min.bytes=sapply(dim.byte.list, min))
## chunks.for is the number of chunks you get if you split the
## data set using just this column. If it is 1, then it is
## fine to chunk on this variable (since we certainly won't
## make more than 1 small tsv file) and in fact we want to
## chunk on this variable, since then this layer's data won't
## be downloaded at first if it is not needed.
not.one <- subset(selector.df, 1 < chunks.for)
if(nrow(not.one) == 0){
NULL
}else{
rownames(not.one)[[which.max(not.one$min.bytes)]]
}
}
while({
bad <- bad.chunk()
!is.null(bad)
}){
can.chunk[[bad]] <- FALSE
}
if(any(can.chunk)){
nest.cols <- subset.vec[!can.chunk]
chunk.cols <- subset.vec[can.chunk]
}else{
nest.cols <- subset.vec
chunk.cols <- NULL
}
} # meta$selectors > 0
}
# If there is only one PANEL, we don't need it anymore.
plot.has.panels <- nrow(meta$built$panel$layout) > 1
g$PANEL <- unique(g.data[["PANEL"]])
geom.has.one.panel <- length(g$PANEL) == 1
if(geom.has.one.panel && (!plot.has.panels)) {
g.data <- g.data[names(g.data) != "PANEL"]
}
## Also add pointers to these chunks from the related selectors.
if(length(chunk.cols)){
selector.names <- as.character(g$aes[chunk.cols])
chunk.name <- paste(selector.names, collapse="_")
g$chunk_order <- as.list(selector.names)
for(selector.name in selector.names){
meta$selectors[[selector.name]]$chunks <-
unique(c(meta$selectors[[selector.name]]$chunks, chunk.name))
}
}else{
g$chunk_order <- list()
}
g$nest_order <- as.list(nest.cols)
names(g$chunk_order) <- NULL
names(g$nest_order) <- NULL
g$subset_order <- g$nest_order
## If this plot has more than one PANEL then add it to subset_order
## and nest_order.
if(plot.has.panels){
g$subset_order <- c(g$subset_order, "PANEL")
g$nest_order <- c(g$nest_order, "PANEL")
}
## nest_order should contain both .variable .value aesthetics, but
## subset_order should contain only .variable.
if(0 < nrow(s.aes$showSelected$several)){
g$nest_order <- with(s.aes$showSelected$several, {
c(g$nest_order, paste(variable), paste(value))
})
g$subset_order <-
c(g$subset_order, paste(s.aes$showSelected$several$variable))
}
## group should be the last thing in nest_order, if it is present.
data.object.geoms <- c("line", "path", "ribbon", "polygon")
if("group" %in% names(g$aes) && g$geom %in% data.object.geoms){
g$nest_order <- c(g$nest_order, "group")
}
## Some geoms should be split into separate groups if there are NAs.
if(any(is.na(g.data)) && "group" %in% names(g$aes)){
sp.cols <- unlist(c(chunk.cols, g$nest_order))
order.args <- list()
for(sp.col in sp.cols){
order.args[[sp.col]] <- g.data[[sp.col]]
}
ord <- do.call(order, order.args)
g.data <- g.data[ord,]
is.missing <- apply(is.na(g.data), 1, any)
diff.vec <- diff(is.missing)
new.group.vec <- c(FALSE, diff.vec == 1)
for(chunk.col in sp.cols){
one.col <- g.data[[chunk.col]]
is.diff <- c(FALSE, one.col[-1] != one.col[-length(one.col)])
new.group.vec[is.diff] <- TRUE
}
subgroup.vec <- cumsum(new.group.vec)
g.data$group <- subgroup.vec
}
## Determine if there are any "common" data that can be saved
## separately to reduce disk usage.
data.or.null <- getCommonChunk(g.data, chunk.cols, g$aes)
g.data.varied <- if(is.null(data.or.null)){
split.x(na.omit(g.data), chunk.cols)
}else{
g$columns$common <- as.list(names(data.or.null$common))
tsv.name <- sprintf("%s_chunk_common.tsv", g$classed)
tsv.path <- file.path(meta$out.dir, tsv.name)
write.table(data.or.null$common, tsv.path,
quote = FALSE, row.names = FALSE,
sep = "\t")
data.or.null$varied
}
## Save each variable chunk to a separate tsv file.
meta$chunk.i <- 1L
meta$g <- g
g$chunks <- saveChunks(g.data.varied, meta)
g$total <- length(unlist(g$chunks))
## Finally save to the master geom list.
meta$geoms[[g$classed]] <- g
g
}
##' Save the common columns for each tsv to one chunk
##' @param built data.frame of built data.
##' @param vars character vector of chunk variable names to split on.
##' @param aes.list a character vector of aesthetics.
##' @return a list of common and varied data to save, or NULL if there is
##' no common data.
getCommonChunk <- function(built, chunk.vars, aes.list){
if(length(chunk.vars) == 0){
return(NULL)
}
if(! "group" %in% names(aes.list)){
## user did not specify group, so do not use any ggplot2-computed
## group for deciding common data.
built$group <- NULL
}
## Remove columns with all NA values
## so that common.not.na is not empty
## due to the plot's alpha, stroke or other columns
all.nas <- sapply(built, function(x){all(is.na(x))})
built <- built[, !all.nas]
## Treat factors as characters, to avoid having them be coerced to
## integer later.
for(col.name in names(built)){
if(is.factor(built[, col.name])){
built[, col.name] <- paste(built[, col.name])
}
}
## If there is only one chunk, then there is no point of making a