forked from syntagmatic/parallel-coordinates
-
Notifications
You must be signed in to change notification settings - Fork 0
/
d3.parcoords.js
2317 lines (1994 loc) · 64.2 KB
/
d3.parcoords.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
d3.parcoords = function(config) {
var __ = {
data: [],
highlighted: [],
dimensions: {},
dimensionTitleRotation: 0,
brushed: false,
brushedColor: null,
alphaOnBrushed: 0.0,
mode: "default",
rate: 20,
width: 600,
height: 300,
margin: { top: 24, right: 0, bottom: 12, left: 0 },
nullValueSeparator: "undefined", // set to "top" or "bottom"
nullValueSeparatorPadding: { top: 8, right: 0, bottom: 8, left: 0 },
color: "#069",
composite: "source-over",
alpha: 0.7,
bundlingStrength: 0.5,
bundleDimension: null,
smoothness: 0.0,
showControlPoints: false,
hideAxis : []
};
extend(__, config);
if (config && config.dimensionTitles) {
console.warn("dimensionTitles passed in config is deprecated. Add title to dimension object.");
d3.entries(config.dimensionTitles).forEach(function(d) {
if (__.dimensions[d.key]) {
__.dimensions[d.key].title = __.dimensions[d.key].title ? __.dimensions[d.key].title : d.value;
} else {
__.dimensions[d.key] = {
title: d.value
};
}
});
}
var pc = function(selection) {
selection = pc.selection = d3.select(selection);
__.width = selection[0][0].clientWidth;
__.height = selection[0][0].clientHeight;
// canvas data layers
["marks", "foreground", "brushed", "highlight"].forEach(function(layer) {
canvas[layer] = selection
.append("canvas")
.attr("class", layer)[0][0];
ctx[layer] = canvas[layer].getContext("2d");
});
// svg tick and brush layers
pc.svg = selection
.append("svg")
.attr("width", __.width)
.attr("height", __.height)
.append("svg:g")
.attr("transform", "translate(" + __.margin.left + "," + __.margin.top + ")");
return pc;
};
var events = d3.dispatch.apply(this,["render", "resize", "highlight", "brush", "brushend", "axesreorder"].concat(d3.keys(__))),
w = function() { return __.width - __.margin.right - __.margin.left; },
h = function() { return __.height - __.margin.top - __.margin.bottom; },
flags = {
brushable: false,
reorderable: false,
axes: false,
interactive: false,
debug: false
},
xscale = d3.scale.ordinal(),
dragging = {},
line = d3.svg.line(),
axis = d3.svg.axis().orient("left").ticks(5),
g, // groups for axes, brushes
ctx = {},
canvas = {},
clusterCentroids = [];
// side effects for setters
var side_effects = d3.dispatch.apply(this,d3.keys(__))
.on("composite", function(d) {
ctx.foreground.globalCompositeOperation = d.value;
ctx.brushed.globalCompositeOperation = d.value;
})
.on("alpha", function(d) {
ctx.foreground.globalAlpha = d.value;
ctx.brushed.globalAlpha = d.value;
})
.on("brushedColor", function (d) {
ctx.brushed.strokeStyle = d.value;
})
.on("width", function(d) { pc.resize(); })
.on("height", function(d) { pc.resize(); })
.on("margin", function(d) { pc.resize(); })
.on("rate", function(d) {
brushedQueue.rate(d.value);
foregroundQueue.rate(d.value);
})
.on("dimensions", function(d) {
__.dimensions = pc.applyDimensionDefaults(d3.keys(d.value));
xscale.domain(pc.getOrderedDimensionKeys());
pc.sortDimensions();
if (flags.interactive){pc.render().updateAxes();}
})
.on("bundleDimension", function(d) {
if (!d3.keys(__.dimensions).length) pc.detectDimensions();
pc.autoscale();
if (typeof d.value === "number") {
if (d.value < d3.keys(__.dimensions).length) {
__.bundleDimension = __.dimensions[d.value];
} else if (d.value < __.hideAxis.length) {
__.bundleDimension = __.hideAxis[d.value];
}
} else {
__.bundleDimension = d.value;
}
__.clusterCentroids = compute_cluster_centroids(__.bundleDimension);
if (flags.interactive){pc.render();}
})
.on("hideAxis", function(d) {
pc.dimensions(pc.applyDimensionDefaults());
pc.dimensions(without(__.dimensions, d.value));
});
// expose the state of the chart
pc.state = __;
pc.flags = flags;
// create getter/setters
getset(pc, __, events);
// expose events
d3.rebind(pc, events, "on");
// getter/setter with event firing
function getset(obj,state,events) {
d3.keys(state).forEach(function(key) {
obj[key] = function(x) {
if (!arguments.length) {
return state[key];
}
if (key === 'dimensions' && Object.prototype.toString.call(x) === '[object Array]') {
console.warn("pc.dimensions([]) is deprecated, use pc.dimensions({})");
x = pc.applyDimensionDefaults(x);
}
var old = state[key];
state[key] = x;
side_effects[key].call(pc,{"value": x, "previous": old});
events[key].call(pc,{"value": x, "previous": old});
return obj;
};
});
};
function extend(target, source) {
for (key in source) {
target[key] = source[key];
}
return target;
};
function without(arr, items) {
items.forEach(function (el) {
delete arr[el];
});
return arr;
};
/** adjusts an axis' default range [h()+1, 1] if a NullValueSeparator is set */
function getRange() {
if (__.nullValueSeparator=="bottom") {
return [h()+1-__.nullValueSeparatorPadding.bottom-__.nullValueSeparatorPadding.top, 1];
} else if (__.nullValueSeparator=="top") {
return [h()+1, 1+__.nullValueSeparatorPadding.bottom+__.nullValueSeparatorPadding.top];
}
return [h()+1, 1];
};
pc.autoscale = function() {
// yscale
var defaultScales = {
"date": function(k) {
var extent = d3.extent(__.data, function(d) {
return d[k] ? d[k].getTime() : null;
});
// special case if single value
if (extent[0] === extent[1]) {
return d3.scale.ordinal()
.domain([extent[0]])
.rangePoints(getRange());
}
return d3.time.scale()
.domain(extent)
.range(getRange());
},
"number": function(k) {
var extent = d3.extent(__.data, function(d) { return +d[k]; });
// special case if single value
if (extent[0] === extent[1]) {
return d3.scale.ordinal()
.domain([extent[0]])
.rangePoints(getRange());
}
return d3.scale.linear()
.domain(extent)
.range(getRange());
},
"string": function(k) {
var counts = {},
domain = [];
// Let's get the count for each value so that we can sort the domain based
// on the number of items for each value.
__.data.map(function(p) {
if (p[k] === undefined && __.nullValueSeparator!== "undefined"){
return; // null values will be drawn beyond the horizontal null value separator!
}
if (counts[p[k]] === undefined) {
counts[p[k]] = 1;
} else {
counts[p[k]] = counts[p[k]] + 1;
}
});
domain = Object.getOwnPropertyNames(counts).sort(function(a, b) {
return counts[a] - counts[b];
});
return d3.scale.ordinal()
.domain(domain)
.rangePoints(getRange());
}
};
d3.keys(__.dimensions).forEach(function(k) {
if (!__.dimensions[k].yscale){
__.dimensions[k].yscale = defaultScales[__.dimensions[k].type](k);
}
});
// xscale
xscale.rangePoints([0, w()], 1);
// canvas sizes
pc.selection.selectAll("canvas")
.style("margin-top", __.margin.top + "px")
.style("margin-left", __.margin.left + "px")
.attr("width", w()+2)
.attr("height", h()+2);
// default styles, needs to be set when canvas width changes
ctx.foreground.strokeStyle = __.color;
ctx.foreground.lineWidth = 1.4;
ctx.foreground.globalCompositeOperation = __.composite;
ctx.foreground.globalAlpha = __.alpha;
ctx.brushed.strokeStyle = __.brushedColor;
ctx.brushed.lineWidth = 1.4;
ctx.brushed.globalCompositeOperation = __.composite;
ctx.brushed.globalAlpha = __.alpha;
ctx.highlight.lineWidth = 3;
return this;
};
pc.scale = function(d, domain) {
__.dimensions[d].yscale.domain(domain);
return this;
};
pc.flip = function(d) {
//__.dimensions[d].yscale.domain().reverse(); // does not work
__.dimensions[d].yscale.domain(__.dimensions[d].yscale.domain().reverse()); // works
return this;
};
pc.commonScale = function(global, type) {
var t = type || "number";
if (typeof global === 'undefined') {
global = true;
}
// try to autodetect dimensions and create scales
if (!d3.keys(__.dimensions).length) {
pc.detectDimensions()
}
pc.autoscale();
// scales of the same type
var scales = d3.keys(__.dimensions).filter(function(p) {
return __.dimensions[p].type == t;
});
if (global) {
var extent = d3.extent(scales.map(function(d,i) {
return __.dimensions[d].yscale.domain();
}).reduce(function(a,b) {
return a.concat(b);
}));
scales.forEach(function(d) {
__.dimensions[d].yscale.domain(extent);
});
} else {
scales.forEach(function(d) {
__.dimensions[d].yscale.domain(d3.extent(__.data, function(d) { return +d[k]; }));
});
}
// update centroids
if (__.bundleDimension !== null) {
pc.bundleDimension(__.bundleDimension);
}
return this;
};
pc.detectDimensions = function() {
pc.dimensions(pc.applyDimensionDefaults());
return this;
};
pc.applyDimensionDefaults = function(dims) {
var types = pc.detectDimensionTypes(__.data);
dims = dims ? dims : d3.keys(types);
var newDims = {};
var currIndex = 0;
dims.forEach(function(k) {
newDims[k] = __.dimensions[k] ? __.dimensions[k] : {};
//Set up defaults
newDims[k].orient= newDims[k].orient ? newDims[k].orient : 'left';
newDims[k].ticks= newDims[k].ticks ? newDims[k].ticks : 5;
newDims[k].innerTickSize= newDims[k].innerTickSize ? newDims[k].innerTickSize : 6;
newDims[k].outerTickSize= newDims[k].outerTickSize ? newDims[k].outerTickSize : 0;
newDims[k].tickPadding= newDims[k].tickPadding ? newDims[k].tickPadding : 3;
newDims[k].type= newDims[k].type ? newDims[k].type : types[k];
newDims[k].index = newDims[k].index ? newDims[k].index : currIndex;
currIndex++;
});
return newDims;
};
pc.getOrderedDimensionKeys = function(){
return d3.keys(__.dimensions).sort(function(x, y){
return d3.ascending(__.dimensions[x].index, __.dimensions[y].index);
});
};
// a better "typeof" from this post: http://stackoverflow.com/questions/7390426/better-way-to-get-type-of-a-javascript-variable
pc.toType = function(v) {
return ({}).toString.call(v).match(/\s([a-zA-Z]+)/)[1].toLowerCase();
};
// try to coerce to number before returning type
pc.toTypeCoerceNumbers = function(v) {
if ((parseFloat(v) == v) && (v != null)) {
return "number";
}
return pc.toType(v);
};
// attempt to determine types of each dimension based on first row of data
pc.detectDimensionTypes = function(data) {
var types = {};
d3.keys(data[0])
.forEach(function(col) {
types[isNaN(Number(col)) ? col : parseInt(col)] = pc.toTypeCoerceNumbers(data[0][col]);
});
return types;
};
pc.render = function() {
// try to autodetect dimensions and create scales
if (!d3.keys(__.dimensions).length) {
pc.detectDimensions()
}
pc.autoscale();
pc.render[__.mode]();
events.render.call(this);
return this;
};
pc.renderBrushed = function() {
if (!d3.keys(__.dimensions).length) pc.detectDimensions();
pc.renderBrushed[__.mode]();
events.render.call(this);
return this;
};
function isBrushed() {
if (__.brushed && __.brushed.length !== __.data.length)
return true;
var object = brush.currentMode().brushState();
for (var key in object) {
if (object.hasOwnProperty(key)) {
return true;
}
}
return false;
};
pc.render.default = function() {
pc.clear('foreground');
pc.clear('highlight');
pc.renderBrushed.default();
__.data.forEach(path_foreground);
};
var foregroundQueue = d3.renderQueue(path_foreground)
.rate(50)
.clear(function() {
pc.clear('foreground');
pc.clear('highlight');
});
pc.render.queue = function() {
pc.renderBrushed.queue();
foregroundQueue(__.data);
};
pc.renderBrushed.default = function() {
pc.clear('brushed');
if (isBrushed()) {
__.brushed.forEach(path_brushed);
}
};
var brushedQueue = d3.renderQueue(path_brushed)
.rate(50)
.clear(function() {
pc.clear('brushed');
});
pc.renderBrushed.queue = function() {
if (isBrushed()) {
brushedQueue(__.brushed);
} else {
brushedQueue([]); // This is needed to clear the currently brushed items
}
};function compute_cluster_centroids(d) {
var clusterCentroids = d3.map();
var clusterCounts = d3.map();
// determine clusterCounts
__.data.forEach(function(row) {
var scaled = __.dimensions[d].yscale(row[d]);
if (!clusterCounts.has(scaled)) {
clusterCounts.set(scaled, 0);
}
var count = clusterCounts.get(scaled);
clusterCounts.set(scaled, count + 1);
});
__.data.forEach(function(row) {
d3.keys(__.dimensions).map(function(p, i) {
var scaled = __.dimensions[d].yscale(row[d]);
if (!clusterCentroids.has(scaled)) {
var map = d3.map();
clusterCentroids.set(scaled, map);
}
if (!clusterCentroids.get(scaled).has(p)) {
clusterCentroids.get(scaled).set(p, 0);
}
var value = clusterCentroids.get(scaled).get(p);
value += __.dimensions[p].yscale(row[p]) / clusterCounts.get(scaled);
clusterCentroids.get(scaled).set(p, value);
});
});
return clusterCentroids;
}
function compute_centroids(row) {
var centroids = [];
var p = d3.keys(__.dimensions);
var cols = p.length;
var a = 0.5; // center between axes
for (var i = 0; i < cols; ++i) {
// centroids on 'real' axes
var x = position(p[i]);
var y = __.dimensions[p[i]].yscale(row[p[i]]);
centroids.push($V([x, y]));
// centroids on 'virtual' axes
if (i < cols - 1) {
var cx = x + a * (position(p[i+1]) - x);
var cy = y + a * (__.dimensions[p[i+1]].yscale(row[p[i+1]]) - y);
if (__.bundleDimension !== null) {
var leftCentroid = __.clusterCentroids.get(__.dimensions[__.bundleDimension].yscale(row[__.bundleDimension])).get(p[i]);
var rightCentroid = __.clusterCentroids.get(__.dimensions[__.bundleDimension].yscale(row[__.bundleDimension])).get(p[i+1]);
var centroid = 0.5 * (leftCentroid + rightCentroid);
cy = centroid + (1 - __.bundlingStrength) * (cy - centroid);
}
centroids.push($V([cx, cy]));
}
}
return centroids;
}
pc.compute_centroids = compute_centroids;
function compute_control_points(centroids) {
var cols = centroids.length;
var a = __.smoothness;
var cps = [];
cps.push(centroids[0]);
cps.push($V([centroids[0].e(1) + a*2*(centroids[1].e(1)-centroids[0].e(1)), centroids[0].e(2)]));
for (var col = 1; col < cols - 1; ++col) {
var mid = centroids[col];
var left = centroids[col - 1];
var right = centroids[col + 1];
var diff = left.subtract(right);
cps.push(mid.add(diff.x(a)));
cps.push(mid);
cps.push(mid.subtract(diff.x(a)));
}
cps.push($V([centroids[cols-1].e(1) + a*2*(centroids[cols-2].e(1)-centroids[cols-1].e(1)), centroids[cols-1].e(2)]));
cps.push(centroids[cols - 1]);
return cps;
};pc.shadows = function() {
flags.shadows = true;
pc.alphaOnBrushed(0.1);
pc.render();
return this;
};
// draw dots with radius r on the axis line where data intersects
pc.axisDots = function(r) {
var r = r || 0.1;
var ctx = pc.ctx.marks;
var startAngle = 0;
var endAngle = 2 * Math.PI;
ctx.globalAlpha = d3.min([ 1 / Math.pow(__.data.length, 1 / 2), 1 ]);
__.data.forEach(function(d) {
d3.entries(__.dimensions).forEach(function(p, i) {
ctx.beginPath();
ctx.arc(position(p), __.dimensions[p.key].yscale(d[p]), r, startAngle, endAngle);
ctx.stroke();
ctx.fill();
});
});
return this;
};
// draw single cubic bezier curve
function single_curve(d, ctx) {
var centroids = compute_centroids(d);
var cps = compute_control_points(centroids);
ctx.moveTo(cps[0].e(1), cps[0].e(2));
for (var i = 1; i < cps.length; i += 3) {
if (__.showControlPoints) {
for (var j = 0; j < 3; j++) {
ctx.fillRect(cps[i+j].e(1), cps[i+j].e(2), 2, 2);
}
}
ctx.bezierCurveTo(cps[i].e(1), cps[i].e(2), cps[i+1].e(1), cps[i+1].e(2), cps[i+2].e(1), cps[i+2].e(2));
}
};
// draw single polyline
function color_path(d, ctx) {
ctx.beginPath();
if ((__.bundleDimension !== null && __.bundlingStrength > 0) || __.smoothness > 0) {
single_curve(d, ctx);
} else {
single_path(d, ctx);
}
ctx.stroke();
};
// draw many polylines of the same color
function paths(data, ctx) {
ctx.clearRect(-1, -1, w() + 2, h() + 2);
ctx.beginPath();
data.forEach(function(d) {
if ((__.bundleDimension !== null && __.bundlingStrength > 0) || __.smoothness > 0) {
single_curve(d, ctx);
} else {
single_path(d, ctx);
}
});
ctx.stroke();
};
// returns the y-position just beyond the separating null value line
function getNullPosition() {
if (__.nullValueSeparator=="bottom") {
return h()+1;
} else if (__.nullValueSeparator=="top") {
return 1;
} else {
console.log("A value is NULL, but nullValueSeparator is not set; set it to 'bottom' or 'top'.");
}
return h()+1;
};
function single_path(d, ctx) {
d3.entries(__.dimensions).forEach(function(p, i) { //p isn't really p
if (i == 0) {
ctx.moveTo(position(p.key), typeof d[p.key] =='undefined' ? getNullPosition() : __.dimensions[p.key].yscale(d[p.key]));
} else {
ctx.lineTo(position(p.key), typeof d[p.key] =='undefined' ? getNullPosition() : __.dimensions[p.key].yscale(d[p.key]));
}
});
};
function path_brushed(d, i) {
if (__.brushedColor !== null) {
ctx.brushed.strokeStyle = d3.functor(__.brushedColor)(d, i);
} else {
ctx.brushed.strokeStyle = d3.functor(__.color)(d, i);
}
return color_path(d, ctx.brushed)
};
function path_foreground(d, i) {
ctx.foreground.strokeStyle = d3.functor(__.color)(d, i);
return color_path(d, ctx.foreground);
};
function path_highlight(d, i) {
ctx.highlight.strokeStyle = d3.functor(__.color)(d, i);
return color_path(d, ctx.highlight);
};
pc.clear = function(layer) {
ctx[layer].clearRect(0, 0, w() + 2, h() + 2);
// This will make sure that the foreground items are transparent
// without the need for changing the opacity style of the foreground canvas
// as this would stop the css styling from working
if(layer === "brushed" && isBrushed()) {
ctx.brushed.fillStyle = pc.selection.style("background-color");
ctx.brushed.globalAlpha = 1 - __.alphaOnBrushed;
ctx.brushed.fillRect(0, 0, w() + 2, h() + 2);
ctx.brushed.globalAlpha = __.alpha;
}
return this;
};
d3.rebind(pc, axis, "ticks", "orient", "tickValues", "tickSubdivide", "tickSize", "tickPadding", "tickFormat");
function flipAxisAndUpdatePCP(dimension) {
var g = pc.svg.selectAll(".dimension");
pc.flip(dimension);
d3.select(this.parentElement)
.transition()
.duration(1100)
.call(axis.scale(__.dimensions[dimension].yscale));
pc.render();
}
function rotateLabels() {
var delta = d3.event.deltaY;
delta = delta < 0 ? -5 : delta;
delta = delta > 0 ? 5 : delta;
__.dimensionTitleRotation += delta;
pc.svg.selectAll("text.label")
.attr("transform", "translate(0,-5) rotate(" + __.dimensionTitleRotation + ")");
d3.event.preventDefault();
}
function dimensionLabels(d) {
return __.dimensions[d].title ? __.dimensions[d].title : d; // dimension display names
}
pc.createAxes = function() {
if (g) pc.removeAxes();
// Add a group element for each dimension.
g = pc.svg.selectAll(".dimension")
.data(pc.getOrderedDimensionKeys(), function(d) {
return d;
})
.enter().append("svg:g")
.attr("class", "dimension")
.attr("transform", function(d) {
return "translate(" + xscale(d) + ")";
});
// Add an axis and title.
g.append("svg:g")
.attr("class", "axis")
.attr("transform", "translate(0,0)")
.each(function(d) { d3.select(this).call( pc.applyAxisConfig(axis, __.dimensions[d]) )
})
.append("svg:text")
.attr({
"text-anchor": "middle",
"y": 0,
"transform": "translate(0,-5) rotate(" + __.dimensionTitleRotation + ")",
"x": 0,
"class": "label"
})
.text(dimensionLabels)
.on("dblclick", flipAxisAndUpdatePCP)
.on("wheel", rotateLabels);
if (__.nullValueSeparator=="top") {
pc.svg.append("line")
.attr("x1", 0)
.attr("y1", 1+__.nullValueSeparatorPadding.top)
.attr("x2", w())
.attr("y2", 1+__.nullValueSeparatorPadding.top)
.attr("stroke-width", 1)
.attr("stroke", "#777")
.attr("fill", "none")
.attr("shape-rendering", "crispEdges");
} else if (__.nullValueSeparator=="bottom") {
pc.svg.append("line")
.attr("x1", 0)
.attr("y1", h()+1-__.nullValueSeparatorPadding.bottom)
.attr("x2", w())
.attr("y2", h()+1-__.nullValueSeparatorPadding.bottom)
.attr("stroke-width", 1)
.attr("stroke", "#777")
.attr("fill", "none")
.attr("shape-rendering", "crispEdges");
}
flags.axes= true;
return this;
};
pc.removeAxes = function() {
g.remove();
return this;
};
pc.updateAxes = function() {
var g_data = pc.svg.selectAll(".dimension").data(pc.getOrderedDimensionKeys());
// Enter
g_data.enter().append("svg:g")
.attr("class", "dimension")
.attr("transform", function(p) { return "translate(" + position(p) + ")"; })
.style("opacity", 0)
.append("svg:g")
.attr("class", "axis")
.attr("transform", "translate(0,0)")
.each(function(d) { d3.select(this).call( pc.applyAxisConfig(axis, __.dimensions[d]) )
})
.append("svg:text")
.attr({
"text-anchor": "middle",
"y": 0,
"transform": "translate(0,-5) rotate(" + __.dimensionTitleRotation + ")",
"x": 0,
"class": "label"
})
.text(dimensionLabels)
.on("dblclick", flipAxisAndUpdatePCP)
.on("wheel", rotateLabels);
// Update
g_data.attr("opacity", 0);
g_data.select(".axis")
.transition()
.duration(1100)
.each(function(d) { d3.select(this).call( pc.applyAxisConfig(axis, __.dimensions[d]) )
});
g_data.select(".label")
.transition()
.duration(1100)
.text(dimensionLabels)
.attr("transform", "translate(0,-5) rotate(" + __.dimensionTitleRotation + ")");
// Exit
g_data.exit().remove();
g = pc.svg.selectAll(".dimension");
g.transition().duration(1100)
.attr("transform", function(p) { return "translate(" + position(p) + ")"; })
.style("opacity", 1);
pc.svg.selectAll(".axis")
.transition()
.duration(1100)
.each(function(d) { d3.select(this).call( pc.applyAxisConfig(axis, __.dimensions[d]) );
});
if (flags.brushable) pc.brushable();
if (flags.reorderable) pc.reorderable();
if (pc.brushMode() !== "None") {
var mode = pc.brushMode();
pc.brushMode("None");
pc.brushMode(mode);
}
return this;
};
pc.applyAxisConfig = function(axis, dimension) {
return axis.scale(dimension.yscale)
.orient(dimension.orient)
.ticks(dimension.ticks)
.tickValues(dimension.tickValues)
.innerTickSize(dimension.innerTickSize)
.outerTickSize(dimension.outerTickSize)
.tickPadding(dimension.tickPadding)
.tickFormat(dimension.tickFormat)
};
// Jason Davies, http://bl.ocks.org/1341281
pc.reorderable = function() {
if (!g) pc.createAxes();
g.style("cursor", "move")
.call(d3.behavior.drag()
.on("dragstart", function(d) {
dragging[d] = this.__origin__ = xscale(d);
})
.on("drag", function(d) {
dragging[d] = Math.min(w(), Math.max(0, this.__origin__ += d3.event.dx));
pc.sortDimensions();
xscale.domain(pc.getOrderedDimensionKeys());
pc.render();
g.attr("transform", function(d) {
return "translate(" + position(d) + ")";
});
})
.on("dragend", function(d) {
// Let's see if the order has changed and send out an event if so.
var i = 0,
j = __.dimensions[d].index,
elem = this,
parent = this.parentElement;
while((elem = elem.previousElementSibling) != null) ++i;
if (i !== j) {
events.axesreorder.call(pc, pc.getOrderedDimensionKeys());
// We now also want to reorder the actual dom elements that represent
// the axes. That is, the g.dimension elements. If we don't do this,
// we get a weird and confusing transition when updateAxes is called.
// This is due to the fact that, initially the nth g.dimension element
// represents the nth axis. However, after a manual reordering,
// without reordering the dom elements, the nth dom elements no longer
// necessarily represents the nth axis.
//
// i is the original index of the dom element
// j is the new index of the dom element
if (i > j) { // Element moved left
parent.insertBefore(this, parent.children[j - 1]);
} else { // Element moved right
if ((j + 1) < parent.children.length) {
parent.insertBefore(this, parent.children[j + 1]);
} else {
parent.appendChild(this);
}
}
}
delete this.__origin__;
delete dragging[d];
d3.select(this).transition().attr("transform", "translate(" + xscale(d) + ")");
pc.render();
}));
flags.reorderable = true;
return this;
};
// Reorder dimensions, such that the highest value (visually) is on the left and
// the lowest on the right. Visual values are determined by the data values in
// the given row.
pc.reorder = function(rowdata) {
var firstDim = pc.getOrderedDimensionKeys()[0];
pc.sortDimensionsByRowData(rowdata);
// NOTE: this is relatively cheap given that:
// number of dimensions < number of data items
// Thus we check equality of order to prevent rerendering when this is the case.
var reordered = false;
reordered = firstDim !== pc.getOrderedDimensionKeys()[0];
if (reordered) {
xscale.domain(pc.getOrderedDimensionKeys());
var highlighted = __.highlighted.slice(0);
pc.unhighlight();
g.transition()
.duration(1500)
.attr("transform", function(d) {
return "translate(" + xscale(d) + ")";
});
pc.render();
// pc.highlight() does not check whether highlighted is length zero, so we do that here.
if (highlighted.length !== 0) {
pc.highlight(highlighted);
}
}
}
pc.sortDimensionsByRowData = function(rowdata) {
var copy = __.dimensions;
var positionSortedKeys = d3.keys(__.dimensions).sort(function(a, b) {
var pixelDifference = __.dimensions[a].yscale(rowdata[a]) - __.dimensions[b].yscale(rowdata[b]);
// Array.sort is not necessarily stable, this means that if pixelDifference is zero
// the ordering of dimensions might change unexpectedly. This is solved by sorting on
// variable name in that case.
if (pixelDifference === 0) {
return a.localeCompare(b);
} // else
return pixelDifference;
});
__.dimensions = {};
positionSortedKeys.forEach(function(p, i){
__.dimensions[p] = copy[p];
__.dimensions[p].index = i;
});
}
pc.sortDimensions = function() {
var copy = __.dimensions;
var positionSortedKeys = d3.keys(__.dimensions).sort(function(a, b) {
return position(a) - position(b);
});
__.dimensions = {};
positionSortedKeys.forEach(function(p, i){
__.dimensions[p] = copy[p];
__.dimensions[p].index = i;
})
};
// pairs of adjacent dimensions
pc.adjacent_pairs = function(arr) {
var ret = [];
for (var i = 0; i < arr.length-1; i++) {
ret.push([arr[i],arr[i+1]]);
};
return ret;
};
var brush = {
modes: {
"None": {
install: function(pc) {}, // Nothing to be done.
uninstall: function(pc) {}, // Nothing to be done.
selected: function() { return []; }, // Nothing to return
brushState: function() { return {}; }
}
},
mode: "None",
predicate: "AND",
currentMode: function() {
return this.modes[this.mode];
}
};
// This function can be used for 'live' updates of brushes. That is, during the
// specification of a brush, this method can be called to update the view.
//
// @param newSelection - The new set of data items that is currently contained
// by the brushes
function brushUpdated(newSelection) {
__.brushed = newSelection;
events.brush.call(pc,__.brushed);
pc.renderBrushed();
}
function brushPredicate(predicate) {
if (!arguments.length) { return brush.predicate; }
predicate = String(predicate).toUpperCase();
if (predicate !== "AND" && predicate !== "OR") {
throw "Invalid predicate " + predicate;
}