LoginSignup
1
1

More than 3 years have passed since last update.

Chart.js【javascriptで簡単にグラフが描ける!】

Last updated at Posted at 2020-01-22

1.Chart.jsを読み込む

CDNサーバからスクリプト「Chart.js」を読み込みます。
具体的には、グラフを描きたいWebページのHTMLソース中に以下の1行を加えるだけです。

<script src="https://cdnjs.cloudflare.com/ajax/libs/Chart.js/2.7.2/Chart.bundle.min.js"></script>

2.canvas要素を記述

グラフを掲載したい場所に、canvas要素を使って下記のように1行を記述するだけです。
idは他と重複しない名前をつけます。

<canvas id="ChartDemo" height="450" width="600"></canvas>

3.グラフの描画内容をscript要素内に記述

<script>
   描画内容の指示下記に記述例があります
</script>

描画内容の指示(以下のようなグラフの例)
・折れ線グラフです。
・X軸には、Item1~Item7の項目があります。
・値は、Item1から順に10, 11, 12, 13, 14, 15, 16です。
・オプションで、Y軸を0~100に固定しています。


var ctx = document.getElementById("ChartDemo").getContext('2d');
var ChartDemo = new Chart(ctx, {
  // 作成するグラフの種類
  type: 'line',
  data: {
  // ラベルとデータセットを設定
    labels: ["Item1", "Item2", "Item3", "Item4", "Item5", "Item6", "Item7"],
    datasets: [
      {
        label: "Chart-1",
        borderColor: 'rgb(255, 0, 0)',
        data: [10, 11, 12, 13, 14, 15, 16],
      },
    ]
  },
  // オプション設定
  options: {
    scales: {
      yAxes: [
        {
          ticks: {
            beginAtZero: true,
            min: 0,
            max: 100
          }
        }
      ]
    }
  }
});

感想

簡単ですね、すごい!
オプション指定で色々できそうです。
今は便利なライブラリが色々あるんですねー。

自己紹介

プログラマー歴7年、ブランク10年のアラフォー主婦です。
記事中に間違っていることがあったら、どんどんつっこんで頂けると嬉しいです。

1
1
0

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
1
1