2016-09-15 19 views
0

こんにちは、私はこのようになりますダイナミックなチャートを作成したい:phases in line chartChartjs:フェーズを折れ線グラフで追加することは可能ですか?

それは、特定のマイルストーンに垂直線を作成するためのChartJsで可能ですか? (可能であれば、各段階に別の色を付けてください)

もしそうでなければ、段階をサポートする動的折れ線グラフライブラリをどのようなライブラリで扱うことができますか?

答えて

1

Chart.js pluginsを使用すると、これを手助けすることができます。しかし、最初に、

var myPlugin = { 
    afterDraw: function(chart) { 
     // This will be triggered after the chart is drawn 
    } 
}; 

Chart.pluginService.register(myPlugin); 


下記リンクされます、あなたが探しているやってプラグイン:彼らはあなたが beforeInitafterUpdateまたは afterDrawのようなチャートの作成時にトリガされ、また、実装が容易されている特定のイベントを処理してみましょうそれがどのように機能するか説明しましょう。あなたのチャートオプション

、あなたは新しいプロパティを追加する必要があります、配列である、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を参照し、ここにその結果であることができます。

enter image description here

関連する問題