LoginSignup
1
1

More than 1 year has passed since last update.

Chart.jsの複数軸グラフはver2とver3で書き方が違う

Last updated at Posted at 2021-07-11

背景

Chart.jsでY軸(縦軸)が右と左にあると便利な事があると思う。
しかしver2.xxとver3.xxではscales以下の書き方が違うみたいなので記す。

ver2.xxのとき

chart_js_2.xx.htm
<!DOCTYPE html>
<html lang="ja">
<head>
  <meta charset="UTF-8">
  <title>Chart.js 2.xx</title>
  <script src="https://cdnjs.cloudflare.com/ajax/libs/Chart.js/2.9.4/Chart.bundle.js"></script>
</head>
<body>
<canvas id="myChart"></canvas>
<script>
var ctx = document.getElementById("myChart");
var myChart = new Chart(ctx, {
    type: 'line',
    data: {
        datasets: [{
            data: [20, 50, 100, 75, 25, 0],
            label: 'Left dataset',

            // これはデータセットを左のy軸に結びつけます
            yAxisID: 'left-y-axis'
        }, {
            data: [0.1, 0.5, 1.0, 2.0, 1.5, 0],
            label: 'Right dataset',

            // これはデータセットを右のy軸に結びつけます
            yAxisID: 'right-y-axis'
        }],
        labels: ['1月', '2月', '3月', '4月', '5月', '6月']
    },
    options: {
        scales: {//↓このあたりが違う
            yAxes: [{
                id: 'left-y-axis',
                type: 'linear',
                position: 'left'
            }, {
                id: 'right-y-axis',
                type: 'linear',
                position: 'right'
            }]
        }
    }
});
</script>
</body>
</html>

ver3.xxのとき

chart_js_3.xx.htm
<!DOCTYPE html>
<html lang="ja">
<head>
  <meta charset="UTF-8">
  <title>Chart.js 3.xx</title>
  <script src="https://cdnjs.cloudflare.com/ajax/libs/Chart.js/3.4.1/chart.min.js"></script>
</head>
<body>
<canvas id="myChart"></canvas>
<script>
var ctx = document.getElementById("myChart");
var myChart = new Chart(ctx, {
    type: 'line',
    data: {
        datasets: [{
            data: [20, 50, 100, 75, 25, 0],
            label: 'Left dataset',

            // これはデータセットを左のy軸に結びつけます
            yAxisID: 'left-y-axis'
        }, {
            data: [0.1, 0.5, 1.0, 2.0, 1.5, 0],
            label: 'Right dataset',

            // これはデータセットを右のy軸に結びつけます
            yAxisID: 'right-y-axis'
        }],
        labels: ['1月', '2月', '3月', '4月', '5月', '6月']
    },
    options: {
        scales: {//↓このあたりが違う
            'left-y-axis': {
                type: 'linear',
                position: 'left'
            },
            'right-y-axis': {
                type: 'linear',
                position: 'right'
            }
        }
    }
});
</script>
</body>
</html>
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