-
Notifications
You must be signed in to change notification settings - Fork 1
/
Copy pathawesome-area-chart.html
599 lines (506 loc) · 23.4 KB
/
awesome-area-chart.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
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
<!--
MIT License
Copyright (c) 2017 Vinod Louis
Permission is hereby granted, free of charge, to any person obtaining a copy
of this software and associated documentation files (the "Software"), to deal
in the Software without restriction, including without limitation the rights
to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
copies of the Software, and to permit persons to whom the Software is
furnished to do so, subject to the following conditions:
The above copyright notice and this permission notice shall be included in all
copies or substantial portions of the Software.
VERSION 1.0.0
-->
<link rel="import" href="../polymer/polymer-element.html">
<script src="../d3/d3.js"></script>
<dom-module id="awesome-area-chart">
<template>
<style>
:host {
display: block;
}
.grid line {
stroke: var(--grid-stroke-color,#ddd);
stroke-width: var(--grid-stroke-width,1px);
}
.cursor-pointer{
cursor: pointer;
}
.line{
opacity:var(--chart-opacity,0.5);
}
</style>
<div id="groundAreaChart"></div>
</template>
<script>
/**
* `awesome-area-chart`
*
*
* @AwesomeAreaChart
* @polymer
* @demo demo/awesome-area-chart.html
------------
Properties
------------
#1: Data is the array of object with minimal 2 key value pair which can act as label and key(s) for area chart
*REQUIRED
data : {
type: Array,
//label here (date) should be an Js date object or a date string which can be type casted to a valid date
value:[{"credit":25000,"debit":10000,"date":"2016-12-31T18:30:00.000Z"},{"credit":43000,"debit":20000,"date":"2017-01-31T18:30:00.000Z"},{"credit":80000,"debit":10000,"date":"2017-02-28T18:30:00.000Z"},{"credit":65000,"debit":35000,"date":"2017-03-31T18:30:00.000Z"},{"credit":25000,"debit":40000,"date":"2017-04-30T18:30:00.000Z"},{"credit":90000,"debit":5000,"date":"2017-05-31T18:30:00.000Z"},{"credit":63000,"debit":7000,"date":"2017-06-30T18:30:00.000Z"},{"credit":41000,"debit":13500,"date":"2017-07-31T18:30:00.000Z"},{"credit":120000,"debit":47500,"date":"2017-08-31T18:30:00.000Z"},{"credit":70000,"debit":1000,"date":"2017-09-30T18:30:00.000Z"},{"credit":77000,"debit":42500,"date":"2017-10-31T18:30:00.000Z"},{"credit":145000,"debit":180000,"date":"2017-11-30T18:30:00.000Z"}];
}
#2 chart-config an composite object of properties not all are required provides additional customization to chart
chartConfig:{
type:Object,
value:{
//default size of the chart if containe has no width
chartSize:300,
*REQUIRED
//The date object or date string property name which can be used to plot graph
label:"",
*REQUIRED
//The values or properties to which graph shall be plot can be a string in case of single area chart or array in case of multi area chart
keys:"",
//Array of colors to be used in chart, lenght should be greater than equal to key(s)
color:[],
//Object of properties left,right,top,bottom : To set margins useful in case of handling long labels
margin:{left:35, right:80, top: 30, bottom: 50}
//Shows tooltip on top
aggregatedTooltip:true,
//It accepts values in similar fashion as keys legends are given preference over keys in labelling
legends:"",
//Draws a circle at every end point on line when set to true
drawCircle:false,
//The x axis format identifier must be an valid d3.js time parse specifier(https://github.com/d3/d3-time-format)
timeFormat:"%d-%b-%y",
//The y axis format identifier must be an valid d3.js number oarse specifier(https://github.com/d3/d3-format)
valueFormat:".2s",
//The rotation value in degree for x axis alignment
xlabelRotate:45,
//draw background gridlines if set to true
gridLines:true
}
}
---------------
Methods
---------------
#1 : circleClick : Function called when the circle is clicked passing parms include : (param1:data for the clicked circle,param3:property under context click, param3: the circle svg object clicked)
---------------
Events
---------------
#1 : tooltip
Hook for displaying tooltip
Return type : String
params passed include : (param1:data for the context point,param2: property name under context)
----------------
Mixins
----------------
--grid-stroke-color : Set grid line color
--grid-stroke-width : Set width of the grid lines
--chart-opacity : Set opacity for area
*/
class AwesomeAreaChart extends Polymer.Element {
static get is() { return 'awesome-area-chart'; }
static get properties() {
return {
chartConfig:{
type: Object
},
__defaultConfig:{
type: Object,
value:{
chartSize:300,
label:"",
margin:{left:35, right:80, top: 30, bottom: 50},
aggregatedTooltip:true,
keys:"",
legends:[],
color:[],
drawCircle:true,
timeFormat:"%d-%b-%y",
valueFormat:".2s",
xlabelRotate:45,
gridLines:true
}
},
data:{
type: Array,
observer:'_dataChanged'
}
};
}
ready(){
super.ready();
}
_dataChanged(val){
if(val){
//The Mandatory check
if(!this.chartConfig.label || typeof this.chartConfig.label !== "string"){
throw new Error("'label' property under chartConfig should be an appropriate string value");
return;
}
if(!this.chartConfig.keys || (typeof this.chartConfig.keys !== "string" && !Array.isArray(this.chartConfig.keys))){
throw new Error("'keys' property under chartConfig should be an appropriate string/array value");
return;
}
//Convert keys to array
this.chartConfig.keys = (!Array.isArray(this.chartConfig.keys)) ? [this.chartConfig.keys] : this.chartConfig.keys;
//Safe check for color
if(this.chartConfig.color){
if(!Array.isArray(this.chartConfig.color)){
(console ? (console.warn || console.log) : function (m) { return m; })("color should be a valid array");
this.chartConfig.color = this.__defaultConfig.color;
}else if(this.chartConfig.color.length < this.chartConfig.keys.length){
(console ? (console.warn || console.log) : function (m) { return m; })("color length should be equal to keys length");
this.chartConfig.color = this.__defaultConfig.color;
}
}
//Safe check for legends
if(this.chartConfig.legends){
if(typeof this.chartConfig.legends !== "string" && !Array.isArray(this.chartConfig.legends)){
(console ? (console.warn || console.log) : function (m) { return m; })("legends should be valid string/array");
this.chartConfig.legends = this.__defaultConfig.legends;
}else if(typeof this.chartConfig.legends === "string" && this.chartConfig.keys.length !== 1){
(console ? (console.warn || console.log) : function (m) { return m; })("legends length should be equal to key length");
this.chartConfig.legends = this.__defaultConfig.legends;
}else if(Array.isArray(this.chartConfig.legends) && this.chartConfig.legends.length < this.chartConfig.keys.length){
(console ? (console.warn || console.log) : function (m) { return m; })("legends length should be equal to key length");
this.chartConfig.legends = this.__defaultConfig.legends;
}
}
//Safe check for margin
if(this.chartConfig.margin){
if(typeof this.chartConfig.margin !== "object"){
(console ? (console.warn || console.log) : function (m) { return m; })("margin should be of type object");
this.chartConfig.margin = this.__defaultConfig.margin;
}else{
var arrM = ["top","bottom","right","left"];
arrM.forEach((d)=>{
if(this.chartConfig.margin.hasOwnProperty(d) && typeof this.chartConfig.margin[d] !== "number"){
(console ? (console.warn || console.log) : function (m) { return m; })(d + " in margin is not a valid number");
this.chartConfig.margin[d] = this.__defaultConfig.margin[d];
}
});
}
}
if(typeof this.chartConfig.aggregatedTooltip !== "boolean" && typeof this.chartConfig.aggregatedTooltip !== "undefined"){
(console ? (console.warn || console.log) : function (m) { return m; })("aggregatedTooltip should be a boolean value");
this.chartConfig.aggregatedTooltip = this.__defaultConfig.aggregatedTooltip;
}
if(typeof this.chartConfig.drawCircle !== "boolean" && typeof this.chartConfig.drawCircle !== "undefined"){
(console ? (console.warn || console.log) : function (m) { return m; })("drawCircle should be a boolean value");
this.chartConfig.drawCircle = this.__defaultConfig.drawCircle;
}
if(typeof this.chartConfig.gridLines !== "boolean" && typeof this.chartConfig.gridLines !== "undefined"){
(console ? (console.warn || console.log) : function (m) { return m; })("gridLines should be a boolean value");
this.chartConfig.gridLines = this.__defaultConfig.gridLines;
}
//Safe check for xlabelRotate
if(this.chartConfig.xlabelRotate && typeof this.chartConfig.xlabelRotate !== "number"){
(console ? (console.warn || console.log) : function (m) { return m; })("xlabelRotate is not a valid number");
this.chartConfig.xlabelRotate = this.__defaultConfig.xlabelRotate;
}
this.paintDelayedChart();
}
}
paintDelayedChart(){
var self = this;
setTimeout(()=>self.drawAreaChartViz(),0)
}
drawAreaChartViz(){
this.chartConfig.margin = Object.assign(JSON.parse(JSON.stringify(this.__defaultConfig.margin)),this.chartConfig.margin);
this.chartConfig = Object.assign(JSON.parse(JSON.stringify(this.__defaultConfig)),this.chartConfig);
if(this.chartConfig.legends && typeof this.chartConfig.legends === "string")
this.chartConfig.legends = [this.chartConfig.legends];
d3.selection.prototype.moveToFront = function() {
return this.each(function(){
this.parentNode.appendChild(this);
});
};
//Set Dimensions
var self = this;
var currHover = null;
var ow = (this.offsetWidth == 0) ? this.chartConfig.chartSize : this.offsetWidth;
var width = Math.floor(ow);
var height = Math.floor(ow*0.70);
var maxValue = 0;
//safely parse label as date
this.data.forEach((el)=>{
maxValue = Math.max(maxValue,this.chartConfig.keys.reduce(function(m, k){ return el[k] > m ? el[k] : m }, -Infinity));
if (!(el[this.chartConfig.label] instanceof Date))
el[this.chartConfig.label] = new Date(el[this.chartConfig.label]);
});
//Remove the old scraps
d3.select(this.$.groundAreaChart).html("");
//Prepare playground
var svg = d3.select(this.$.groundAreaChart).append("svg")
.attr("width", width)
.attr("height", height)
.attr("id","ground")
//In case of no data handle
if(this.data.length == 0){
svg.append("text").attr("x",width/2).attr("y",height/2).attr("text-anchor","middle").text("No Data Available to display");
return;
}
// Add the clip path.
svg.append("clipPath")
.attr("id", "clip")
.append("rect")
.attr("width", width)
.attr("height", height);
//Set Margins
var margin = this.chartConfig.margin;
var width = svg.attr("width") - margin.left - margin.right;
var height = svg.attr("height") - margin.bottom - margin.top;
//Prepare scales
var x = d3.scaleTime()
.rangeRound([0, width]);
var y = d3.scaleLinear()
.rangeRound([height, 0]);
//return continuous value
var parseTime = function(d){
return Date.parse(d)
}
//Set Domain for axis
x.domain(d3.extent(this.data,(d) => parseTime(d[this.chartConfig.label])));
y.domain([0, maxValue]);
//X axis Tick
var x_axis = d3.axisBottom(x).tickFormat((d)=>d3.timeFormat(this.chartConfig.timeFormat)(d));
//Y Axis Tick
var y_axis = d3.axisLeft(y)
if(this.chartConfig.gridLines)
y_axis = y_axis.tickSize(-width);
y_axis.tickFormat((d)=>d3.format(this.chartConfig.valueFormat)(d));
var multiline = (category)=>{
var line = d3.line()
.x((d) => x(parseTime(d[this.chartConfig.label])))
.y((d) => y(d[category]));
return line;
}
var multiarea = (category)=>{
var area = d3.area()
.x((d) => x(parseTime(d.date)))
.y0(height)
.y1((d)=> y(d[category]));
return area;
}
var gradient = (gradientColor)=>{
if(typeof gradientColor === "string"){
return [{offset: "0%", color: "#ffffff"},{offset: "100%", color: gradientColor}];
}
var arrGradient = []
for(var prop in gradientColor){
arrGradient.push({offset:prop,color:gradientColor[prop]});
}
return arrGradient;
}
//Define Color
var color = (this.chartConfig.color && this.chartConfig.color.length > 0) ? this.chartConfig.color : d3.schemeCategory10;
var gradientColor = (this.chartConfig.color && this.chartConfig.color.length > 0) ? this.chartConfig.color : d3.schemeCategory10;
//Bring chart to playground
var g = svg.append("g")
.attr("transform","translate(" + margin.left + "," + margin.top + ")");
// Add the X Axis
g.append("g")
.attr("transform", "translate(0," + height + ")")
.call(x_axis)
.selectAll("text")
.attr("y", 0)
.attr("x", 5)
.attr("dy", ".95em")
.attr("transform", "rotate(" + this.chartConfig.xlabelRotate +")")
.style("text-anchor", "start");
// Add the Y Axis
g.append("g")
.attr("class", "grid")
.call(y_axis)
//Make the gradient for all keys
this.chartConfig.keys.forEach((el,ind)=>{
svg.append("linearGradient")
.attr("id", "AreaFillgradient_"+ el)
.attr("gradientUnits", "userSpaceOnUse")
.attr("x1", 0).attr("y1", y(0))
.attr("x2", 0).attr("y2", y(maxValue))
.selectAll("stop")
.data(gradient(gradientColor[ind]))
.enter().append("stop")
.attr("offset",(d)=> d.offset)
.attr("stop-color",(d)=> d.color);
var lineFunction = multiline(el);
var areaFunction = multiarea(el);
g.append("path")
.datum(this.data)
.attr("class", "line")
.attr("stroke",(d,i)=> color[ind])
.attr("fill","none")
.attr("d", lineFunction)
g.append("path")
.datum(this.data)
.attr("class", "line")
.attr("stroke", ()=> color[ind])
.attr("fill","url(#AreaFillgradient_" + el + ")")
.attr("d", areaFunction)
g.append("text")
.datum((d) => { return {name: (this.chartConfig.legends.length > 0) ? this.chartConfig.legends[ind] : el[0].toUpperCase() + el.substr(1).toLowerCase(0) , value: this.data[this.data.length-1]}})
.attr("transform",(d) => { return "translate(" + x(parseTime(d.value[this.chartConfig.label])) + "," + y(d.value[el]) + ")"; })
.attr("x", 7)
.attr("dy", ".35em")
.text((d)=> d.name)
.attr("stroke-width",0.5)
.attr("stroke",()=>color[ind])
if(this.chartConfig.drawCircle || (this.circleClick && typeof this.circleClick === "function")){
g.selectAll(".circle."+el)
.data(this.data)
.enter()
.append("circle")
.attr("cx",(d)=> x(parseTime(d.date)))
.attr("cy",(d)=> y(d[el]))
.attr("r",5)
.attr("class",(d)=>{return (self.circleClick && typeof self.circleClick === "function") ? "circle cursor-pointer "+ el : "circle " + el})
.attr("stroke",(d,i)=>color[ind])
.attr("fill",(d,i)=>color[ind])
.on("click",function(d){
if(self.circleClick && typeof self.circleClick === "function")
self.circleClick(d,el,this)
})
.on('mouseenter',function(d,i){
currHover = g.append("circle").attr("cx",this.getAttribute("cx"))
.attr("cy",this.getAttribute("cy"))
.attr("r",10)
.attr("fill","none")
.attr("stroke",this.getAttribute("stroke"))
//console.log(this);
}).on("mouseleave",function(d,i){
currHover.remove();
})
.append("svg:title")
.text((d, i)=>{
if(this.tooltip && typeof this.tooltip === "function")
return this.tooltip(d,el);
return el + " : " + d[el];
});
}
});
if(this.chartConfig.drawCircle || (this.circleClick && typeof this.circleClick === "function")){
this.chartConfig.keys.forEach((el,ind)=>{
g.selectAll(".circle."+el)
//.transition().duration(300).delay((d,i)=> (i*300))
//.attr('r', 5)
.each(function(){
if(!self.chartConfig.aggregatedTooltip || self.chartConfig.keys.length > 1)
d3.select(this).moveToFront();
});
});
}
//g.selectAll()
//TODO Animation
/*
// Add 'curtain' rectangle to hide entire graph
var curtain = svg.append('rect')
.attr('x', -1 * (width + margin.left + 10))
.attr('y', -1 * (height + margin.top))
.attr('height', (height + margin.top))
.attr('width', width)
.attr('class', 'curtain')
.attr('transform', 'rotate(180)')
.style('fill', '#ffffff');
// Create a shared transition for anything we're animating
var t = svg.transition()
.delay(750)
.duration(2000)
.ease(d3.easeLinear)
.on('end', function() {
d3.select('line.guide')
.transition()
.style('opacity', 0)
.remove()
//svg.append("text")
//.attr("x", (width / 2))
//.attr("y", (margin.top - margin.top/2))
//.attr("text-anchor", "middle")
//.style("font-size", "12px")
//.text("Click on points to drill down and anywhere on chart to reset");
});
t.select('rect.curtain')
.attr('width', 0);
t.select('line.guide')
.attr('transform', 'translate(' + width + ', 0)')
*/
if(!this.chartConfig.aggregatedTooltip || this.chartConfig.keys.length > 1)
return;
//ToolTip formation
var bisectDate = d3.bisector((d) => d.date).left;
var rectHov = svg.append("svg:rect")
.attr("transform",
"translate(" + margin.left + "," + margin.top + ")")
.attr("height",height)
.attr("width",width+margin.right)
.attr("fill","none")
.attr('pointer-events', 'all')
.on("mouseout", hoverMouseOff)
.on("mousemove", hoverMouseOn);
var hoverLineGroup = svg.append("g")
.attr("transform",
"translate(" + margin.left + "," + margin.top + ")")
.attr("class", "hover-line");
var hoverLine = hoverLineGroup
.append("line")
.attr("stroke", "#666666")
.attr("x1", margin.bottom).attr("x2", 10)
.attr("y1", 0).attr("y2", height)
.style("stroke-dasharray", ("3, 3"));
/*var hoverrect = hoverLineGroup.append("rect")
.attr("width","70px")
.attr("height","25px")
.attr("fill","#e5e5e5")*/
var hoverTT = hoverLineGroup.append('text')
.attr("dy", ".35em")
.attr("text-anchor","middle")
.attr("class", "hover-tex capo")
.style("font-size", "12px")
//.attr('y', height-20);
/*var cle = hoverLineGroup.append("circle")
.attr("r", 4.5);*/
/*var hoverTT2 = hoverLineGroup.append('text')
.attr("class", "hover-text capo")*/
hoverLineGroup.style("opacity", 1e-6);
/*var rectHover = svg.append("rect")
.data(data)
.attr("fill", "none")
.attr("class", "overlay")
.attr("width", width)
.attr("height", height);*/
function hoverMouseOn() {
var mouse_x = d3.mouse(this)[0];
var mouse_y = d3.mouse(this)[1];
var graph_y = y.invert(mouse_y);
var graph_x = x.invert(mouse_x);
var mouseDate = x.invert(mouse_x);
var i = bisectDate(self.data, mouseDate); // returns the index to the current data item
//console.log(i,graph_y,graph_x,mouseDate)
//var d0 = data[i - 1]
//var d1 = data[i];
// work out which date value is closest to the mouse
//var d = mouseDate - d0[0] > d1[0] - mouseDate ? d1 : d0;
i = (i==0) ? 1 : i;
hoverTT.text(
(self.tooltip && typeof self.tooltip === "function") ? self.tooltip(self.data[i-1],self.chartConfig.keys[0]) : d3.timeFormat(self.chartConfig.timeFormat)(self.data[i-1][self.chartConfig.label]) + " ," + d3.format(self.chartConfig.valueFormat)(self.data[i-1][self.chartConfig.keys[0]])
);
//hoverrect.attr('x', x(self.data[i-1][self.chartConfig.label])-50);
//hoverrect.attr('y', -25);
hoverTT.attr('x', x(self.data[i-1][self.chartConfig.label])-15);
hoverTT.attr('y', -12.5);
/*cle.attr('x', mouse_x)
.attr('y', mouse_y);*/
hoverLine.attr("x1",x(self.data[i-1][self.chartConfig.label])).attr("x2", x(self.data[i-1][self.chartConfig.label]))
hoverLineGroup.style("opacity", 1);
}
function hoverMouseOff() {
hoverLineGroup.style("opacity", 1e-6);
}
}
}
window.customElements.define(AwesomeAreaChart.is, AwesomeAreaChart);
</script>
</dom-module>