chart.js - Chartjs: Is it possible to add phases in line chart? -
hello want create dynamic chart looks this: phases in line chart
is possible chartjs create vertical lines @ milestones? (if possible give each phase color)
if not, other libraries can handle dynamic line chart libraries support phases?
using chart.js plugins can this. let handle specific events triggered during chart creation beforeinit, afterupdate or afterdraw , easy implement :
var myplugin = { afterdraw: function(chart) { // triggered after chart drawn } }; chart.pluginservice.register(myplugin); plugin doing looking linked below, first let me explain how works.
in chart options, you'll need add new property, called phases, array :
// following example won't work every chart options: { scales: { xaxes: [{ // `from` & `to` must exist in xaxe ticks phases: [{ from: "january", to: "march", // can define color here color: "blue" }, { from: "may", to: "june", color: "red" }] }] } } and then, here plugin use information :
var phaseplugin = { // need handle `afterdraw` event since draw phases edges // after drawn afterdraw: function(chart) { // variables plugin needs follow ... 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; // every phase ... (var = 0; < phases.length; i++) { // check if tick exists if (ticks.indexof(phases[i].from) == -1 || (ticks.indexof(phases[i].to) == -1)) { // else, skip next phase continue; } // x position of first limit tick var xpos = ((xaxe.width - xaxe.paddingright) / xaxe.maxindex) * ticks.indexof(phases[i].from) + xaxe.left + 1; // , draw dashed line ctx.setlinedash([8, 8]); ctx.strokestyle = phases[i].color; ctx.strokerect(xpos, yaxe.top, 0, yaxe.height); // same other limit 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]); } } }; you can see working example in jsfiddle , here result :

Comments
Post a Comment