Chart.js 2 で積み上げ棒グラフを実装する方法
はじめに
Chart.js は無料で使用できるオープンソースなグラフ描画ライブラリです。執筆時点では、3.0.0-Alpha がリリースされていますが、今日は最新安定板の Chart.js 2.9.3 を使って積み上げ棒グラフを描画する方法をご紹介します。
1. インストール
Chart.js の公式サイトで様々なインストール方法が紹介されています。
- Installation · Chart.js documentation
- https://www.chartjs.org/docs/latest/getting-started/installation.html
今回は GitHub からファイルをダウンロードして設置しました。ダウンロードしたファイルは Chart.min.css と Chart.min.js です。
- Release v2.9.3 · chartjs/Chart.js · GitHub
- https://github.com/chartjs/Chart.js/releases/tag/v2.9.3
Chart.bundle.js は Moment.js が含まれているものとのことです。
- Bundled Build (Chart.js documentation)
- https://www.chartjs.org/docs/latest/getting-started/installation.html#bundled-build
2. 積み上げ棒グラフのサンプル
今回作ったサンプルコードです。
index.html
<!DOCTYPE html>
<html lang="ja">
<head>
<meta charset="UTF-8">
<title>Sample</title>
<link rel="stylesheet" href="Chart.min.css">
<script src="Chart.min.js"></script>
<script src="sample.js"></script>
</head>
<body>
<canvas id="myChart" width="640" height="360"></canvas>
</body>
</html>
sample.js
window.onload = function () {
const myCanvas = document.getElementById("myChart");
new Chart(myCanvas, {
type: "horizontalBar", // 縦なら "bar" を指定
data: {
labels: ["Store 1", "Store 2", "Store 3"],
datasets: [
{
label: "Orange",
data: [3, 6, 9],
backgroundColor: "#F6AD3C",
},
{
label: "Grape",
data: [12, 8, 4],
backgroundColor: "#A64A97",
},
{
label: "Melon",
data: [2, 6, 4],
backgroundColor: "#AACF52",
},
]
},
options: {
// 凡例
legend: {
position: 'right'
},
// レスポンシブ(true だとサイズ自動調整)
responsive: false,
scales: {
// X軸
xAxes: [{
scaleLabel: {
display: true,
fontColor: "#999",
labelString: "Sales Quantity"
},
stacked: true,
ticks: {
// 下記のように固定値ではなく、
// データに応じて算出するのがいいと思います
max: 24,
stepSize: 4,
}
}],
// Y軸
yAxes: [{
stacked: true
}]
}
}
});
}
- Stacked Bar Chart
- https://www.chartjs.org/docs/latest/getting-started/installation.html
公式ドキュメントではサンプルコードが少ないので、様々なサイトを調べて試行錯誤して書きました。
棒グラフの色は、下記サイトを参考にして同一トーンで揃えました。
- ブライトトーン Bright tone
- https://iro-color.com/colorchart/tone/bright-tone.html
3. おわりに
まだ Chart.js を触り始めたばかりですが、多機能で便利そうです。プラグインの作成もできるようで、グラフに各値を表示するのに使えるようなので、今度はそちらにチャレンジしてみようと思っています。