在chartJS中跳过y轴上的小数点

moh*_*317 48 javascript chart.js

我正在使用这个库在我的网络应用程序中绘制图表.问题是我在y轴上有小数点.您可以在下图中看到在此输入图像描述

有没有办法可以限制它只有数字?

这是我的代码

var matches = $("#matches").get(0).getContext("2d");

var data = {
        labels: labelsFromCurrentDateTillLastWeek,
        datasets: [
            {
                label: "Last Weeks Matches",
                fillColor: "rgba(220,220,220,0.2)",
                strokeColor: "rgba(220,220,220,1)",
                pointColor: "rgba(220,220,220,1)",
                pointStrokeColor: "#fff",
                pointHighlightFill: "#fff",
                pointHighlightStroke: "rgba(220,220,220,1)",
                data: result
            }
        ]
    };

    var options = {
        scaleLabel: function (label) {
            return Math.round(label.value);
        }
    };

    var myLineChart = new Chart(matches, {
        type: 'bar',
        data: data,
        options: options

    })
Run Code Online (Sandbox Code Playgroud)

Qui*_*nce 106

在chartjs 2.x中,您可以将a的选项传递@DreamTeK给yaxis tick字段.在此,您可以检查标签是否为整数

这是一个例子

 options = {
     scales: {
         yAxes: [{
             ticks: {
                 beginAtZero: true,
                 userCallback: function(label, index, labels) {
                     // when the floored value is the same as the value we have a whole number
                     if (Math.floor(label) === label) {
                         return label;
                     }

                 },
             }
         }],
     },
 }
Run Code Online (Sandbox Code Playgroud)

小提琴的例子

  • 这些图表是否有完整的文档指南?这个http://www.chartjs.org/docs/latest/charts/line.html进行了详细介绍,但没有提及beginAtZero。 (2认同)
  • 更简单的选择:http://www.chartjs.org/docs/latest/axes/radial/linear.html?h=stepsize#tick-options (2认同)

Dre*_*TeK 32

2019更新

现在可以使用以下precision选项轻松实现:

ticks: {
  precision:0
}
Run Code Online (Sandbox Code Playgroud)

根据文档

如果已定义并且未指定stepSize,则步长将舍入到许多小数位。

  • @tonix 它在选项/刻度/刻度中。我的帖子中有官方文档和示例的链接。 (2认同)

Joh*_*Rix 24

另一种方法是使用fixedStepSize选项,如下所示:

options = {
    scales: {
        yAxes: [{
            ticks: {
                fixedStepSize: 1
            }
        }],
    },
};
Run Code Online (Sandbox Code Playgroud)

  • 这*应该是这么简单.不幸的是,当有大量数据时,此设置可防止跳过某些点.例如,当值为0到1000时,chart.js将显示0到1000之间的所有整数,而不是显示例如0,100,200等. (6认同)
  • 当前使用2.7且“ fixedStepSize”应为“ stepSize”,请参见文档:http://www.chartjs.org/docs/latest/axes/radial/linear.html?h=stepsize#tick-options。如果应用货币格式,也不能很好地发挥作用。 (2认同)

小智 19

到最新版本,此选项更改为

scales: {
  yAxes: [{
    ticks: {
      stepSize: 1,
      beginAtZero: true,
    },
  }],
},
Run Code Online (Sandbox Code Playgroud)

  • 请不要在本网站上使用“最新版本”一词。 (4认同)