0
你好,我想創建一個如下所示的動態圖表:phases in line chartChartjs:是否可以在折線圖中添加相位?
ChartJs有可能在某些里程碑處創建垂直線嗎? (如果可能的話,也給每個階段另一種顏色)
如果不是,其他庫可以處理支持階段的動態折線圖庫嗎?
你好,我想創建一個如下所示的動態圖表:phases in line chartChartjs:是否可以在折線圖中添加相位?
ChartJs有可能在某些里程碑處創建垂直線嗎? (如果可能的話,也給每個階段另一種顏色)
如果不是,其他庫可以處理支持階段的動態折線圖庫嗎?
使用Chart.js plugins可以幫助你做到這一點。他們讓你處理那些圖表創建像beforeInit
,afterUpdate
或afterDraw
過程中引發的,也是容易實現的特定事件:
var myPlugin = {
afterDraw: function(chart) {
// This will be triggered after the chart is drawn
}
};
Chart.pluginService.register(myPlugin);
在你的圖表選項,你將需要添加一個新的屬性,稱爲phases
,這是一個數組:
// The following is an example that won't work with every chart
options: {
scales: {
xAxes: [{
// `from` & `to` must exist in your xAxe ticks
phases: [{
from: "January",
to: "March",
// You can also define the color here
color: "blue"
},
{
from: "May",
to: "June",
color: "red"
}]
}]
}
}
然後,這裏是使用該信息插件:
var phasePlugin = {
// You need to handle the `afterDraw` event since you draw phases edges
// after everything is drawn
afterDraw: function(chart)
{
// All the variables the 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;
// For every phase ...
for (var i = 0; i < phases.length; i++) {
// We check if the tick actually exists
if (ticks.indexOf(phases[i].from) == -1 || (ticks.indexOf(phases[i].to) == -1)) {
// Else, we skip to the next phase
continue;
}
// We get the x position of the first limit tick
var xPos = ((xAxe.width - xAxe.paddingRight)/xAxe.maxIndex) * ticks.indexOf(phases[i].from) + xAxe.left + 1;
// And draw the dashed line
ctx.setLineDash([8, 8]);
ctx.strokeStyle = phases[i].color;
ctx.strokeRect(xPos, yAxe.top, 0, yAxe.height);
// Same for the 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]);
}
}
};
你可以看到一個完全工作的例子in this jsFiddle這裏是它的結果: