在chartjs中的y轴上设置固定的步长和刻度数

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

我已经使用scales.y.ticks.stepsize和scales.y.ticks.count属性来按照文档制作固定的步长和刻度计数,但它不起作用。

我需要

scales.y.ticks.stepsize = 20

scales.y.ticks.count = 5

如果数据集包含较大数字(如 (50, 90))但不包含较小数字 (1, 3),则该方法有效。

Jsfiddle链接:https://jsfiddle.net/9r2wf6d4/4/

有人可以帮我吗?我会很感激的!

javascript chart.js
1个回答
0
投票

解决方案可能是在 y 轴上设置

min
max

scales: {
    y: {
        ticks: {
            stepSize: 20,
            count: 5
        },
        min: 0, 
        max: 100
    }
}

var data = {
  labels: ["x1", "x2", "x3"],
  datasets: [{
    label: "First",
    backgroundColor: 'rgba(255, 99, 132, 0.2)',
    borderWidth: 1,
    data: [3, 20, 30],
    barPercentage: 0.3,
  },
  {
    label: "Second",
    backgroundColor: 'green',
    borderWidth: 1,
    data: [3, 7, 9],
    barPercentage: 0.3,
  },
  {
    label: "Third",
    backgroundColor: 'rgba(255, 206, 86, 0.2)',
    borderWidth: 1,
    data: [3, 3, 3],
    barPercentage: 0.5,
    yAxisID: "total"
  }]
};

var options = {
  toolbar: {
      show: false
  },
  fill: {
    type: "gradient",
    gradient: {
      shadeIntensity: 1,
      opacityFrom: 0.5,
      opacityTo: 0.5,
      stops: [0, 100]
    }
  },
 scales: {
    x: {
      stacked: true,
      barThickness: 30,
    }, 
    y: {
      min: 0,   // Minimum value
      max: 100, // Maximum value
      stacked: true,
      ticks: {
        count: 5,
        beginAtZero: true,
        autoSkip: false, 
        stepSize: 20,
      },
      grid: {
        drawBorder: false
      }
    },
    total: {
      min: 0,   // Minimum value
      max: 5,   // Maximum value
      display: true,
      ticks: {
        count: 5,
        autoSkip: false,
        stepSize: 1,
      },
      beginAtZero: true,
      position: 'right',
    }
}

};

var ctx = document.getElementById("myChart").getContext("2d");
var myBarChart = new Chart(ctx, {
  type: 'bar',
  data: data,
  options: options
});
<script src="https://cdnjs.cloudflare.com/ajax/libs/Chart.js/3.7.1/chart.min.js"></script>


<canvas id="myChart" width="500" height="100"></canvas>

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