Zhihao's Studio.

associate brush

Word count: 2,531 / Reading time: 14 min
2014/11/15 Share

这篇博客记录了在上一篇博客加入scatterplot matrix的基础上,实现了associate brush的操作,即,从RadViz中brush一块区域,右边16个scatterplot里对应的点都会高亮出来,其他的点将暗淡下去;同样的,从右边16个scatterplot matrix里任一scatterplot cell里brush一些点,另外15个cell以及左边的RadViz里相应的点都会被highlight出来。具体的效果如下图:

代码如下:

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
\<!DOCTYPE html\>
\<html\>
\<meta http-equiv="content-type" content="text/html;charset=gbk"\>
\<meta name="author" content="oscar999"\>
\<head\>
\<script type="text/javascript" src="script/d3.v3.js"\> \</script\>
\<style\>
body {
width: 1440px;
margin: 15px auto 0;
background: #fff;
}
# RadViz{
float:left;margin-top:20px;margin-left:10px;width:510px; height:510px; border-width:1px; border-style:solid; border-color:#bfb7b0;
}
\</style\>
\<title\>RadViz\</title\>
\</head\>
\<body\>
\<div id="RadViz"\> \</div\>
\<script src="kNN.js"\>\</script\>
\<script src="dunnsIndex.js"\>\</script\>
\<style\>
svg {
font: 10px sans-serif;
padding: 10px;
}
.axis,
.frame {
shape-rendering: crispEdges;
}
.axis line {
stroke: #ddd;
}
.axis path {
display: none;
}
.cell text {
font-weight: bold;
text-transform: capitalize;
}
.frame {
fill: none;
stroke: #aaa;
}
circle {
fill-opacity: .7;
}
circle.hidden {
fill: #ccc !important;
}
.extent {
fill: #000;
fill-opacity: .125;
stroke: #fff;
}
\</style\>
\<script type="text/javascript"\>
var DimNum = 4; //维度数
var ordertxt = [1,2,3,4](); //order顺序
var orderNum = ordertxt.length; //order的个数
var UnitRadius=360/orderNum; //每个单元的角度
var centerX=240.0; //圆心
var centerY=270.0;
var r = 190; //半径
var outerRadius = r+10; //内半径
var innerRadius = r-10; //外半径
var DimPoint = new Array();
var Radius = new Array();
var NodePoint =new Array();
//compute DimPoint
for(var i=0;i\<orderNum;i++){
DimPoint[i]()=new Array();
}
for(var i=0; i\<orderNum;i++){
Radius[i]() = (UnitRadius*i)*Math.PI/180;
DimPoint[i]()[0]()=r\*Math.cos(Radius[i]()); //DA的x坐标
DimPoint[i]()[1]()=r\*Math.sin(Radius[i]()); //DA的y坐标
DimPoint[i]()[2]()=ordertxt[i](); //DA的值
}
//compute Data Point
d3.csv("iris-normalization.csv",function(RecordData){
for(var i=0;i\<RecordData.length;i++){
NodePoint[i]()=new Array();
}
for(var i=0;i\<RecordData.length;i++){
var tt=RecordData[i]().dimData;
var t1=tt.split(",");
for(var j=0;j\<t1.length;j++){
t1[j]()=parseFloat(t1[j]());
}
var t2=new Array(t1.length);
for(var k=1;k\<=ordertxt.length;k++)
{
t2[k-1]()=t1[ordertxt[k-1]()-1];
}
// console.log(t2)
// console.log(t1+" ---")
RecordData[i]().dimData = t2;
}
var dataStr = "";
for(var i=0;i\<RecordData.length;i++){
var SumDown = getSumDown(RecordData[i]().dimData,orderNum);
var SumUpX = getSumUpX(RecordData[i]().dimData,Radius,orderNum);
var SumUpY = getSumUpY(RecordData[i]().dimData,Radius,orderNum);
var CoordX = SumUpX/SumDown;
var CoordY = SumUpY/SumDown;
NodePoint[i]()[0]() = CoordX+centerX;
NodePoint[i]()[1]() = CoordY+centerY;
NodePoint[i]()[2]() = RecordData[i]().classId;
NodePoint[i]()[3]() = RecordData[i]().id;
dataStr = dataStr+NodePoint[i]()[3]()+","+NodePoint[i]()[0]()+","+NodePoint[i]()[1]()+","+NodePoint[i]()[2]()+"\n";
}
// console.log(dataStr);
// console.log(dataStr);
var width = 600, height = 500;
var svg = d3.select(RadViz).append("svg").attr("width",width).attr("height", height) ;
var xScale = d3.scale.linear().domain([10,510]())
.range([10,510]());
var yScale = d3.scale.linear().domain([10,510]())
.range([20,510-20]());
var brush = d3.svg.brush()
.x(xScale)
.y(yScale)
.extent([0,0](),[0,0]())
.on('brush',brushed)
.on('brushstart',brushstart)
.on('brushend',brushend);
function brushstart(){
d3.select('body').selectAll('.cell').selectAll('circle')
// .style('fill','#ccc');
.classed('hidden',true);
}
function brushend(){
if (brush.empty()) {
d3.select('body').selectAll('.cell').selectAll('circle')
.classed('hidden', function () {
return false;
});
}
}
function brushed(){
var extent = brush.extent();
var xmin = extent[0]()[0]();
var xmax = extent[1]()[0]();
var ymin = extent[0]()[1]();
var ymax = extent[1]()[1]();
// console.log(xmax + " " + xmin);
// console.log(ymax + " " + ymin);
Nodes.style("fill",function(d, i) {
var color;
// console.log(d);
// d3.select('body').selectAll('.cell').selectAll('circle')
// .style('fill','#ccc');
if(d[0]()\>=xmin && d[0]()\<=xmax && d[1]()\>=ymin && d[1]()\<=ymax){
d3.select('body').selectAll('.cell').selectAll('circle')
.filter(function(dd){return dd.id==d[3]();})
.classed('hidden',false);
return 'red';
}else{
// return color(d[2]());
if (d[2]() == "1")
color = "#ffc2ce";
else if (d[2]() == "2")
color = "#0ffa1d";
else if (d[2]() == "3")
color = "#fee905";
return color;
}
});
}
svg.append('g').call(brush)
.selectAll('rect')
.style('fill-opacity',0.3);
var dimdata = []();
for ( var i = 0; i \< DimNum; i++) {
dimdata[i]() = 1;
}
//draw arc
var pie = d3.layout.pie().sort(null);
var arc = d3.svg.arc()
.startAngle(function(d,i){
return (UnitRadius*i+90-0.5*UnitRadius+1)\* Math.PI/180})
.endAngle(function(d,i){return (UnitRadius*i+90+0.5*UnitRadius)\*Math.PI/180})
.innerRadius(innerRadius)
.outerRadius(outerRadius)
;
var arcs = svg.selectAll("g.arc").data(pie(dimdata)).enter()
.append("g").attr("class", "arc").attr("transform",
"translate(" + centerX + "," + centerY + ")")
;
arcs.append("path")
//.style("stroke","red")
//.style("stroke-opacity",0)
// .style("stroke-width",0)
.attr("fill",function(d, i) {
var color1=["#006650","#f5ab00","#db4527","#005687"]();
return color1[i]();
})
.attr("d", arc);
//show Dimension Point
svg.selectAll("circle")
.data(DimPoint)
.enter()
.append("circle")
.attr("cx", function(d) {
return d[0]()+centerX;
})
.attr("cy", function(d) {
return d[1]()+centerY;
}).attr("r", 4)
.attr("opacity",0.8);
svg.selectAll("text")
.data(DimPoint)
.enter()
.append("text")
.text(function(d) {
return d[2]();
})
.attr("x", function(d) {
return d[0]()+centerX ;
}).attr("y", function(d) {
return d[1]()+centerY;
}).attr("font-family", "sans-serif")
.attr("font-size", 15)
.attr("stroke-width",2)
.attr("fill", "black");
//show data point
var Nodes = svg.selectAll("RadViz")
.data(NodePoint)
.enter()
.append("circle")
.attr("class", "node")
.attr("id",function(d,i){return i;})
.attr("cx",function(d,i){ return d[0](); })
.attr("cy",function(d,i){return d[1]();})
.attr("r", 4.5)
.attr("class","nodes")
.style("opacity",0.8)
.style("fill",function(d, i) {
var color;
if (d[2]() == "1")
color = "#ffc2ce";
else if (d[2]() == "2")
color = "#0ffa1d";
else if (d[2]() == "3")
color = "#fee905";
return color;
});
Nodes.on("mouseenter",function(){d3.select(this).style('fill','red')
var x = d3.select(this).attr('cx');
var y = d3.select(this).attr('cy');
// alert(x+" "+y)
// var sequence = new Array();
sequence = kNN(NodePoint,[x,y](),5);
var NN= Nodes.filter(function(d,i){
var flag=false;
for(var i=0;i\<sequence.length;i++)
{
if(d[3]()==sequence[i]()){
flag=true;
}
}
return flag;
}).style('fill','red')
})
.on('mouseleave',function(d,i){Nodes.style("fill",function(d, i) {
var color;
if (d[2]() == "1")
color = "#ffc2ce";
else if (d[2]() == "2")
color = "#0ffa1d";
else if (d[2]() == "3")
color = "#fee905";
return color;
})})
.style("stroke", "black")
.style("stroke-width", 0.8)
.append("title")
.text(function(d) { return "point"+d[3]()+"-class:"+d[2](); })
Nodes.on('click',function(d,i){
// var x = d3.select(this).attr('cx')
// var y = d3.select(this).attr('cy')
var x = d[0]();
var y = d[1]();
// alert(x+" "+y)
// var sequence = new Array();
sequence = kNN(NodePoint,[x,y](),5);
// alert(sequence);
var Str="";
for(var kk=0;kk\<sequence.length;kk++){
Str=Str+NodePoint[sequence[kk]()][2]()+" ";
}
alert(Str);
})
var KNum =15;
var right = 0;
for(var i=0;i\<NodePoint.length;i++) {
var tmp = new Array();
tmp = [NodePoint[i]()[0](), NodePoint[i]()[1]()];
// console.log(tmp);
sequence = kNN(NodePoint, tmp, KNum);
var count1 = 0;
var count2 = 0;
var count3 = 0;
for (var kk = 0; kk \< sequence.length; kk++) {
if (NodePoint[sequence[kk]()][2]() == 1) {
count1++;
} else if (NodePoint[sequence[kk]()][2]() == 2) {
count2++;
} else if (NodePoint[sequence[kk]()][2]() == 3) {
count3++;
}
}
var max = Math.max(count1, Math.max(count2, count3))
var predict = 0;
if (count1 == max) {
predict = 1;
} else if (count2 == max) {
predict = 2;
} else if (count3 == max) {
predict = 3;
}
if (NodePoint[i]()[2]() == predict) {
right++;
} else {
console.log("predict is " + predict + " NodePoint is " + NodePoint[i]()[2]())
}
}
console.log(right);
var dunnsindex = (dunnsIndex(3,NodePoint));
svg.append('text')
.text('Dunns Index: '+dunnsindex.toFixed(3))
.attr('x',width)
.attr('y',height)
.attr('dx',-250)
});//.data
function getSumUpX(RecordData,Radius,orderNum){
var TempUpX=0;
for(var i=0;i\<orderNum;i++){
TempUpX=TempUpX+r*RecordData[i]()*Math.cos(Radius[i]());
}
return TempUpX;
}
function getSumUpY(RecordData,Radius,orderNum){
var TempUpY=0;
for(var i=0;i\<orderNum;i++){
TempUpY=TempUpY+r*RecordData[i]()*Math.sin(Radius[i]());
}
return TempUpY;
}
function getSumDown(RecordData,orderNum){
var TempDown=0;
for(var i=0;i\<orderNum;i++){
TempDown =TempDown+RecordData[i]();
}
return TempDown;
}
\</script\>
\<style\>
svg {
font: 10px sans-serif;
padding: 10px;
}
.axis,
.frame {
shape-rendering: crispEdges;
}
.axis line {
stroke: #ddd;
}
.axis path {
display: none;
}
.cell text {
font-weight: bold;
text-transform: capitalize;
}
.frame {
fill: none;
stroke: #aaa;
}
circle {
fill-opacity: .7;
}
circle.hidden {
fill: #ccc !important;
}
.extent {
fill: #000;
fill-opacity: .125;
stroke: #fff;
}
\</style\>
\<script\>
var width = 960,
size = 130,
padding = 20;
var x = d3.scale.linear()
.range([padding / 2, size - padding / 2]());
var y = d3.scale.linear()
.range([size - padding / 2, padding / 2]());
var xAxis = d3.svg.axis()
.scale(x)
.orient("bottom")
.ticks(6);
var yAxis = d3.svg.axis()
.scale(y)
.orient("left")
.ticks(6);
var color = d3.scale.category10();
d3.csv("flowers.csv", function(error, data) {
if (error) throw error;
var domainByTrait = {},
traits = d3.keys(data[0]()).filter(function(d) { return d !== "species"&&d!="id"; }),
n = traits.length;
traits.forEach(function(trait) {
domainByTrait[trait]() = d3.extent(data, function(d) { return d[trait](); });
});
xAxis.tickSize(size \* n);
yAxis.tickSize(-size \* n);
var brush = d3.svg.brush()
.x(x)
.y(y)
.on("brushstart", brushstart)
.on("brush", brushmove)
.on("brushend", brushend);
var svg = d3.select("body").append("svg")
.attr("width", size \* n + padding)
.attr("height", size \* n + padding)
.append("g")
.attr("transform", "translate(" + padding + "," + padding / 2 + ")");
svg.selectAll(".x.axis")
.data(traits)
.enter().append("g")
.attr("class", "x axis")
.attr("transform", function(d, i) { return "translate(" + (n - i - 1) \* size + ",0)"; })
.each(function(d) { x.domain(domainByTrait[d]()); d3.select(this).call(xAxis); });
svg.selectAll(".y.axis")
.data(traits)
.enter().append("g")
.attr("class", "y axis")
.attr("transform", function(d, i) { return "translate(0," + i \* size + ")"; })
.each(function(d) { y.domain(domainByTrait[d]()); d3.select(this).call(yAxis); });
var cell = svg.selectAll(".cell")
.data(cross(traits, traits))
.enter().append("g")
.attr("class", "cell")
.attr("transform", function(d) { return "translate(" + (n - d.i - 1) * size + "," + d.j * size + ")"; })
.each(plot);
// Titles for the diagonal.
cell.filter(function(d) { return d.i === d.j; }).append("text")
.attr("x", padding)
.attr("y", padding)
.attr("dy", ".71em")
.text(function(d) { return d.x; });
cell.call(brush);
function plot(p) {
var cell = d3.select(this);
x.domain(domainByTrait[p.x]());
y.domain(domainByTrait[p.y]());
cell.append("rect")
.attr("class", "frame")
.attr("x", padding / 2)
.attr("y", padding / 2)
.attr("width", size - padding)
.attr("height", size - padding);
cell.selectAll("circle")
.data(data)
.enter().append("circle")
.attr("cx", function(d) { return x(d[p.x]()); })
.attr("cy", function(d) { return y(d[p.y]()); })
.attr("r", 4)
.style("fill", function(d) {
return color(d.species);
});
}
var brushCell;
// Clear the previously-active brush, if any.
function brushstart(p) {
if (brushCell !== this) {
d3.select(brushCell).call(brush.clear());
x.domain(domainByTrait[p.x]());
y.domain(domainByTrait[p.y]());
brushCell = this;
}
d3.select('#RadViz').selectAll('.nodes')
.classed('hidden',true);
}
// Highlight the selected circles.
function brushmove(p) {
var e = brush.extent();
svg.selectAll("circle").classed("hidden", function(d) {
if( e[0]()[0]() \> d[p.x]() || d[p.x]() \> e[1]()[0]()
|| e[0]()[1]() \> d[p.y]() || d[p.y]() \> e[1]()[1]()){
return true;
}else{
// console.log(d);
d3.select('#RadViz').selectAll('.nodes')
.filter(function(dd){
return d.id==dd[3]();
})
.classed('hidden',false);
return false;
}
});
}
// If the brush is empty, select all circles.
function brushend() {
if (brush.empty())
{
svg.selectAll(".hidden").classed("hidden", false);
d3.select('#RadViz').selectAll('.nodes')
.classed('hidden',false);
}
}
d3.select(self.frameElement).style("height", size \* n + padding + 20 + "px");
});
function cross(a, b) {
var c = [](), n = a.length, m = b.length, i, j;
for (i = -1; ++i \< n;) for (j = -1; ++j \< m;) c.push({x: a[i](), i: i, y: b[j](), j: j});
return c;
}
\</script\>
\</body\>
\</html\>

