Line Chart with Customization - CanvasJS JavaScript Charts
Line Chart with Customization - CanvasJS JavaScript Charts
by canvasjs
HTML
<script src="https://canvasjs.com/assets/script/canvasjs.min.js"></script>
<br/><!-- Just so that JSFiddle's Result label doesn't overlap the Chart -->
<div id="chartContainer" style="height: 360px; width: 100%;"></div>
JavaScript
var data = '[{"x":"new Date(2016,6,26)","y":8060},{"x":"new Date(2016,6,28)","y":5760}]'; //Server returns stringified JSON data
var dps;
mychart(data);
function mychart(data) {
//alert(data);
dps = JSON.parse(data); //Parse the stringified data
/*In the stringified data, you need to extract the date leaving 'new Date' as its of type string and not Date-time.
Extract it as different groups so that you can pass each field as number to date-object, as new Date("2016,6,26") points to 26-Jun-2016 whereas new Date(2016,6,26) points to 26-Jul-2016*/
for(var i=0;i<dps.length;i++){
dps[i].x = dps[i].x.match(/(\d*),(\d*),(\d*)/);//Extract date as seperate groups
dps[i].x = new Date(Number(dps[i].x[1]), Number(dps[i].x[2]), Number(dps[i].x[3]));//Create new Date object and assign it to x
}
/*alert(data);
remove non-printable and other non-valid JSON chars
var datap = data.replace(/[\u0000-\u0019]+/g,””);
var datapoint=eval(datap); //
alert(datapoint);*/
var chart = new CanvasJS.Chart("chartContainer", {
title: {
text: "Growth of Gangnam Style on YouTube"
},
axisX: {
valueFormatString: "DD-MMM",
interval: 2,
intervalType: "day",
labelAngle: -50,
labelFontColor: "rgb(0,75,141)",
// minimum: new Date(2012, 06, 10)
},
axisY: {
title: "Views on YouTube",
interlacedColor: "azure",
tickColor: "azure",
titleFontColor: "rgb(0,75,141)",
valueFormatString: "#M,.",
interval: 1000
},
data: [{
type: "line", //Type of Chart
dataPoints: dps
}]
});
chart.render();
}