Chart.js 折线图动态更改其 y 轴

问题描述 投票:0回答:1

我正在实施管理仪表板,它将显示有关 CPU 使用情况的信息

所以我需要在 y 轴上显示 0-100(百分比)的值范围,但是当我尝试实现此操作时,图表会动态更改 y 轴值,而不是静态的 0-100

javascript

new Chart(document.querySelector('#lineChart'), {
          type: 'line',
          data: {
            labels: ['January', 'February', 'March', 'April', 'May', 'June', 'July'],
            datasets: [{
              label: 'Line Chart',
              data: [20, 30, 80, 15, 5, 4, 55],
              fill: true,
              borderColor: 'rgb(75, 192, 192)',
              tension: 0.1
            }]
          },
          options: {
            scales: {
              y: {
                type: 'linear',
                ticks: {
                  beginAtZero: true,
                  stepSize: 20, // Customize the step size if needed
                  min: 0,
                  max:100,
                  suggestedMax: Math.max(maxValue,100), // Set the maximum value of the y-axis to 100
                },
              }
            }
          }
        });

html

          <canvas id="lineChart" style="max-height: 400px; display: block; box-sizing: border-box; height: 234px; width: 469px;" width="469" height="234"></canvas>


javascript html charts javascript-objects
1个回答
0
投票

min
max
beginAtZero
suggestedMax
选项应该是
scales.y
对象的键,因此位于
ticks
对象之外。但是,如果设置了
min: 0
max:100
,则不需要另外两个。 唯一位于
ticks
对象内的选项是
stepSize

new Chart(document.querySelector('#lineChart'), {
    type: 'line',
    data: {
        labels: ['January', 'February', 'March', 'April', 'May', 'June', 'July'],
        datasets: [{
            label: 'Line Chart',
            data: [20, 30, 80, 15, 5, 4, 55],
            fill: true,
            borderColor: 'rgb(75, 192, 192)',
            tension: 0.1
        }]
    },
    options: {
        scales: {
            y: {
                type: 'linear',
                min: 0,
                max:100,
                //beginAtZero: true,
                //suggestedMax: Math.max(maxValue,100), 
                ticks: {
                    stepSize: 20, // Customize the step size if needed
                },
            }
        }
    }
});
<canvas id="lineChart" style="max-height: 400px; display: block; box-sizing: border-box; height: 234px; width: 469px;" width="469" height="234"></canvas>
<script src="https://cdnjs.cloudflare.com/ajax/libs/Chart.js/4.4.1/chart.umd.js" integrity="sha512-ZwR1/gSZM3ai6vCdI+LVF1zSq/5HznD3ZSTk7kajkaj4D292NLuduDCO1c/NT8Id+jE58KYLKT7hXnbtryGmMg==" crossorigin="anonymous" referrerpolicy="no-referrer"></script>

© www.soinside.com 2019 - 2024. All rights reserved.