LoginSignup
9
13

More than 5 years have passed since last update.

Chart.jsの棒グラフで色分けする方法

Posted at

Chart.jsの棒グラフは色分けできない\(^o^)/

Chart.jsはcanvasを使ったグラフ描画ライブラリです。
ここに来るということはChart.jsをすでにご存知で、棒グラフで色分けする方法を知りたい人なはず(確信
ソースコードを改変したらできたので、改変場所を教えます。

完成プレビュー

chart.png

やり方

改良前

Chart.js
1163       ctx.beginPath();
1164       ctx.fillStyle = this.fillColor;
1165       ctx.strokeStyle = this.strokeColor;
1166       ctx.lineWidth = this.strokeWidth;
|
2002               fillColor : dataset.fillColor,
2004               highlightFill : dataset.highlightFill || dataset.fillColor,
2005               highlightStroke : dataset.highlightStroke || dataset.strokeColor

改変後コード

Chart.js
1163       ctx.beginPath();
+- 1164    ctx.fillStyle = this.fillColor[this.index];
+- 1165    ctx.strokeStyle = this.strokeColor[this.index];
1166       ctx.lineWidth = this.strokeWidth;
|
2002               fillColor : dataset.fillColor,
+ 2003             index : index,
2004               highlightFill : dataset.highlightFill || dataset.fillColor,
2005               highlightStroke : dataset.highlightStroke || dataset.strokeColor

棒の色指定方法

xxx.js
var ctx = document.getElementById("chart").getContext("2d");
var data = {
      labels : ["January","February","March","April","May","June","July"],
      datasets : [
        {
          fillColor   : [
            "rgba(131,185,206,0.5)",
            "rgba(131,185,206,0.5)",
            "rgba(131,185,206,0.5)",
            "rgba(131,185,206,0.5)",
            "rgba(246,133,124,0.5)",
            "rgba(246,133,124,0.5)",
            "rgba(206,195,73,0.5)"
          ],
          strokeColor : [
            "rgba(131,185,206,1)",
            "rgba(131,185,206,1)",
            "rgba(131,185,206,1)",
            "rgba(131,185,206,1)",
            "rgba(246,133,124,1)",
            "rgba(246,133,124,1)",
            "rgba(206,195,73,1)"
          ],
          data : [65,59,90,81,56,55,40]
        }
      ]
}
chart = new Chart(ctx).Bar(data);

終わりに

最初からその機能ちょうだい

9
13
1

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
9
13