linechart.js
by Sajeetharan Sinnathurai
HTML
<script src="https://d3js.org/d3.v4.min.js"></script>
CSS
body {
font: 10px sans-serif;
}
.axis path,
.axis line {
fill: none;
stroke: #000;
shape-rendering: crispEdges;
}
/*.x.axis path {
display: none;
}*/
.line {
fill: none;
stroke: steelblue;
stroke-width: 1.5px;
}
JavaScript
var data =
'{"recordsFiltered":5,"raCounts":[{"name":"comp_name","values":[{"date_":"2016","actual":170.0,"DT_RowId":"row_null"},{"date_":"2015","actual":198.0,"DT_RowId":"row_null"},{"date_":"2015","actual":149.0,"DT_RowId":"row_null"},{"date_":"2014","actual":197.0,"DT_RowId":"row_null"},{"date_":"2014","actual":146.0,"DT_RowId":"row_null"}],"DT_RowId":"row_null"}],"draw":null,"recordsTotal":5}';
data = JSON.parse(data).raCounts[0].values;
//linechart.js
data.forEach(function(d) {
debugger;
d.Date = new Date(d.date_);
d.actual = +d.actual;
console.log(d.Date);
return d;
});
var margin = {
top: 30,
right: 40,
bottom: 30,
left: 50
},
width = 600 - margin.left - margin.right,
height = 270 - margin.top - margin.bottom;
var x = d3.scaleTime()
.range([0, width]);
var y0 = d3.scaleLinear()
.range([height, 0]);
// Scale the range of the data
x.domain(d3.extent(data, function(d) {
return d.Date;
}));
y0.domain([
d3.min(data, function(d) {
return Math.min(d.actual);
}),
d3.max(data, function(d) {
return Math.max(d.actual);
})
]);
var valueline1 = d3.line()
.x(function(d) {
console.log(x(d.actual));
return x(d.Date);
})
.y(function(d) {
return y0(d.actual);
});
var svg = d3.select("body")
.append("svg")
.attr("width", width + margin.left + margin.right)
.attr("height", height + margin.top + margin.bottom)
.append("g")
.attr("transform",
"translate(" + margin.left + "," + margin.top + ")");
svg.append("g") // Add the X Axis
.attr("class", "x axis")
.attr("transform", "translate(0," + height + ")")
.call(d3.axisBottom(x));
// text label for the x axis
svg.append("text")
.attr("transform",
"translate(" + (width / 2) + " ," +
(height + margin.top + 20) + ")")
.style("text-anchor", "middle")
.text("Date");
svg.append("g")
.attr("class", "y axis")
.style("fill", "steelblue")
.call(d3.axisLeft(y0));
svg.append("path")
.data([data])
...