Chart.js で縦向きと横向きの棒グラフを作るサンプルや基本的なプロパティについて説明する。
まず、Chart.js で簡単な縦向き(垂直)の棒グラフを作る。 コードは以下の通り。
<script src="https://cdnjs.cloudflare.com/ajax/libs/Chart.js/2.7.2/Chart.min.js"></script> <style> #ex_chart {max-width:640px;max-height:480px;} </style> <canvas id="ex_chart"></canvas> <script> var ctx = document.getElementById('ex_chart'); var data = { labels: ["平成26年", "平成27年", "平成28年", "平成29年", "平成30年"], datasets: [{ label: '得点', data: [880, 740, 900, 520, 930], backgroundColor: 'rgba(255, 100, 100, 1)' }] }; var options = { scales: { yAxes: [{ ticks: { min: 300 } }] } }; var ex_chart = new Chart(ctx, { type: 'bar', data: data, options: options }); </script>
backgroundColor で棒の中に色を塗れる。 borderColor と borderWidth を使うと棒の周囲に線を描けるが、ここでは書いていない。
options にある min は yAxes(Y軸)の最低値を指定している。
そして以下のような棒グラフができる。
棒グラフを横向き(水平)にするには type に horizontalBar を指定する。 コードは上記サンプルと同じなので変更箇所だけ記す。
var options = { scales: { xAxes: [{ ticks: { min: 300 } }] } }; var ex_chart = new Chart(ctx, { type: 'horizontalBar', data: data, options: options });
type を horizontalBar に変更した。 グラフの最低値はX軸に適用したいので xAxes に変更した。 グラフは以下のようになる。
様々なプロパティを指定すると、グラフにタイトルやラベルを追加したり、複数の棒を並べることができる。 コードは上記サンプルと異なる部分だけ記す。
var data = { labels: ["1月", "2月", "3月", "4月", "5月"], datasets: [{ label: 'プリンター', data: [880, 740, 900, 520, 930], backgroundColor: 'rgba(255, 100, 100, 1)' }, { label: 'パソコン', data: [1200, 1350, 1220, 1220, 1420], backgroundColor: 'rgba(100, 100, 255, 1)' }] }; var options = { scales: { xAxes: [{ scaleLabel: { display: true, labelString: '月' } }], yAxes: [{ ticks: { min: 0, userCallback: function(tick) { return tick.toString() + '台'; } }, scaleLabel: { display: true, labelString: '台数' } }] }, title: { display: true, text: '販売台数' } }; var ex_chart = new Chart(ctx, { type: 'bar', data: data, options: options });
各種プロパティの説明は 折れ線グラフ と同じなので、そちらをご覧ください。
そして以下のような棒グラフになる。