-
Notifications
You must be signed in to change notification settings - Fork 0
/
zatanna.js
489 lines (437 loc) · 16.8 KB
/
zatanna.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
/**
* Zatanna, a Javascript library, v1.0
* @requires d3 v3.4.11 or later
* @requires jQuery v2.1.1 or later
*
* Zatanna is a Javascript library that makes it easy to build graphs with
* D3. It also simplifies using d3Pie.
*
* For usage and examples, visit:
* https://github.com/zipongo/zatanna/
*
* Licensed under the MIT license:
* http://www.opensource.org/licenses/mit-license.php
*
* Copyright (c) 2014, Greg Schwartz at Zipongo, Inc.
*/
/**
* Build a line chart using D3.
* @param {string} targetSelector The selector (#id or .class or combination) to put the SVG element in.
* @param {array} data The data array. See notes for accepted forms to the data.
* @param {string} yAxisLabel Label for the yAxis. Can also be set to "".
* @param {hash} options Hash of options. See notes for accepted options.
* Example: d3LineChart("#enrolled", dataPeriod.enrollmentMonthly, "Users", {xAxisIsDates: true, yTicks: 7});
* Based upon Michael Bostock's line chart code, http://bl.ocks.org/mbostock/3883245
*/
function d3LineChart(targetSelector, data, yAxisLabel, options) {
options = options || {};
yAxisLabel = yAxisLabel || "";
var margin = {top: options.margin_top || 25, right: options.margin_right || 20, bottom: options.margin_bottom || 30, left: options.margin_left || 60};
var width = (options.width || 950) - margin.left - margin.right;
var height = (options.height || 400) - margin.top - margin.bottom;
var yTicks = options.yTicks || 10;
var xGrid = (options.xGrid !== null ? options.xGrid : true);
var yGrid = (options.yGrid !== null ? options.yGrid : true);
var labelDataPoints = (options.labelDataPoints !== null ? options.labelDataPoints : true);
//later this can be allowed to be off, and the function will be able to build scatter plots. But for now, we're only supporting dates.
options.xAxisIsDates = true;
var parseDate = d3.time.format("%Y-%m-%d").parse;
data.forEach(function(d) {
if(options.xAxisIsDates) d.date = parseDate(d.date);
else d.x = +d.x;
d.count = +d.count;
});
var x = d3.time.scale()
.range([0, width]);
var y = d3.scale.linear()
.range([height, 0]);
var xAxis = d3.svg.axis()
.scale(x)
.orient("bottom");
if(options.xAxisTicks && options.xAxisTicks.interval && options.xAxisTicks.amount)
xAxis = xAxis.ticks(options.xAxisTicks.interval, options.xAxisTicks.amount);
var yAxis = d3.svg.axis()
.scale(y)
.orient("left")
.ticks(yTicks);
var line = d3.svg.line()
.x(function(d) { return x(options.xAxisIsDates ? d.date : d.x); })
.y(function(d) { return y(d.count); });
var svg = d3.select(targetSelector).append("svg")
.attr("class", "lineChart")
.attr("width", width + margin.left + margin.right)
.attr("height", height + margin.top + margin.bottom)
.append("g")
.attr("transform", "translate(" + margin.left + "," + margin.top + ")");
x.domain(d3.extent(data, function(d) { return (options.xAxisIsDates ? d.date : d.x); }));
y.domain(d3.extent(data, function(d) { return d.count; }));
svg.append("g")
.attr("class", "x axis")
.attr("transform", "translate(0," + height + ")")
.call(xAxis);
svg.append("g")
.attr("class", "y axis")
.call(yAxis)
.append("text")
.attr("transform", "rotate(-90)")
.attr("y", 6)
.attr("dy", ".71em")
.style("text-anchor", "end")
.text(yAxisLabel);
if(xGrid || yGrid) {
var rules = svg.selectAll("g.rule")
.data(x.ticks(10))
.enter().append("svg:g")
.attr("class", "rule");
}
if(xGrid) {
// Draw grid lines
rules.append("svg:line")
.attr("class", function(d) { return d ? null : "axis"; })
.data(options.xAxisTicks && options.xAxisTicks.interval && options.xAxisTicks.amount ? x.ticks(options.xAxisTicks.interval, options.xAxisTicks.amount) : x.ticks())
.attr("x1", x)
.attr("x2", x)
.attr("y1", 0)
.attr("y2", height - 1);
}
if(yGrid) {
rules.append("svg:line")
.attr("class", function(d) { return d ? null : "axis"; })
.data(y.ticks(yTicks))
.attr("y1", y)
.attr("y2", y)
.attr("x1", 0)
.attr("x2", width - 10);
}
svg.append("path")
.datum(data)
.attr("class", "line")
.attr("d", line);
if(labelDataPoints) {
//show a dot at each datapoint
svg.selectAll(".dataLabel")
.data(data)
.enter().append("text")
.attr("class", "dataLabel")
.text(function(d,i) { return (i>0 ? d.count : ""); })
.attr("text-anchor", "middle")
.attr("x", function(d) { return x(options.xAxisIsDates ? d.date : d.x); })
.attr("y", function(d) { return y(d.count) - 9; });
//show a dot at each datapoint
svg.selectAll(".dot")
.data(data)
.enter().append("circle")
.attr("class", "dot")
.attr("r", 3.5)
.attr("cx", function(d) { return x(options.xAxisIsDates ? d.date : d.x); })
.attr("cy", function(d) { return y(d.count); });
}
}
/**
* Build a pie chart using D3pie.
* @param {string} targetSelector The selector (#id or .class or combination) to put the SVG element in.
* @param {array} data The data array. See notes for accepted forms to the data.
* @param {hash} options Hash of options. See notes for accepted options.
* Example: d3PieChart("#ages", dataPeriod.users.ages, {title: "Age", width: 480, height: 300});
* Data is expected in one of these three formats:
* {family: 213, roommates: 32, kids: 178, alone: 57 }
* {'18-29': 173, '30-49': 231, '50-64': 81, '65+': 0}
* {green: 10, yellow: 26, red: 33} (And then you probably want to include {"stoplight": "true"} in the options.)
*/
function d3PieChart(targetSelector, data, options) {
options = options || {};
var stoplightColors = {green: "#6ABC22", yellow: "#FAD130", red: "#F7181B"};
var colorSet = null;
if(options.colors)
colorSet = options.colors;
else
colorSet = ["#98abc5", "#8a89a6", "#7b6888", "#6b486b", "#a05d56", "#d0743c", "#ff8c00"];
var convertedData = Array(), colorCounter = 0;
for(var i in data) {
var item = {
"label": i,
"value": +data[i],
"color": colorSet[colorCounter++]
};
//don't show a label
if(options.stoplight && stoplightColors[i]) {
item["color"] = stoplightColors[i];
item["label"] = data[i];
}
convertedData.push(item);
if(colorCounter > colorSet.length-1) colorCounter=0;
}
var settings = {
"header": {
"titleSubtitlePadding": 9,
"location": "pie-center"
},
"size": {
"canvasHeight": options.height || 320,
"canvasWidth": options.width || 320,
"pieInnerRadius": "70%",
"pieOuterRadius": "85%"
},
"data": {
"sortOrder": "value-desc",
"content": convertedData
},
"labels": {
"outer": {
"pieDistance": 16
},
"inner": {
"hideWhenLessThanPercentage": 3
},
"mainLabel": {
"fontSize": 16
},
"percentage": {
"color": "#ffffff",
"fontSize": 12,
"decimalPlaces": 0
},
"value": {
"color": "#adadad",
"fontSize": 11
},
"lines": {
"enabled": true
}
},
"effects": {
"pullOutSegmentOnClick": {
"effect": "linear",
"speed": 400,
"size": 8
}
},
"misc": {
"gradient": {
"enabled": !options.stoplight,
"percentage": 100
}
}
};
if(options.title) {
settings["header"]["title"] = {
"text": options.title,
"fontSize": 24,
"font": "open sans"
};
}
if(options.subtitle) {
settings["header"]["subtitle"] = {
"text": options.subtitle,
"color": "#999999",
"fontSize": 14,
"font": "open sans"
};
}
if(options.footer) {
settings["footer"] = {
"text": options.footer,
"color": "#999999",
"fontSize": 10,
"font": "open sans",
"location": "bottom-left"
};
}
//merge in other options to allow tweaking ANYTHING in the d3Pie call!
jQuery.extend(true, settings, options);
var pie = new d3pie(targetSelector, settings);
return pie;
}
/**
* Build a bar chart using D3.
* @param {string} targetSelector The selector (#id or .class or combination) to put the SVG element in.
* @param {array} data The data array. See notes for accepted forms to the data.
* @param {hash} options Hash of options. See notes for accepted options.
* Based upon Michael Bostock's bar chart code, http://bl.ocks.org/mbostock/3885304
*/
function d3BarChart(targetSelector, data, options) {
options = options || {};
var margin = {top: options.margin_top || 20, right: options.margin_right || 20, bottom: options.margin_bottom || 30, left: options.margin_left || 40};
var width = (options.width || 950) - margin.left - margin.right;
var height = (options.height || 400) - margin.top - margin.bottom;
var yTicks = options.yTicks || 10;
var defaultBarColor = options.defaultBarColor || "steelblue";
var hasLeftSymbol = hasRightSymbol = false;
//optional symbols
var leftSymbol = {
"shape": "triangle",
"color": "gray",
"showLine": true,
"lineColor": "black",
"lineDashing": "8, 2",
"width": 8
};
var rightSymbol = {
"shape": "circle",
"color": "gray",
"showLine": true,
"lineColor": "black",
"lineDashing": "4, 2",
"width": leftSymbol.width //by default, same size
};
//convert the data to force it into the right format
var convertedData = [];
for(var i in data) {
var item = {
"label": i,
"value": +data[i].value || +data[i],
"color": data[i].color || defaultBarColor
};
//merge the symbol defaults with optional passed values
if(data[i].leftSymbol && (data[i].leftSymbol > 0 || data[i].leftSymbol.value > 0)) {
item["leftSymbol"] = { "value": +data[i].leftSymbol.value || +data[i].leftSymbol };
jQuery.extend(item["leftSymbol"], leftSymbol, options.leftSymbol);
hasLeftSymbol = true;
}
if(data[i].rightSymbol && (data[i].rightSymbol > 0 || data[i].rightSymbol.value > 0)) {
item["rightSymbol"] = { "value": +data[i].rightSymbol.value || +data[i].rightSymbol };
jQuery.extend(item["rightSymbol"], rightSymbol, options.rightSymbol);
hasRightSymbol = true;
}
convertedData.push(item);
}
var x = d3.scale.ordinal()
.rangeRoundBands([0, width], .1);
var y = d3.scale.linear()
.range([height, 0]);
var xAxis = d3.svg.axis()
.scale(x)
.orient("bottom");
var yAxis = d3.svg.axis()
.scale(y)
.orient("left")
.ticks(yTicks, yTicks);
var svg = d3.select(targetSelector).append("svg")
.attr("class", "barChart")
.attr("width", width + margin.left + margin.right)
.attr("height", height + margin.top + margin.bottom)
.append("g")
.attr("transform", "translate(" + margin.left + "," + margin.top + ")");
x.domain(convertedData.map(function(d) { return d.label; }));
y.domain([0, d3.max(convertedData, function(d) {
//find the max of the value, and both symbol's values, if set
var values = [d.value];
if(d.leftSymbol) values.push(d.leftSymbol.value);
if(d.rightSymbol) values.push(d.rightSymbol.value);
return d3.max(values);
})]);
svg.append("g")
.attr("class", "x axis")
.attr("transform", "translate(0," + height + ")")
.call(xAxis);
svg.append("g")
.attr("class", "y axis")
.call(yAxis)
.append("text")
.attr("transform", "rotate(-90)")
.attr("y", 6)
.attr("dy", ".71em")
.style("text-anchor", "end")
.text(options.yAxisTitle || "");
//bars
svg.selectAll(".bar")
.data(convertedData)
.enter().append("rect")
.attr("class", "bar")
.attr("x", function(d) { return x(d.label) + (d.leftSymbol ? d.leftSymbol.width -2 : 0); })
.attr("width", function(d) { return x.rangeBand() - (d.leftSymbol ? d.leftSymbol.width : 0) - (d.rightSymbol ? d.rightSymbol.width : 0); })
.attr("y", function(d) { return y(d.value); })
.attr("height", function(d) { return height - y(d.value); })
.style("fill", function(d) { return d.color; });
//left symbols
if(hasLeftSymbol) {
svg.selectAll(".symbol")
.data(convertedData)
.enter().append("path")
.attr("transform", function(d) {if(d.leftSymbol) return "translate(" + x(d.label) + "," + y(d.leftSymbol.value) + ")" + (d.leftSymbol.shape=="triangle" ? "rotate(90)" : ""); })
.attr("d", d3.svg.symbol()
.size(function(d) { if(d.leftSymbol) return Math.pow(d.leftSymbol.width,2); })
.type(function(d) { if(d.leftSymbol) { if(d.leftSymbol.shape=="triangle") return "triangle-up"; else return d.leftSymbol.shape; } })
)
.style("fill", function(d) { if(d.leftSymbol) return d.leftSymbol.color; });
//left symbol labels
svg.selectAll(".leftLabel")
.data(convertedData)
.enter().append("text")
.attr("class", "symbolLabel")
.attr("dy", ".71em")
.text(function(d) { if(d.leftSymbol) return d.leftSymbol.label; })
.attr("transform", function(d) {
if(d.leftSymbol) {
var my_x = x(d.label)-d.leftSymbol.width/2,
my_y = y(d.leftSymbol.value)+d.leftSymbol.width;
if(my_y + this.offsetWidth + 10 >= height) { my_y -= d.leftSymbol.width * 2; }
return "translate(" + my_x + "," + my_y + ") rotate(-90)";
}
})
.style("text-anchor", function(d) {
if(d.leftSymbol) {
var my_y = y(d.leftSymbol.value)+d.leftSymbol.width;
return (my_y + this.offsetWidth + 10 >= height ? "start" : "end");
}
});
//left symbol lines
svg.selectAll(".leftLines")
.data(convertedData)
.enter().append("line")
.style("stroke-dasharray", function(d) { return d.leftSymbol.lineDashing; })
.attr("stroke-width", function(d) { return (d.leftSymbol && d.leftSymbol.showLine ? 1 : 0); }) //if !showLine, line isn't visible
.attr("stroke", function(d) { if(d.leftSymbol) return d.leftSymbol.lineColor; })
.attr("x1", function(d) { if(d.leftSymbol) return x(d.label) + d.leftSymbol.width - 3; })
.attr("y1", function(d) { if(d.leftSymbol) return y(d.leftSymbol.value); })
.attr("x2", function(d) { if(d.leftSymbol) return x(d.label) - 2 + x.rangeBand() - (d.rightSymbol ? d.rightSymbol.width : 0) ; })
.attr("y2", function(d) { if(d.leftSymbol) return y(d.leftSymbol.value); });
}
if(hasRightSymbol) {
//right symbols
svg.selectAll(".symbol")
.data(convertedData)
.enter().append("path")
.attr("transform", function(d) {
if(d.rightSymbol)
return "translate(" + (x(d.label)+x.rangeBand()-d.rightSymbol.width+4) + "," + y(d.rightSymbol.value) + ")" + (d.rightSymbol.shape=="triangle" ? "rotate(-90)" : "");
})
.attr("d", d3.svg.symbol()
.size(function(d) { if(d.rightSymbol) return Math.pow(d.rightSymbol.width,2); })
.type(function(d) { if(d.rightSymbol) { if(d.rightSymbol.shape=="triangle") return "triangle-up"; else return d.rightSymbol.shape; } })
)
.style("fill", function(d) { if(d.rightSymbol) return d.rightSymbol.color; });
//right symbol labels
svg.selectAll(".rightLabel")
.data(convertedData)
.enter().append("text")
.attr("class", "symbolLabel")
.attr("dy", ".71em")
.text(function(d) { if(d.rightSymbol) return d.rightSymbol.label; })
.attr("transform", function(d) {
if(d.rightSymbol) {
var my_x = x(d.label)+x.rangeBand()-d.rightSymbol.width+1,
my_y = y(d.rightSymbol.value)+d.rightSymbol.width;
if(my_y + this.offsetWidth + 10 >= height) { my_y -= d.rightSymbol.width * 2; }
return "translate(" + my_x + "," + my_y + ") rotate(-90)";
}
})
.style("text-anchor", function(d) {
if(d.rightSymbol) {
var my_y = y(d.rightSymbol.value)+d.rightSymbol.width;
return (my_y + this.offsetWidth + 10 >= height ? "start" : "end");
}
});
//right symbol lines
svg.selectAll(".rightLines")
.data(convertedData)
.enter().append("line")
.style("stroke-dasharray", function(d) { return d.rightSymbol.lineDashing; })
.attr("stroke-width", function(d) { return (d.rightSymbol && d.rightSymbol.showLine ? 1 : 0); }) //if !showLine, line isn't visible
.attr("stroke", function(d) { if(d.rightSymbol) return d.rightSymbol.lineColor; })
.attr("x1", function(d) { if(d.rightSymbol) return x(d.label) + (d.leftSymbol ? d.leftSymbol.width + 1 : 0); })
.attr("y1", function(d) { if(d.rightSymbol) return y(d.rightSymbol.value); })
.attr("x2", function(d) { if(d.rightSymbol) return x(d.label) + x.rangeBand() - (d.rightSymbol ? d.rightSymbol.width : 0); })
.attr("y2", function(d) { if(d.rightSymbol) return y(d.rightSymbol.value); });
}
}