13
Help us understand the problem. What are the problem?

More than 5 years have passed since last update.

posted at

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

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);

終わりに

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

Why not register and get more from Qiita?
  1. We will deliver articles that match you
    By following users and tags, you can catch up information on technical fields that you are interested in as a whole
  2. you can read useful information later efficiently
    By "stocking" the articles you like, you can search right away
Sign upLogin
13
Help us understand the problem. What are the problem?