这次实现的associate brush操作,有下面需要注意和值得总结的地方:

  1. 首先考虑的是,既然需要实现associate,就必须要有将两个view联系起来的东西,可以类比数据库表中的外键,两个表都有这个键,就可以联系起来。
  2. 特别需要注意的是brushed、brushstart和brushend这三个函数,如何判断一个点在brush的区域里面还是外面,以及如何在brush动作完成之后,继续保持brush点的highlight,需要加一句判断if(brush.emtpy())。
  3. 控制是否高亮,可以给circle加一个class .hidden,这样的话可以方便的给circle加上这个class,也方便后面不要这个class的时候去掉,刚开始实现的时候还加了对原来颜色的判断,很麻烦,而引入了.hidden class后,想加上这个class的时候就一句 .classed(‘hidden’,true)就可以了,不想要的时候,用.classed(‘hidden’,false)就去掉了这个包袱,非常方便。
  4. 关于hidden这个class,还遇到了一个大坑。在前端测试可以通过,但是加入了node.js的后端之后,始终测试无法通过,出现了hidden的类完全消失了的情况,其他地方怎么找也找不到问题,可能是hidden class是node的保留class?将hidden改成hidden1之后问题就解决了,以后这种敏感的词前面还是加上my的好,如myHidden…

发现一个bug,就是brush之后,如果再次resize brush的框,对应的已经着色了的其他点不会相应的变化,需要修改brushmove函数为:

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
function brushmove(p) {
var e = brush.extent();
svg.selectAll("circle").classed("hidden", function(d) {
if( e[0]()[0]() \> d[p.x]() || d[p.x]() \> e[1]()[0]()
|| e[0]()[1]() \> d[p.y]() || d[p.y]() \> e[1]()[1]()){
d3.select('#RadViz').selectAll('.nodes')
.filter(function(dd){
return d.id==dd[3]()
}).classed('hidden',true);
return true;
}else{
// console.log(d);
d3.select('#RadViz').selectAll('.nodes')
.filter(function(dd){
return d.id==dd[3]();
})
.classed('hidden',false);
return false;
}
});
}
CATALOG