# Line Chart
The code is under file `awesome-line-chart-demo.html`. The chart is draw for a set of dummy transaction withdrawal and deposit on a particular date
- X-axis represents the date
- Y-axis shows the credit/debit amount
<link rel="import" href="https://polygit.org/polymer+polymer+v2.0.0-rc.3/webcomponentsjs+webcomponents+v1.0.0-rc.6/components/polymer/polymer-element.html">
<link rel="import" href="awesome-charts/awesome-line-chart.html">
<dom-module id="awesome-line-chart-demo">
<template>
<style>
:host {
display: block;
}
.container {
margin: 10px;
background-color: #fafafa;
padding: 10px;
border: 1px solid #e5e5e5;
}
pre {
font-family: Consolas, Menlo, Monaco, Lucida Console, Liberation Mono, DejaVu Sans Mono, Bitstream Vera Sans Mono, Courier New, monospace, serif;
margin-bottom: 10px;
overflow: auto;
width: auto;
padding: 5px;
background-color: #eee;
width: 650px!ie7;
padding-bottom: 20px!ie7;
max-height: 600px;
}
</style>
<div class="container">
<h2>Basic Line chart</h2>
<blockquote>
<pre>
<code>
#1 : Charts binded with data and basic minimal configuration
</code>
</pre>
</blockquote>
<div class="chart1">
<awesome-line-chart data={{data1}} chart-config={{config1}}></awesome-line-chart>
</div>
</div>
<div class="container">
<h2>Multi Line chart with events</h2>
<blockquote>
<pre>
<code>
#1 : Charts binded with data and few configuration factors
#2 : The hover tooltip here is not default its resolved via a hook 'tooltip'
#3 : Click events are binded, click any circle to see in action
</code>
</pre>
</blockquote>
<div class="chart2">
<awesome-line-chart data={{data2}} chart-config={{config2}} tooltip={{fntooltip}} circle-click={{fnCircleClick}}></awesome-line-chart>
</div>
</div>
</template>
<script>
// Define the class for a new element called custom-element
class AwesomeLineChartDemo extends Polymer.Element {
static get is() {
return "awesome-line-chart-demo";
}
static get properties() {
return {
data1:{
type:Array,
value:[],
notify:true
},
data2:{
type:Array,
value:[],
notify:true
},
config1:{
type:Object,
value:{
keys:"credit",
label:"date",
gridLines:false
}
},
config2:{
type:Object,
value:{
keys:["credit","debit"],
label:"date",
legends:["Deposit","Withdraw"],
color:["#89e200","#ff812f"],
timeFormat:"%d-%b",
valueFormat:"",
xlabelRotate:90,
margin:{left:50}
}
}
}
}
ready() {
super.ready();
this.data1 = [{"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"}];
this.data2 = [{"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"}];
}
fntooltip(d,prop){
return prop + " : " + d[prop].toLocaleString('en');
}
fnCircleClick(d,k,el){
alert(k + " clicked")
console.log(d,k,el);
}
}
// Register the new element with the browser
customElements.define(AwesomeLineChartDemo.is, AwesomeLineChartDemo);
</script>
</dom-module>
<!DOCTYPE html>
<html lang="en">
<head>
<script src="https://polygit.org/webcomponentsjs+1.0.0-rc.5/components/webcomponentsjs/webcomponents-loader.js"></script>
<link rel="import" href="awesome-line-chart-demo.html">
</head>
<body>
<awesome-line-chart-demo></awesome-line-chart-demo>
</body>
</html>
<!--
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.
-->
<link rel="import" href="https://polygit.org/polymer+polymer+v2.0.0-rc.3/webcomponentsjs+webcomponents+v1.0.0-rc.6/components/polymer/polymer-element.html">
<script src="https://d3js.org/d3.v4.min.js"></script>
<dom-module id="awesome-line-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="groundLineChart"></div>
</template>
<script>
/**
* `awesome-line-chart`
*
*
* @AwesomeLineChart
* @polymer
* @demo demo/awesome-line-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 container 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}
//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:true,
//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 AwesomeLineChart extends Polymer.Element {
static get is() { return 'awesome-line-chart'; }
static get properties() {
return {
chartConfig:{
type: Object
},
__defaultConfig:{
type: Object,
value:{
chartSize:300,
label:"",
keys:"",
legends:[],
color:[],
drawCircle:true,
timeFormat:"%d-%b-%y",
valueFormat:".2s",
xlabelRotate:45,
gridLines:true,
margin:{left:35, right:80, top: 30, bottom: 50}
}
},
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.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.drawLineChartViz(),0)
}
drawLineChartViz(){
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.$.groundLineChart).html("");
//Prepare playground
var svg = d3.select(this.$.groundLineChart).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;
}
//Define Color
var color = (this.chartConfig.color && this.chartConfig.color.length > 0) ? this.chartConfig.color : d3.schemeCategory20;
//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)=>{
var lineFunction = multiline(el);
g.append("path")
.datum(this.data)
.attr("class", "line")
.attr("stroke",(d,i)=> color[ind])
.attr("fill","none")
.attr("d", lineFunction)
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.drawCircle || 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)')
*/
}
}
window.customElements.define(AwesomeLineChart.is, AwesomeLineChart);
</script>
</dom-module>