Giuliano commited on
Commit
7bba3ca
1 Parent(s): 25aa7c8

Create sketch.js

Browse files
Files changed (1) hide show
  1. sketch.js +64 -0
sketch.js ADDED
@@ -0,0 +1,64 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ let kmeansModel
2
+ const width = 640;
3
+ const height = 480;
4
+ const colDict = {
5
+ 0: 'skyblue',
6
+ 1: 'coral',
7
+ 2: 'olive',
8
+ 3: 'tan',
9
+ 4: 'grey'
10
+ }
11
+
12
+ const names = [{name: 'john'}, {name: 'mary'}, {name: 'anne'}, {name: 'paul'}, {name: 'george'}];
13
+ const data = [{ x: 300, y: 4}, { x: 2000, y: 3}, { x: 450, y: 5}, { x: 1500, y: 2}, { x: 850, y: 4}];
14
+
15
+
16
+ const options = {
17
+ k: 2,
18
+ maxIter: 10,
19
+ threshold: 2,
20
+ };
21
+
22
+
23
+ kmeansModel = ml5.kmeans(data, options, clustersCalculated);
24
+
25
+
26
+ function clustersCalculated() {
27
+ console.log('Points Clustered!');
28
+ console.log(kmeansModel);
29
+
30
+ const dataset = kmeansModel.dataset;
31
+
32
+ //d3.select('svg').remove();
33
+
34
+ const svg = d3.select('svg');
35
+
36
+ const xScale = d3.scaleLinear()
37
+ .domain(d3.extent(dataset, d => d[0]))
38
+ .range([10, width - 100]);
39
+
40
+
41
+ const yScale = d3.scaleLinear()
42
+ .domain(d3.extent(dataset, d => d[1]))
43
+ .range([height - 50, 20]);
44
+
45
+
46
+ const circle_data = svg.selectAll('circle')
47
+ .data(dataset)
48
+ .enter();
49
+
50
+
51
+ const circles = circle_data.append('circle')
52
+ .attr('cx', d => xScale(d[0]))
53
+ .attr('cy', d => yScale(d[1]))
54
+ .attr('r', 9)
55
+ .attr('fill', (d, i) => colDict[dataset[i].centroid]);
56
+
57
+
58
+ circle_data.append('text')
59
+ .attr('dy', d => yScale(d[1]))
60
+ .attr('dx', d => xScale(d[0]))
61
+ .data(names)
62
+ .text(d => d.name);
63
+
64
+ }