概要
みなさんこんにちはcandleです。今回はChart.js2.0でy軸の最大値、最小値を設定する方法を紹介します。
Chart.js 2.0では特に指定しないと自動的に、y軸の最大値を設定してくれますが、場合によっては自分で設定したい場合があります。
前提
Chart jsが用意されている
最大値と最小値を設定する
結論から書くと以下のようなサンプルソースコードになります。y軸を指定しているのはoptionsのところです。
$(document).on('ready', function() { var ctx, data, myChart; ctx = document.getElementById('myChart'); if (ctx !== null) { data = { labels: ['January', 'February', 'March', 'April', 'May', 'June', 'July'], datasets: [ { label: 'My First dataset', fill: false, lineTension: 0.1, backgroundColor: 'rgba(75,192,192,0.4)', borderColor: 'rgba(75,192,192,1)', borderCapStyle: 'butt', borderDash: [], borderDashOffset: 0.0, borderJoinStyle: 'miter', pointBorderColor: 'rgba(75,192,192,1)', pointBackgroundColor: '#fff', pointBorderWidth: 1, pointHoverRadius: 5, pointHoverBackgroundColor: 'rgba(75,192,192,1)', pointHoverBorderColor: 'rgba(220,220,220,1)', pointHoverBorderWidth: 2, pointRadius: 1, pointHitRadius: 10, data: [65, 59, 80, 81, 56, 55, 40] } ] }; return myChart = new Chart.Line(ctx, { data: data, options: { scales: { yAxes: [ { ticks: { beginAtZero: true, min: 0, max: 100 } } ] } } }); } });
optionsだけ取り出すと以下のようになります。
myChart = new Chart.Line(ctx, { data: data, options: { scales: { yAxes: [ { ticks: { beginAtZero: true, min: 0, max: 100 } } ] } } });
これでグラフを表示するとy軸の最大値が100になっています。
coffeeでは以下のようになります。
$(document).on 'ready', -> ctx = document.getElementById('myChart') if ctx != null data = labels: ['January','February','March','April','May','June','July'] datasets: [ { label: 'My First dataset' fill: false lineTension: 0.1 backgroundColor: 'rgba(75,192,192,0.4)' borderColor: 'rgba(75,192,192,1)' borderCapStyle: 'butt' borderDash: [] borderDashOffset: 0.0 borderJoinStyle: 'miter' pointBorderColor: 'rgba(75,192,192,1)' pointBackgroundColor: '#fff' pointBorderWidth: 1 pointHoverRadius: 5 pointHoverBackgroundColor: 'rgba(75,192,192,1)' pointHoverBorderColor: 'rgba(220,220,220,1)' pointHoverBorderWidth: 2 pointRadius: 1 pointHitRadius: 10 data: [65,59,80,81,56,55,40] } ] myChart = new Chart.Line(ctx, data: data options: scales: yAxes: [ { ticks: beginAtZero: true min: 0 max: 100 } ] )
まとめ
chart jsが1.0から2にバージョンアップしてこの指定がわからなくて苦労しました。