jquery - 如何在图表栏 JS 中设置自定义 Y 轴值 (Chart.js v2.8.0)

标签 jquery chart.js

我想设置图表条js Y轴的线差为2。

目前,Y 轴值类似于 0、10、20、30,但我需要类似于 0、2、4、6、8...30。我的代码如下

<script>
$( document ).ready(function() {
    var BarsChart = (function() {
        var $chart = $('#chart-bars');
        function initChart($chart) {
            var ordersChart = new Chart($chart, {
                type: 'bar',
                data: {
                    labels: ["Jan","Feb","Mar","Apr","May"],
                    datasets: [{
                        label: 'Events',
                        data: [0,5,6,0,0],
                        backgroundColor: "#2dce89"
                    }]
                },
                  options: {
                scales: {
                    yAxes: [{
                            display: true,
                            ticks: {
                        beginAtZero: true,
                        stepSize: 2,
                        max: 30
                            }
                        }]
                }
                  }
            });
            $chart.data('chart', ordersChart);
        }
        if ($chart.length) {
            initChart($chart);
        }
})();
});
</script>

最佳答案

您可以将 autoSkip: false 添加到 yAxis.ticks配置如下

ticks: {
  autoSkip: false,

If autoSkip is true (default), Chart.js automatically calculates how many labels can be shown and hides labels accordingly. Turn autoSkip off to show all labels no matter what.

new Chart(document.getElementById('myChart'), {
  type: 'bar',
  data: {
    labels: ["Jan", "Feb", "Mar", "Apr", "May"],
    datasets: [{
      label: 'Events',
      data: [0, 5, 6, 0, 0],
      backgroundColor: "#2dce89"
    }]
  },
  options: {
    responsive: true,
    legend: {
      display: false
    },
    scales: {
      yAxes: [{
        display: true,
        ticks: {
          autoSkip: false,
          beginAtZero: true,
          stepSize: 2,
          max: 30
        }
      }]
    }
  }
});
canvas {
  max-width: 260px;
}
<script src="https://cdnjs.cloudflare.com/ajax/libs/Chart.js/2.9.3/Chart.min.js"></script>
<canvas id="myChart" height="200"></canvas>

关于jquery - 如何在图表栏 JS 中设置自定义 Y 轴值 (Chart.js v2.8.0),我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/60584885/

相关文章:

javascript - 为什么我的 jQuery 没有返回 <select> 的值

jquery - 我可以将类应用于包含链接的表行,而不是链接本身吗?

javascript - 悬停特定框时如何将 jQuery 实现到特定类的类?

jquery - CSS 过渡 Chrome 问题

javascript - 条形图中的链接 (charts.js)

javascript - ChartJS + twig symfony

html - 如何控制我的 Chart.JS 饼图图例的位置及其外观?

backbone.js - Chartjs 与 Backbone

jQuery 轮播自动播放

javascript - 错误: Cannot find module 'canvas' - Chart.js