Chart.js 棒グラフ

棒グラフは、長方形の長さを変数とする統計グラフです。

棒グラフは、2つ以上の値(異なる時間や異なる条件)を比較するために使われます。変数は1つだけで、通常は小さなデータセットの分析に利用されます。

棒グラフのtypeプロパティはbar、type はチャートタイプを表します。

const config = {
  type: 'bar',
  data: data,
  options: {
    scales: {
      y: {
        beginAtZero: true
      }
    }
  },
};

次に、簡単な棒グラフを作成してみましょう。

サンプル

const ctx = document.getElementById('myChart');
const labels = ['一月份', '二月份', '三月份','四月份', '五月份', '六月份', '七月份'];  // X軸上の対応するラベルを設定
const data = {
  labels: labels,
  datasets: [{
    label: '私の最初の棒グラフ',
    data: [65, 59, 80, 81, 56, 55, 40],
    backgroundColor: [      // 各棒グラフの背景色を設定
      'rgba(255, 99, 132, 0.2)',
      'rgba(255, 159, 64, 0.2)',
      'rgba(255, 205, 86, 0.2)',
      'rgba(75, 192, 192, 0.2)',
      'rgba(54, 162, 235, 0.2)',
      'rgba(153, 102, 255, 0.2)',
      'rgba(201, 203, 207, 0.2)'
    ],
    borderColor: [     // 各棒グラフの枠線の色を設定
      'rgb(255, 99, 132)',
      'rgb(255, 159, 64)',
      'rgb(255, 205, 86)',
      'rgb(75, 192, 192)',
      'rgb(54, 162, 235)',
      'rgb(153, 102, 255)',
      'rgb(201, 203, 207)'
    ],
    borderWidth: 1     // 線の幅を設定
  }]
};
const config = {
  type: 'bar', // チャートタイプを設定
  data: data,  // データセットを設定
  options: {
    scales: {
      y: {
        beginAtZero: true // y軸を0から開始するように設定
      }
    }
  },
};
const myChart = new Chart(ctx, config);

試してみる »

上記のサンプルの出力結果は次のとおりです:

水平棒グラフ

水平棒グラフは垂直棒グラフの変形で、データの傾向を表示したり、複数のデータセットを並べて比較するためによく使用されます。

水平棒グラフを設定するには、オプションオブジェクトの indexAxis プロパティをy、indexAxis プロパティのデフォルト値はx。

サンプル

const ctx = document.getElementById('myChart');
const labels = ['一月份', '二月份', '三月份','四月份', '五月份', '六月份', '七月份'];  // X軸上の対応するラベルを設定
const data = {
  labels: labels,
  datasets: [{
    axis: 'y',
    label: '私の最初の棒グラフ',
    data: [65, 59, 80, 81, 56, 55, 40],
    fill: false,
    backgroundColor: [      // 各棒グラフの背景色を設定
      'rgba(255, 99, 132, 0.2)',
      'rgba(255, 159, 64, 0.2)',
      'rgba(255, 205, 86, 0.2)',
      'rgba(75, 192, 192, 0.2)',
      'rgba(54, 162, 235, 0.2)',
      'rgba(153, 102, 255, 0.2)',
      'rgba(201, 203, 207, 0.2)'
    ],
    borderColor: [     // 各棒グラフの枠線の色を設定
      'rgb(255, 99, 132)',
      'rgb(255, 159, 64)',
      'rgb(255, 205, 86)',
      'rgb(75, 192, 192)',
      'rgb(54, 162, 235)',
      'rgb(153, 102, 255)',
      'rgb(201, 203, 207)'
    ],
    borderWidth: 1     // 線の幅を設定
  }]
};
const config = {
  type: 'bar', // チャートタイプを設定
  data: data,  // データセットを設定
  options: {
    indexAxis: 'y',
  }
};
const myChart = new Chart(ctx, config);

試してみる »

上記のサンプルの出力結果は次のとおりです:

その他の拡張