3
0

More than 3 years have passed since last update.

chartjs オプション変更後グラフ更新する

Last updated at Posted at 2021-02-14

動機

chartjsグラフのオプションを変更してから、グラフ更新するコードをメモします。
ネットで探しましたが、なかなか見つけられなくて、メモします。
複雑ではなく、簡単なコードで記録します。

グラフの縦スケールの最大値を変更してから、グラフを変更する例

index.html
<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <meta http-equiv="X-UA-Compatible" content="IE=edge">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>縦スケールオプション変更</title>
    <!-- ライブラリの指定 -->
    <script src="https://cdnjs.cloudflare.com/ajax/libs/Chart.js/2.7.1/Chart.min.js"></script>
    <script>
        window.onload = function(){
            var ctx = document.getElementById('myChart').getContext('2d');
            var chart = new Chart(ctx, {
                // 作成したいチャートのタイプ
                type: 'line',

                // データセットのデータ
                data: {
                    labels: ["1月", "2月", "3月", "4月", "5月", "6月", "7月"],
                    datasets: [{
                        label: "初めてのデータセット",
                        backgroundColor: 'rgb(255, 99, 132)',
                        borderColor: 'rgb(255, 99, 132)',
                        data: [0, 10, 5, 2, 20, 30, 45],
                    }]
                },

                // ここに設定オプションを書きます
                options: {
                    scales: {
                        yAxes: [           // Y軸 
                            {
                                ticks: {     // 目盛り        
                                    min: 0,      // 最小値
                                    max: 45,     // 最大値
                                    stepSize: 5  // 間隔
                                }
                            }
                        ]
                    }
                }
            });
            document.getElementById("square-button").onclick = function () {
                // 縦スケール最大値を変更する
                chart.options.scales.yAxes[0].ticks.max = 100
                // グラフを更新メソッド
                chart.update();
            }
        }

    </script>
</head>
<body>
    <p>縦スケール範囲を変更</p>
    <canvas id="myChart"></canvas>
    <button id="square-button">縦スケール最高値を100にする</button>
</body>
</html>

結果

変更前 最大値:45

スクリーンショット 2021-02-14 12.42.40.png

変化後 最大値:100

スクリーンショット 2021-02-14 12.42.50.png

3
0
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
3
0