Javascript examples for Chart.js:Line Chart
Chartjs to add phases in line chart
<html> <head> <meta name="viewport" content="width=device-width, initial-scale=1"> <script type="text/javascript" src="https://cdnjs.cloudflare.com/ajax/libs/Chart.js/2.2.2/Chart.min.js"></script> <script type="text/javascript"> window.onload=function(){/*w w w.jav a 2s . co m*/ var ctx = document.getElementById("canvas"); var phasePlugin = { afterDraw: function(chart) { var ctx = chart.chart.ctx; var xAxeId = chart.config.options.scales.xAxes[0].id; var xAxe = chart.scales[xAxeId]; var yAxeId = chart.config.options.scales.yAxes[0].id; var yAxe = chart.scales[yAxeId]; var ticks = xAxe.ticks; var phases = chart.config.options.scales.xAxes[0].phases; for (var i = 0; i < phases.length; i++) { if (ticks.indexOf(phases[i].from) == -1 || (ticks.indexOf(phases[i].to) == -1)) continue; var xPos = ((xAxe.width - xAxe.paddingRight) / xAxe.maxIndex) * ticks.indexOf(phases[i].from) + xAxe.left + 1; ctx.setLineDash([8, 8]); ctx.strokeStyle = phases[i].color; ctx.strokeRect(xPos, yAxe.top, 0, yAxe.height); xPos = ((xAxe.width - xAxe.paddingRight) / xAxe.maxIndex) * ticks.indexOf(phases[i].to) + xAxe.left + 1; ctx.strokeStyle = phases[i].color; ctx.strokeRect(xPos, yAxe.top, 0, yAxe.height); ctx.setLineDash([1,0]); } } }; Chart.pluginService.register(phasePlugin); var data = { labels: ["January", "February", "March", "April", "May", "June", "July"], datasets: [ { label: "My First dataset", fill: false, lineTension: 0.1, backgroundColor: "rgba(75,192,192,0.4)", borderColor: "rgba(75,192,192,1)", borderCapStyle: 'butt', borderDash: [], borderDashOffset: 0.0, borderJoinStyle: 'miter', pointBorderColor: "rgba(75,192,192,1)", pointBackgroundColor: "#fff", pointBorderWidth: 1, pointHoverRadius: 5, pointHoverBackgroundColor: "rgba(75,192,192,1)", pointHoverBorderColor: "rgba(220,220,220,1)", pointHoverBorderWidth: 2, pointRadius: 1, pointHitRadius: 10, data: [65, 59, 80, 81, 56, 55, 40], spanGaps: false, } ] }; var myLineChart = new Chart(ctx, { type: 'line', data: data, options: { scales: { xAxes: [{ phases: [{ from: "January", to: "March", color: "blue" }, { from: "May", to: "June", color: "red" }] }] } } }); } </script> </head> <body> <canvas id="canvas" height="200"></canvas> </body> </html>