-
Notifications
You must be signed in to change notification settings - Fork 23
/
Copy pathanimint.js
2490 lines (2380 loc) · 83.2 KB
/
animint.js
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
// Define functions to render linked interactive plots using d3.
// Another script should define e.g.
// <script>
// var plot = new animint("#plot","path/to/plot.json");
// </script>
// Constructor for animint Object.
var animint = function (to_select, json_file) {
var default_axis_px = 16;
function wait_until_then(timeout, condFun, readyFun) {
var args=arguments
function checkFun() {
if(condFun()) {
readyFun(args[3],args[4]);
} else{
setTimeout(checkFun, timeout);
}
}
checkFun();
}
function convert_R_types(resp_array, types){
return resp_array.map(function (d) {
for (var v_name in d) {
if(!is_interactive_aes(v_name)){
var r_type = types[v_name];
if (r_type == "integer") {
d[v_name] = parseInt(d[v_name]);
} else if (r_type == "numeric") {
d[v_name] = parseFloat(d[v_name]);
} else if (r_type == "factor" || r_type == "rgb"
|| r_type == "linetype" || r_type == "label"
|| r_type == "character") {
// keep it as a character
} else if (r_type == "character" & v_name == "outliers") {
d[v_name] = parseFloat(d[v_name].split(" @ "));
}
}
}
return d;
});
}
// replacing periods in variable with an underscore this makes sure
// that selector doesn't confuse . in name with css selectors
function safe_name(unsafe_name){
return unsafe_name.replace(/[ .]/g, '_');
}
function legend_class_name(selector_name){
return safe_name(selector_name) + "_variable";
}
function is_interactive_aes(v_name){
if(v_name.indexOf("clickSelects") > -1){
return true;
}
if(v_name.indexOf("showSelected") > -1){
return true;
}
return false;
}
var linetypesize2dasharray = function (lt, size) {
var isInt = function(n) {
return typeof n === 'number' && parseFloat(n) == parseInt(n, 10) && !isNaN(n);
};
if(isInt(lt)){ // R integer line types.
if(lt == 1){
return null;
}
var o = {
0: size * 0 + "," + size * 10,
2: size * 4 + "," + size * 4,
3: size + "," + size * 2,
4: size + "," + size * 2 + "," + size * 4 + "," + size * 2,
5: size * 8 + "," + size * 4,
6: size * 2 + "," + size * 2 + "," + size * 6 + "," + size * 2
};
} else { // R defined line types
if(lt == "solid" || lt === null){
return null;
}
var o = {
"blank": size * 0 + "," + size * 10,
"none": size * 0 + "," + size * 10,
"dashed": size * 4 + "," + size * 4,
"dotted": size + "," + size * 2,
"dotdash": size + "," + size * 2 + "," + size * 4 + "," + size * 2,
"longdash": size * 8 + "," + size * 4,
"twodash": size * 2 + "," + size * 2 + "," + size * 6 + "," + size * 2,
"22": size * 2 + "," + size * 2,
"42": size * 4 + "," + size * 2,
"44": size * 4 + "," + size * 4,"13": size + "," + size * 3,
"1343": size + "," + size * 3 + "," + size * 4 + "," + size * 3,
"73": size * 7 + "," + size * 3,
"2262": size * 2 + "," + size * 2 + "," + size * 6 + "," + size * 2,
"12223242": size + "," + size * 2 + "," + size * 2 + "," + size * 2 + "," + size * 3 + "," + size * 2 + "," + size * 4 + "," + size * 2,
"F282": size * 15 + "," + size * 2 + "," + size * 8 + "," + size * 2,
"F4448444": size * 15 + "," + size * 4 + "," + size * 4 + "," + size * 4 + "," + size * 8 + "," + size * 4 + "," + size * 4 + "," + size * 4,
"224282F2": size * 2 + "," + size * 2 + "," + size * 4 + "," + size * 2 + "," + size * 8 + "," + size * 2 + "," + size * 16 + "," + size * 2,
"F1": size * 16 + "," + size
};
}
if (lt in o){
return o[lt];
} else{ // manually specified line types
str = lt.split("");
strnum = str.map(function (d) {
return size * parseInt(d, 16);
});
return strnum;
}
};
var isArray = function(o) {
return Object.prototype.toString.call(o) === '[object Array]';
};
// create a dummy element, apply the appropriate classes,
// and then measure the element
// Inspired from http://jsfiddle.net/uzddx/2/
var measureText = function(pText, pFontSize, pAngle, pStyle) {
if (!pText || pText.length === 0) return {height: 0, width: 0};
if (pAngle === null || isNaN(pAngle)) pAngle = 0;
var container = element.append('svg');
// do we need to set the class so that styling is applied?
//.attr('class', classname);
container.append('text')
.attr({x: -1000, y: -1000})
.attr("transform", "rotate(" + pAngle + ")")
.attr("style", pStyle)
.attr("font-size", pFontSize)
.text(pText);
var bbox = container.node().getBBox();
container.remove();
return {height: bbox.height, width: bbox.width};
};
var nest_by_group = d3.nest().key(function(d){ return d.group; });
var dirs = json_file.split("/");
dirs.pop(); //if a directory path exists, remove the JSON file from dirs
var element = d3.select(to_select);
this.element = element;
var viz_id = element.attr("id");
var plot_widget_table = element.append("table");
var plot_td = plot_widget_table.append("tr").append("td");
plot_td.attr("class","plot_content");
var widget_td = plot_widget_table.append("tr").append("td");
var Widgets = {};
this.Widgets = Widgets;
var Selectors = {};
this.Selectors = Selectors;
var Plots = {};
this.Plots = Plots;
var Geoms = {};
this.Geoms = Geoms;
// SVGs must be stored separately from Geoms since they are
// initialized first, with the Plots.
var SVGs = {};
this.SVGs = SVGs;
var Animation = {};
this.Animation = Animation;
var all_geom_names = {};
this.all_geom_names = all_geom_names;
//creating an array to contain the selectize widgets
var selectized_array = [];
var data_object_geoms = {
"line":true,
"path":true,
"ribbon":true,
"polygon":true
};
var css = document.createElement('style');
css.type = 'text/css';
var styles = [".axis path{fill: none;stroke: black;shape-rendering: crispEdges;}",
".axis line{fill: none;stroke: black;shape-rendering: crispEdges;}",
".axis text {font-family: sans-serif;font-size: 11px;}"];
var add_geom = function (g_name, g_info) {
// Determine if data will be an object or an array.
if(g_info.geom in data_object_geoms){
g_info.data_is_object = true;
}else{
g_info.data_is_object = false;
}
// Add a row to the loading table.
g_info.tr = Widgets["loading"].append("tr");
g_info.tr.append("td").text(g_name);
g_info.tr.append("td").attr("class", "chunk");
g_info.tr.append("td").attr("class", "downloaded").text(0);
g_info.tr.append("td").text(g_info.total);
g_info.tr.append("td").attr("class", "status").text("initialized");
// load chunk tsv
g_info.data = {};
g_info.download_status = {};
Geoms[g_name] = g_info;
// Determine whether common chunk tsv exists
// If yes, load it
if(g_info.hasOwnProperty("columns") && g_info.columns.common){
var common_tsv = get_tsv(g_info, "_common");
g_info.common_tsv = common_tsv;
var common_path = getTSVpath(common_tsv);
d3.tsv(common_path, function (error, response) {
var converted = convert_R_types(response, g_info.types);
g_info.data[common_tsv] = nest_by_group.map(converted);
});
} else {
g_info.common_tsv = null;
}
// Save this geom and load it!
update_geom(g_name, null);
};
var add_plot = function (p_name, p_info) {
// Each plot may have one or more legends. To make space for the
// legends, we put each plot in a table with one row and two
// columns: tdLeft and tdRight.
var plot_table = plot_td.append("table").style("display", "inline-block");
var plot_tr = plot_table.append("tr");
var tdLeft = plot_tr.append("td");
var tdRight = plot_tr.append("td").attr("class", p_name+"_legend");
if(viz_id === null){
p_info.plot_id = p_name;
}else{
p_info.plot_id = viz_id + "_" + p_name;
}
var svg = tdLeft.append("svg")
.attr("id", p_info.plot_id)
.attr("height", p_info.options.height)
.attr("width", p_info.options.width);
// divvy up width/height based on the panel layout
var nrows = Math.max.apply(null, p_info.layout.ROW);
var ncols = Math.max.apply(null, p_info.layout.COL);
var panel_names = p_info.layout.PANEL;
var npanels = Math.max.apply(null, panel_names);
// Note axis names are "shared" across panels (just like the title)
var xtitlepadding = 5 + measureText(p_info["xtitle"], default_axis_px).height;
var ytitlepadding = 5 + measureText(p_info["ytitle"], default_axis_px).height;
// 'margins' are fixed across panels and do not
// include title/axis/label padding (since these are not
// fixed across panels). They do, however, account for
// spacing between panels
var text_height_pixels = measureText("foo", 11).height;
var margin = {
left: 0,
right: text_height_pixels * p_info.panel_margin_lines,
top: text_height_pixels * p_info.panel_margin_lines,
bottom: 0
};
var plotdim = {
width: 0,
height: 0,
xstart: 0,
xend: 0,
ystart: 0,
yend: 0,
graph: {
width: 0,
height: 0
},
margin: margin,
xlab: {
x: 0,
y: 0
},
ylab: {
x: 0,
y: 0
},
title: {
x: 0,
y: 0
}
};
// Draw the title
var titlepadding = measureText(p_info.title, p_info.title_size).height;
// why are we giving the title padding if it is undefined?
if (p_info.title === undefined) titlepadding = 0;
plotdim.title.x = p_info.options.width / 2;
plotdim.title.y = titlepadding;
svg.append("text")
.text(p_info.title)
.attr("class", "plottitle")
.attr("font-family", "sans-serif")
.attr("font-size", p_info.title_size)
.attr("transform", "translate(" + plotdim.title.x + "," +
plotdim.title.y + ")")
.style("text-anchor", "middle");
// grab max text size over axis labels and facet strip labels
var axispaddingy = 5;
if(p_info.hasOwnProperty("ylabs") && p_info.ylabs.length){
axispaddingy += Math.max.apply(null, p_info.ylabs.map(function(entry){
// + 5 to give a little extra space to avoid bad axis labels
// in shiny.
return measureText(entry, p_info.ysize).width + 5;
}));
}
var axispaddingx = 30; // distance between tick marks and x axis name.
if(p_info.hasOwnProperty("xlabs") && p_info.xlabs.length){
// TODO: throw warning if text height is large portion of plot height?
axispaddingx += Math.max.apply(null, p_info.xlabs.map(function(entry){
return measureText(entry, p_info.xsize, p_info.xangle).height;
}));
// TODO: carefully calculating this gets complicated with rotating xlabs
//margin.right += 5;
}
plotdim.margin = margin;
var strip_heights = p_info.strips.top.map(function(entry){
return measureText(entry, p_info.strip_text_xsize).height;
});
var strip_widths = p_info.strips.right.map(function(entry){
return measureText(entry, p_info.strip_text_ysize).height;
});
// compute the number of x/y axes, max strip height per row, and
// max strip width per columns, for calculating height/width of
// graphing region.
var row_strip_heights = [];
var col_strip_widths = [];
var n_xaxes = 0;
var n_yaxes = 0;
var current_row, current_col;
for (var layout_i = 0; layout_i < npanels; layout_i++) {
current_row = p_info.layout.ROW[layout_i] - 1;
current_col = p_info.layout.COL[layout_i] - 1;
if(row_strip_heights[current_row] === undefined){
row_strip_heights[current_row] = [];
}
if(col_strip_widths[current_col] === undefined){
col_strip_widths[current_col] = [];
}
row_strip_heights[current_row].push(strip_heights[layout_i]);
col_strip_widths[current_col].push(strip_widths[layout_i]);
if (p_info.layout.COL[layout_i] == 1) {
n_xaxes += p_info.layout.AXIS_X[layout_i];
}
if (p_info.layout.ROW[layout_i] == 1) {
n_yaxes += p_info.layout.AXIS_Y[layout_i];
}
}
function cumsum_array(array_of_arrays){
var cumsum = [], max_value, cumsum_value = 0;
for(var i=0; i<array_of_arrays.length; i++){
cumsum_value += d3.max(array_of_arrays[i]);
cumsum[i] = cumsum_value;
}
return cumsum;
}
var cum_height_per_row = cumsum_array(row_strip_heights);
var cum_width_per_col = cumsum_array(col_strip_widths);
var strip_width = d3.max(cum_width_per_col);
var strip_height = d3.max(cum_height_per_row);
// the *entire graph* height/width
var graph_width = p_info.options.width -
ncols * (margin.left + margin.right) -
strip_width -
n_yaxes * axispaddingy - ytitlepadding;
var graph_height = p_info.options.height -
nrows * (margin.top + margin.bottom) -
strip_height -
titlepadding - n_xaxes * axispaddingx - xtitlepadding;
// Impose the pixelated aspect ratio of the graph upon the width/height
// proportions calculated by the compiler. This has to be done on the
// rendering side since the precomputed proportions apply to the *graph*
// and the graph size depends upon results of measureText()
if (p_info.layout.coord_fixed[0]) {
var aspect = (graph_height / nrows) / (graph_width / ncols);
} else {
var aspect = 1;
}
var wp = p_info.layout.width_proportion.map(function(x){
return x * Math.min(1, aspect);
})
var hp = p_info.layout.height_proportion.map(function(x){
return x * Math.min(1, 1/aspect);
})
// track the proportion of the graph that should be 'blank'
// this is mainly used to implement coord_fixed()
var graph_height_blank = 1;
var graph_width_blank = 1;
for (var layout_i = 0; layout_i < npanels; layout_i++) {
if (p_info.layout.COL[layout_i] == 1) graph_height_blank -= hp[layout_i];
if (p_info.layout.ROW[layout_i] == 1) graph_width_blank -= wp[layout_i];
}
// cumulative portion of the graph used
var graph_width_cum = (graph_width_blank / 2) * graph_width;
var graph_height_cum = (graph_height_blank / 2) * graph_height;
// Bind plot data to this plot's SVG element
svg.plot = p_info;
Plots[p_name] = p_info;
p_info.geoms.forEach(function (g_name) {
var layer_g_element = svg.append("g").attr("class", g_name);
panel_names.forEach(function(PANEL){
layer_g_element.append("g").attr("class", "PANEL" + PANEL);
});
SVGs[g_name] = svg;
});
// create a grouping for strip labels (even if there are none).
var topStrip = svg.append("g")
.attr("class", "topStrip")
;
var rightStrip = svg.append("g")
.attr("class", "rightStrip")
;
// this will hold x/y scales for each panel
// eventually we inject this into Plots[p_name]
var scales = {};
n_xaxes = 0;
n_yaxes = 0;
// Draw a plot outline for every panel
for (var layout_i = 0; layout_i < npanels; layout_i++) {
var panel_i = layout_i + 1;
var axis = p_info["axis" + panel_i];
//forces values to be in an array
var xaxisvals = [];
var xaxislabs = [];
var yaxisvals = [];
var yaxislabs = [];
var outbreaks, outlabs;
//function to write labels and breaks to their respective arrays
var axislabs = function(breaks, labs, axis){
if(axis=="x"){
outbreaks = xaxisvals;
outlabs = xaxislabs;
} else {
outbreaks = yaxisvals;
outlabs = yaxislabs;
} // set appropriate variable names
if (isArray(breaks)) {
breaks.forEach(function (d) {
outbreaks.push(d);
})
} else {
//breaks can be an object!
for (key in breaks) {
outbreaks.push(breaks[key]);
}
}
if (labs){
labs.forEach(function (d) {
outlabs.push(d);
// push each label provided into the array
});
} else {
outbreaks.forEach(function (d) {
outlabs.push("");
// push a blank string to the array for each axis tick
// if the specified label is null
});
}
};
if(axis["xticks"]){
axislabs(axis.x, axis.xlab, "x");
}
if(axis["yticks"]){
axislabs(axis.y, axis.ylab, "y");
}
// compute the current panel height/width
plotdim.graph.height = graph_height * hp[layout_i];
plotdim.graph.width = graph_width * wp[layout_i];
current_row = p_info.layout.ROW[layout_i];
current_col = p_info.layout.COL[layout_i];
var draw_x = p_info.layout.AXIS_X[layout_i];
var draw_y = p_info.layout.AXIS_Y[layout_i];
// panels are drawn using a "typewriter approach" (left to right
// & top to bottom) if the carriage is returned (ie, there is a
// new row), change some parameters:
var new_row = current_col <= p_info.layout.COL[layout_i - 1]
if (new_row) {
n_yaxes = 0;
graph_width_cum = (graph_width_blank / 2) * graph_width;
graph_height_cum += graph_height * hp[layout_i-1];
}
n_xaxes += draw_x;
n_yaxes += draw_y;
// calculate panel specific locations to be used in placing
// axes, labels, etc.
plotdim.xstart = current_col * plotdim.margin.left +
(current_col - 1) * plotdim.margin.right +
graph_width_cum + n_yaxes * axispaddingy + ytitlepadding;
// room for right strips should be distributed evenly across
// panels to preserve aspect ratio
plotdim.xend = plotdim.xstart + plotdim.graph.width;
// total height of strips drawn thus far
var strip_h = cum_height_per_row[current_row-1];
plotdim.ystart = current_row * plotdim.margin.top +
(current_row - 1) * plotdim.margin.bottom +
graph_height_cum + titlepadding + strip_h;
// room for xaxis title should be distributed evenly across
// panels to preserve aspect ratio
plotdim.yend = plotdim.ystart + plotdim.graph.height;
// always add to the width (note it may have been reset earlier)
graph_width_cum = graph_width_cum + plotdim.graph.width;
// get the x position of the y-axis title (and add padding) when
// rendering the first plot.
if (layout_i === 0) {
var ytitle_x = (plotdim.xstart - axispaddingy - ytitlepadding / 2);
var xtitle_left = plotdim.xstart;
var ytitle_top = plotdim.ystart;
}
// get the y position of the x-axis title when drawing the last
// panel.
if (layout_i === (npanels - 1)) {
var xtitle_y = (plotdim.yend + axispaddingx);
var xtitle_right = plotdim.xend;
var ytitle_bottom = plotdim.yend;
}
var draw_strip = function(strip, side) {
if (strip == "") {
return(null);
}
var x, y, rotate, stripElement, strip_text_xy;
if (side == "right") {
x = plotdim.xend;
y = (plotdim.ystart + plotdim.yend) / 2;
rotate = 90;
stripElement = rightStrip;
strip_text_xy = "y";
}else{ //top
x = (plotdim.xstart + plotdim.xend) / 2;
y = plotdim.ystart;
rotate = 0;
stripElement = topStrip;
strip_text_xy = "x";
}
var trans_text = "translate(" + x + "," + y + ")";
var rot_text = "rotate(" + rotate + ")";
var strip_text_size = "strip_text_"+strip_text_xy+"size";
stripElement
.selectAll("." + side + "Strips")
.data(strip)
.enter()
.append("text")
.style("text-anchor", "middle")
.style("font-size", p_info[strip_text_size])
.text(function(d) { return d; })
// NOTE: there could be multiple strips per panel
// TODO: is there a better way to manage spacing?
.attr("transform", trans_text + rot_text)
;
}
draw_strip([p_info.strips.top[layout_i]], "top");
draw_strip([p_info.strips.right[layout_i]], "right");
// for each of the x and y axes, there is a "real" and fake
// version. The real version will be used for plotting the
// data, and the fake version is just for the display of the
// axes.
scales[panel_i] = {};
scales[panel_i].x = d3.scale.linear()
.domain(axis.xrange)
.range([plotdim.xstart, plotdim.xend]);
scales[panel_i].y = d3.scale.linear()
.domain(axis.yrange)
.range([plotdim.yend, plotdim.ystart]);
if(draw_x){
var xaxis = d3.svg.axis()
.scale(scales[panel_i].x)
.tickValues(xaxisvals)
.tickFormat(function (d) {
return xaxislabs[xaxisvals.indexOf(d)].toString();
})
.orient("bottom")
;
var axis_panel = "xaxis" + "_" + panel_i;
var xaxis_g = svg.append("g")
.attr("class", "xaxis axis " + axis_panel)
.attr("transform", "translate(0," + plotdim.yend + ")")
.call(xaxis);
if(axis["xline"] == false){
var axis_path = xaxis_g.select("path.domain");
axis_path.remove();
}
xaxis_g.selectAll("text")
.style("text-anchor", p_info.xanchor)
.style("font-size", p_info.xsize)
.attr("transform", "rotate(" + p_info.xangle + " 0 9)");
}
if(draw_y){
var yaxis = d3.svg.axis()
.scale(scales[panel_i].y)
.tickValues(yaxisvals)
.tickFormat(function (d) {
return yaxislabs[yaxisvals.indexOf(d)].toString();
})
.orient("left");
var axis_panel = "yaxis" + "_" + panel_i;
var yaxis_g = svg.append("g")
.attr("class", "yaxis axis " + axis_panel)
.attr("transform", "translate(" + (plotdim.xstart) + ",0)")
.call(yaxis);
if(axis["yline"] == false){
var axis_path = yaxis_g.select("path.domain");
axis_path.remove();
}
yaxis_g.selectAll(".tick text")
.style("font-size", p_info.ysize);
}
if(!axis.xline) {
styles.push("#"+p_name+" #xaxis"+" path{stroke:none;}");
}
if(!axis.xticks) {
styles.push("#"+p_name+" #xaxis .tick"+" line{stroke:none;}");
}
if(!axis.yline) {
styles.push("#"+p_name+" #yaxis"+" path{stroke:none;}");
}
if(!axis.yticks) {
styles.push("#"+p_name+" #yaxis .tick"+" line{stroke:none;}");
}
// creating g element for background, grid lines, and border
// uses insert to draw it right before plot title
var background = svg.insert("g", ".plottitle")
.attr("class", "background bgr" + panel_i);
// drawing background
if(Object.keys(p_info.panel_background).length > 1) {
background.append("rect")
.attr("x", plotdim.xstart)
.attr("y", plotdim.ystart)
.attr("width", plotdim.xend - plotdim.xstart)
.attr("height", plotdim.yend - plotdim.ystart)
.attr("class", "background_rect")
.style("fill", p_info.panel_background.fill)
.style("stroke", p_info.panel_background.colour)
.style("stroke-dasharray", function() {
return linetypesize2dasharray(p_info.panel_background.linetype,
p_info.panel_background.size);
});
}
// drawing the grid lines
["grid_minor", "grid_major"].forEach(function(grid_class){
var grid_background = p_info[grid_class];
// if grid lines are defined
if(grid_background.hasOwnProperty("size")) {
var grid = background.append("g")
.attr("class", grid_class);
["x","y"].forEach(function(scale_var){
var const_var;
if(scale_var == "x"){
const_var = "y";
}else{
const_var = "x";
}
grid.append("g")
.attr("class", scale_var)
.selectAll("line")
.data(grid_background.loc[scale_var][layout_i])
.enter()
.append("line")
.attr(const_var + "1", plotdim[const_var + "start"])
.attr(const_var + "2", plotdim[const_var + "end"])
.attr(scale_var + "1", function(d) {
return scales[panel_i][scale_var](d);
})
.attr(scale_var + "2", function(d) {
return scales[panel_i][scale_var](d);
})
.style("stroke", grid_background.colour)
.style("stroke-linecap", grid_background.lineend)
.style("stroke-width", grid_background.size)
.style("stroke-dasharray", linetypesize2dasharray(
grid_background.linetype, grid_background.size))
;
});
}
});
// drawing border
// uses insert to draw it right before the #plottitle
if(Object.keys(p_info.panel_border).length > 1) {
background.append("rect")
.attr("x", plotdim.xstart)
.attr("y", plotdim.ystart)
.attr("width", plotdim.xend - plotdim.xstart)
.attr("height", plotdim.yend - plotdim.ystart)
.attr("class", "border_rect")
.style("fill", p_info.panel_border.fill)
.style("stroke", p_info.panel_border.colour)
.style("stroke-dasharray", function() {
return linetypesize2dasharray(p_info.panel_border.linetype,
p_info.panel_border.size);
});
}
} //end of for(layout_i
// After drawing all backgrounds, we can draw the axis labels.
if(p_info["ytitle"]){
svg.append("text")
.text(p_info["ytitle"])
.attr("class", "ytitle")
.style("text-anchor", "middle")
.style("font-size", default_axis_px + "px")
.attr("transform", "translate(" +
ytitle_x +
"," +
(ytitle_top + ytitle_bottom)/2 +
")rotate(270)")
;
}
if(p_info["xtitle"]){
svg.append("text")
.text(p_info["xtitle"])
.attr("class", "xtitle")
.style("text-anchor", "middle")
.style("font-size", default_axis_px + "px")
.attr("transform", "translate(" +
(xtitle_left + xtitle_right)/2 +
"," +
xtitle_y +
")")
;
}
Plots[p_name].scales = scales;
}; //end of add_plot()
function update_legend_opacity(v_name){
var s_info = Selectors[v_name];
s_info.legend_tds.style("opacity", s_info.legend_update_fun);
}
var add_selector = function (s_name, s_info) {
Selectors[s_name] = s_info;
if(s_info.type == "multiple"){
if(!isArray(s_info.selected)){
s_info.selected = [s_info.selected];
}
// legend_update_fun is evaluated in the context of the
// td.legend_entry_label.
s_info.legend_update_fun = function(d){
var i_value = s_info.selected.indexOf(this.textContent);
if(i_value == -1){
return 0.5;
}else{
return 1;
}
}
}else{
s_info.legend_update_fun = function(d){
if(this.textContent == s_info.selected){
return 1;
}else{
return 0.5;
}
}
}
s_info.legend_tds =
element.selectAll("tr."+legend_class_name(s_name)+" td.legend_entry_label")
;
update_legend_opacity(s_name);
}; //end of add_selector()
function get_tsv(g_info, chunk_id){
return g_info.classed + "_chunk" + chunk_id + ".tsv";
}
function getTSVpath(tsv_name){
return dirs.concat(tsv_name).join("/");
}
/**
* copy common chunk tsv to varied chunk tsv, returning an array of
* objects.
*/
function copy_chunk(g_info, varied_chunk) {
var varied_by_group = nest_by_group.map(varied_chunk);
var common_by_group = g_info.data[g_info.common_tsv];
var new_varied_chunk = [];
for(group_id in varied_by_group){
var varied_one_group = varied_by_group[group_id];
var common_one_group = common_by_group[group_id];
var common_i = 0;
for(var varied_i=0; varied_i < varied_one_group.length; varied_i++){
// there are two cases: each group of varied data is of length
// 1, or of length of the common data.
if(common_one_group.length == varied_one_group.length){
common_i = varied_i;
}
var varied_obj = varied_one_group[varied_i];
var common_obj = common_one_group[common_i];
for(col in common_obj){
if(col != "group"){
varied_obj[col] = common_obj[col];
}
}
new_varied_chunk.push(varied_obj);
}
}
return new_varied_chunk;
}
// update_geom is called from add_geom and update_selector. It
// downloads data if necessary, and then calls draw_geom.
var update_geom = function (g_name, selector_name) {
var g_info = Geoms[g_name];
// First apply chunk_order selector variables.
var chunk_id = g_info.chunks;
g_info.chunk_order.forEach(function (v_name) {
if(chunk_id == null){
return; // no data in a higher up chunk var.
}
var value = Selectors[v_name].selected;
if(chunk_id.hasOwnProperty(value)){
chunk_id = chunk_id[value];
}else{
chunk_id = null; // no data to show in this subset.
}
});
if(chunk_id == null){
draw_panels(g_info, [], selector_name); //draw nothing.
return;
}
var tsv_name = get_tsv(g_info, chunk_id);
// get the data if it has not yet been downloaded.
g_info.tr.select("td.chunk").text(tsv_name);
if(g_info.data.hasOwnProperty(tsv_name)){
draw_panels(g_info, g_info.data[tsv_name], selector_name);
}else{
g_info.tr.select("td.status").text("downloading");
var svg = SVGs[g_name];
var loading = svg.append("text")
.attr("class", "loading"+tsv_name)
.text("Downloading "+tsv_name+"...")
.attr("font-size", 9)
//.attr("x", svg.attr("width")/2)
.attr("y", 10)
.style("fill", "red");
download_chunk(g_info, tsv_name, function(chunk){
loading.remove();
draw_panels(g_info, chunk, selector_name);
});
}
};
var draw_panels = function(g_info, chunk, selector_name) {
// derive the plot name from the geometry name
var g_names = g_info.classed.split("_");
var p_name = g_names[g_names.length - 1];
var panels = Plots[p_name].layout.PANEL;
panels.forEach(function(panel) {
draw_geom(g_info, chunk, selector_name, panel);
});
};
function download_next(g_name){
var g_info = Geoms[g_name];
var selector_value = Animation.sequence[g_info.seq_i];
var chunk_id = g_info.chunks[selector_value];
var tsv_name = get_tsv(g_info, chunk_id);
g_info.seq_count += 1;
if(Animation.sequence.length == g_info.seq_count){
Animation.done_geoms[g_name] = 1;
return;
}
g_info.seq_i += 1;
if(g_info.seq_i == Animation.sequence.length){
g_info.seq_i = 0;
}
if(typeof(chunk_id) == "string"){
download_chunk(g_info, tsv_name, function(chunk){
download_next(g_name);
})
}else{
download_next(g_name);
}
}
// download_chunk is called from update_geom and download_next.
function download_chunk(g_info, tsv_name, funAfter){
if(g_info.download_status.hasOwnProperty(tsv_name)){
var chunk;
if(g_info.data_is_object){
chunk = {};
}else{
chunk = [];
}
funAfter(chunk);
return; // do not download twice.
}
g_info.download_status[tsv_name] = "downloading";
// prefix tsv file with appropriate path
var tsv_file = getTSVpath(tsv_name);
d3.tsv(tsv_file, function (error, response) {
// First convert to correct types.
g_info.download_status[tsv_name] = "processing";
response = convert_R_types(response, g_info.types);
wait_until_then(500, function(){
if(g_info.common_tsv) {
return g_info.data.hasOwnProperty(g_info.common_tsv);
}else{
return true;
}
}, function(){
if(g_info.common_tsv) {
// copy data from common tsv to varied tsv
response = copy_chunk(g_info, response);
}
var nest = d3.nest();
g_info.nest_order.forEach(function (v_name) {
nest.key(function (d) {
return d[v_name];
});
});
var chunk = nest.map(response);
g_info.data[tsv_name] = chunk;
g_info.tr.select("td.downloaded").text(d3.keys(g_info.data).length);
g_info.download_status[tsv_name] = "saved";
funAfter(chunk);
});
});
}//download_chunk.
// update_geom is responsible for obtaining a chunk of downloaded
// data, and then calling draw_geom to actually draw it.
var draw_geom = function(g_info, chunk, selector_name, PANEL){
g_info.tr.select("td.status").text("displayed");
var svg = SVGs[g_info.classed];
// derive the plot name from the geometry name
var g_names = g_info.classed.split("_");
var p_name = g_names[g_names.length - 1];
var scales = Plots[p_name].scales[PANEL];
var selected_arrays = [ [] ]; //double array necessary.
var has_clickSelects = g_info.aes.hasOwnProperty("clickSelects");
var has_clickSelects_variable =
g_info.aes.hasOwnProperty("clickSelects.variable");
g_info.subset_order.forEach(function (aes_name) {
var selected, values;
var new_arrays = [];
if(0 < aes_name.indexOf(".variable")){
selected_arrays.forEach(function(old_array){
var some_data = chunk;
old_array.forEach(function(value){
if(some_data.hasOwnProperty(value)) {
some_data = some_data[value];
} else {
some_data = {};
}
})
values = d3.keys(some_data);
values.forEach(function(s_name){
var selected = Selectors[s_name].selected;
var new_array = old_array.concat(s_name).concat(selected);
new_arrays.push(new_array);
})
})
}else{//not .variable aes:
if(aes_name == "PANEL"){
selected = PANEL;
}else{
var s_name = g_info.aes[aes_name];
selected = Selectors[s_name].selected;
}
if(isArray(selected)){
values = selected; //multiple selection.
}else{
values = [selected]; //single selection.
}
values.forEach(function(value){
selected_arrays.forEach(function(old_array){
var new_array = old_array.concat(value);
new_arrays.push(new_array);
})
})
}
selected_arrays = new_arrays;
});
// data can be either an array[] if it will be directly involved
// in a data-bind, or an object{} if it will be involved in a
// data-bind by group (e.g. geom_line).
var data;
if(g_info.data_is_object){
data = {};