-
Notifications
You must be signed in to change notification settings - Fork 0
/
index.html
542 lines (450 loc) · 19.1 KB
/
index.html
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
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>Scatter API</title>
<!--Inlcluding Ajax-->
<script src="https://cdnjs.cloudflare.com/ajax/libs/d3/3.5.6/d3.min.js" charset="utf-8"></script>
<!--Including D3 and D3 Hexbin-->
<script src="http://d3js.org/d3.v3.min.js"></script>
<script src="http://d3js.org/d3.hexbin.v0.js"></script>
<!--Including bootstrap-->
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.11.3/jquery.min.js"></script>
<!-- Latest compiled and minified CSS -->
<link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.6/css/bootstrap.min.css"
integrity="sha384-1q8mTJOASx8j1Au+a5WDVnPi2lkFfwwEAa8hDDdjZlpLegxhjVME1fgjWPGmkzs7" crossorigin="anonymous">
<!-- Latest compiled and minified JavaScript -->
<script src="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.6/js/bootstrap.min.js"
integrity="sha384-0mSbJDEHialfmuBBQP6A4Qrprq5OVfW37PRR3j5ELqxss1yVqOtnepnHVP9aJ7xS"
crossorigin="anonymous"></script>
<!--Including Google Fonts-->
<link href='https://fonts.googleapis.com/css?family=Cuprum|Alegreya+Sans|Yanone+Kaffeesatz' rel='stylesheet'
type='text/css'>
<!--Including highlight-->
<link rel="stylesheet" href="//cdnjs.cloudflare.com/ajax/libs/highlight.js/9.1.0/styles/default.min.css">
<script src="//cdnjs.cloudflare.com/ajax/libs/highlight.js/9.1.0/highlight.min.js"></script>
<script>hljs.initHighlightingOnLoad();</script>
<!--Including Scatter API-->
<script src="js/scatterAPI.js"></script>
<link rel="stylesheet" href="css/scatAPI.css">
<!--Including Font Awesome-->
<link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/font-awesome/4.6.0/css/font-awesome.min.css">
</head>
<body>
<div class="row">
<div class="col-lg-2"></div>
<div class="col-lg-8" id="main" style="min-height: 100vh">
<h1>
My Experiments with D3:
</h1>
<h2>
Building a Scatter-Plot/Hex-bins API
</h2>
<div style="
font-style: italic; color: darkblue;margin-left: 50px;
margin-right: 50px;
text-align: justify; margin-top: 50px">
Update: 4/11/2016<br>
Added polygon Support<br><br>
Update: 2/15/2016<br>
I've updated the code to render hex-bins if the number of points > 10^4. <br>
This results in cleaner, faster and more meaningful visualization of points.<br><br>
</div>
<p>
In a recent research project of mine, I was required to plot a staggering number of scatter plots
in different sizes with different properties (labels, titles, etc).
So it just made sense to wrap up the d3 function into a nice API.
At the time of writing this, the API is not quite robust, but does an okayish job of
resizing with target svg sizes.
</p>
<h3>
Demo
</h3>
<p>
Try playing with the different options.
(All fields are optional)
</p>
<p>
<form id="user-form">
Title:
<input type="text" name="title" placeholder="My epic chart">
<br>
X-label:
<input type="text" name="xlab" placeholder="x-axis">
Y-label:
<input type="text" name="ylab" placeholder="y-axis">
<br>
Number of points: <input type="number" name="numberOfPoints" placeholder="1000">
<br>
X-range from <input type="number" name="xMin" placeholder="0"> to <input type="number" name="xMax"
placeholder="100"><br>
Y-range from <input type="number" name="yMin" placeholder="0"> to <input type="number" name="yMax"
placeholder="100">
<br><br><input type="submit" value="Update">
<form>
<input type="checkbox" id="brush" name="brush" value="brush">Brush
</form>
</form>
</p>
<script>
$("#user-form").submit(function (event) {
event.preventDefault()
var formArray = $('form').serializeArray();
//
drawUserChart(xlab = formArray[1]['value'], ylab = formArray[2]['value'], title = formArray[0]['value'], brush = $('#brush').prop('checked'), minX = parseInt(formArray[4]['value']), maxX = parseInt(formArray[5]['value']), minY = parseInt(formArray[6]['value']), maxY = parseInt(formArray[7]['value']), height = 500, width = 40, numberOfPoints = formArray[3]['value']);
})
</script>
<div class="text-center">
<button type="button" class="btn btn-primary" onclick="drawPolygon()">
New Polygon
</button>
<button type="button" class="btn btn-primary" onclick="undoPolyPoints()">
Undo
</button>
<button type="button" class="btn btn-success" onclick="changePolygonColorGreen()">
Green Polygon
</button>
<button type="button" class="btn btn-danger" onclick="changePolygonColorRed()">
Red Polygon
</button>
</div>
<svg id="main-chart">
<polygon id="userPolygon" points=""></polygon>
<!--<p style="position: relative; bottom: 560px;left:650px">-->
<!--<a> <i class="fa fa-bars" aria-hidden="true"></i></a>-->
<!--</p>-->
</svg>
<p style="margin-top: 30px">
Selected region using brush: <span id="brush-region" style="color: orangered">N/A</span>
</p>
<h2 style="margin-top: 100px; margin-bottom: 30px">
Usage
</h2>
<p>
Scroll down to see the complete HTML, CSS and Javascript code.
<br>
I've tried making the API as consistent with the popular charting APIs (like highcharts) as I possibly
could.
<br>
Calling the function is just one line.
<pre><code class="javascript">
drawScatter(options);
</code></pre>
<p>
The options object looks like this:
</p>
<pre><code class="javascript">
var options = {
'renderTo': "#main-chart",
'data': [{'x': 4, 'y': 5}, {'x': 3, 'y': 5}, {'x': 4, 'y': 2}, {'x': 4, 'y': 7}],
'x-label': "x-axis",
'y-label': "y-axis",
'brush': true,
'title': "My Epic Chart"
};
</code></pre>
<h3>
The CSS
</h3>
<p>
<pre><code>
#main-chart {
display: block;
margin: auto;
margin-top: 50px;
height: 600px;
width: 800px;
background: whitesmoke;
border: 1px solid black;
}
.axis text {
font: 10px sans-serif;
}
.axis path,
.axis line {
fill: none;
stroke: #000;
shape-rendering: crispEdges;
}
.hexagon {
fill: white;
stroke: #000;
stroke-width: .5px;
}
.brush .extent {
stroke: black;
fill: green;
fill-opacity: .125;
shape-rendering: crispEdges;
}
</code></pre>
</p>
</p>
<h3>
The Entire Javascript
</h3>
<p>
<pre><code>
/**
* Created by an5ra on 2/14/2016.
*/
var xStart, yStart, xEnd, yEnd;
function drawScatter(options) {
var container, brushable, data, xlabel, ylabel, title, brush;
//Find an element to render the chart
if ($(options['renderTo']) != undefined) {
container = $(options['renderTo']);
}
else {
console.log("Tried to render chart to an unknown or missing element!");
return;
}
if ('brush' in options) {
brushable = options['brush'];
}
else
brushable = false;
if ('data' in options) {
data = options['data'];
}
else
data = {};
title = options['title'];
xlabel = options['x-label'];
ylabel = options['y-label'];
// finding actual dimensions of div
var heightOfDiv = container.innerHeight();
//console.log(innerHeight);
var widthOfDiv = container.innerWidth();
//console.log(innerWidth);
// finding relative point radius
var radius = 4;
// Setting margins as percentages
var topMargin = heightOfDiv * 0.14;
var bottomMargin = heightOfDiv * 0.1;
var rightMargin = widthOfDiv * 0.08;
var leftMargin = widthOfDiv * 0.09;
var margin = {
top: Math.ceil(topMargin),
right: Math.ceil(rightMargin),
bottom: Math.ceil(bottomMargin),
left: Math.ceil(leftMargin)
},
width = widthOfDiv - margin.left - margin.right,
height = heightOfDiv - margin.top - margin.bottom;
//function to get x Value from data
var xVals = function (d) {
return d['x'];
}
//function to get y Value from data
var yVals = function (d) {
return d['y'];
}
//setting y-scale to fit in the svg window
var yScale = d3.scale.linear()
.domain([0, d3.max(data, yVals)])
.range([height, 0]);
//setting x-scale to fit in the svg window
var xScale = d3.scale.linear()
.domain([0, d3.max(data, xVals)])
.range([0, width]);
// AXES:
// to change tick-sizes: .ticksize(inner, outer) where inner are the normal ticks and outer are the end
ticks
// here we are keeping the inner ticks to the default value of 6 and the outer to negative extremes to
form a box
var xAxis = d3.svg.axis()
.scale(xScale)
.orient("bottom")
.tickSize(6, -height);
var yAxis = d3.svg.axis()
.scale(yScale)
.orient("left")
.tickSize(6, -width);
// declaring brush
var brush = d3.svg.brush()
.x(d3.scale.identity().domain([0, width]))
.y(d3.scale.identity().domain([0, height]))
.on("brush", brushed);
var svg = d3.select(options['renderTo'])
.attr("width", width + margin.left + margin.right)
.attr("height", height + margin.top + margin.bottom)
.append("g") //group that will house the plot
.attr("transform", "translate(" + margin.left + "," + margin.top + ")"); //to center the g in the svg
// ------------------ HEX BIN PROPERTIES --------------------------------------
var points = new Array(data.length)
// converting to array of points
for (var i = 0; i < data.length; i++) {
var point = [xScale(data[i]['x']), yScale(data[i]['y'])]
points[i] = point;
}
/*
Clip-path is made to clip anything that goes out of the svg
*/
svg.append("clipPath")
.attr("id", "clip")
.append("rect")
.attr("class", "mesh")
.attr("width", width)
.attr("height", height);
var hexColor = d3.scale.linear()
.domain([0, 20])
.range(["white", "darkblue"])
.interpolate(d3.interpolateLab);
var hexColorRed = d3.scale.linear()
.domain([0, 20])
.range(["white", "maroon"])
.interpolate(d3.interpolateLab);
var hexbin = d3.hexbin()
.size([width, height])
.radius(20);
if(points.length>10000)
drawHexbin();
else
drawScatterPlot();
// ------------------- DRAWING PLOTS FUNCTIONS -------------------------------------
/**
* DRAWING A HEXBIN PLOT
*/
function drawHexbin() {
var hexbinPlot = svg.append("g")
.attr("clip-path", "url(#clip)")
.selectAll(".hexagon")
.data(hexbin(points)) // returns an array of bins
.enter().append("path") // enter returns all fictitious elements according to number of data points
.attr("class", "hexagon") // the class hexagon is a custom class made to incorporate stroke and fill
.attr("d", hexbin.hexagon())
.attr("transform", function (d) {
return "translate(" + d.x + "," + d.y + ")"; // Each bin (or d) returned by hexbin(points) is an array
containing the bin’s points
})
;
//load the points animatedly
//reference url for ease: https://github.com/mbostock/d3/wiki/Transitions#d3_ease
hexbinPlot.transition()
.style("fill", function (d) {
return hexColor(d.length);
})
.duration(900)
.ease('sin');
}
/**
* DRAWING A SCATTERPLOT
*/
function drawScatterPlot() {
var scatterPlot = svg.append('g')
.attr("clip-path", "url(#clip)")
.selectAll('circle').data(data)
.enter().append('circle')
.style('fill', "darkblue")
.attr('r', 0)
.attr('cx', function (d) {
return xScale(d['x'])
})
.attr('cy', function (d) {
return yScale(d['y'])
})
;
//load the points animatedly
//reference url for ease: https://github.com/mbostock/d3/wiki/Transitions#d3_ease
//load the points animatedly
scatterPlot.transition()
.attr('r', 4)
.duration(1000)
.ease('elastic')
}
// adding the axes
svg.append("g")
.attr("class", "y axis")
.call(yAxis);
svg.append("g")
.attr("class", "x axis")
.attr("transform", "translate(0," + height + ")")
.call(xAxis);
// adding the axes labels
svg.append("text")
.attr("text-anchor", "middle") // this makes it easy to centre the text as the transform is applied to
the anchor
.attr("transform", "translate(" + (-leftMargin / 2) + "," + (height / 2) + ")rotate(-90)") // text is
drawn off the screen top left, move down and out and rotate
.text(ylabel);
svg.append("text")
.attr("text-anchor", "middle") // this makes it easy to centre the text as the transform is applied to
the anchor
.attr("transform", "translate(" + (width / 2) + "," + (height + 6 + (bottomMargin / 2)) + ")") // centre
below axis
.text(xlabel);
// title
svg.append("text")
.attr("class", "chart-title")
.attr("text-anchor", "middle") // this makes it easy to centre the text as the transform is applied to
the anchor
.attr("transform", "translate(" + (width / 2) + "," + ( -20 + ")")) // text is drawn off the screen top
left, move down and out and rotate
.text(title);
// adding the brush
if (brushable)
svg.append("g")
.attr("class", "brush")
.call(brush)
.call(brush.event);
function brushed() {
var extent = brush.extent();
xStart = xScale.invert(extent[0][0]);
yStart = yScale.invert(extent[0][1]);
xEnd = xScale.invert(extent[1][0]);
yEnd = yScale.invert(extent[1][1]);
xStart = Math.round(xStart * 100) / 100;
xEnd = Math.round(xEnd * 100) / 100;
yStart = Math.round(yStart * 100) / 100;
yEnd = Math.round(yEnd * 100) / 100;
$("#brush-region").text(("(" + xStart + ", " + yStart + ") to (" + xEnd + ", " + yEnd + ")"));
}
}
function drawRandomChart() {
var options = {
'renderTo': "#main-chart",
'data': [{'x': 4, 'y': 5}, {'x': 3, 'y': 5}, {'x': 4, 'y': 2}, {'x': 4, 'y': 7}],
'x-label': "x-axis",
'y-label': "y-axis",
'brush': true,
'title': "My Epic Chart"
};
drawScatter(options);
}
function drawUserChart(xlab, ylab, title, brush, minX, maxX, minY, maxY, height, width, numberOfPoints)
{
var points = [];
var i = 0;
//console.log("number of points" + numberOfPoints);
while (i < numberOfPoints) {
var x = Math.floor(Math.random() * (maxX - minX)) + minX;
var y = Math.floor(Math.random() * (maxY - minY)) + minY;
var obj = {'x': x, 'y': y};
//console.log(obj);
points.push(obj);
i++;
}
//console.log("points are:" + points);
var options = {
'renderTo': "#main-chart",
'data': points,
'x-label': xlab,
'y-label': ylab,
'title': title,
'brush': brush
};
//console.log(options);
$("#main-chart").html("");
drawScatter(options);
}
</code></pre>
</p>
</div>
<div class="col-lg-2"></div>
</div>
<script>
drawRandomChart();
</script>
</body>
</html>