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

时间:2016-06-08 10:08:42

标签: javascript chart.js

我正在使用this库在我的网络应用中绘制图表。问题是我在y轴上有小数点。您可以在enter image description here

下面的图片中看到

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

这是我的代码

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

    })

6 个答案:

答案 0 :(得分:96)

更新:请参阅@DreamTeK的更新回复,其中显示了现在如何在chartjs api https://stackoverflow.com/a/54006487/2737978

中完成此操作

在chartjs 2.x中,您可以将userCallback的选项传递给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;
                     }

                 },
             }
         }],
     },
 }

fiddle example

答案 1 :(得分:18)

2019更新

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

ticks: {
  precision:0
}

按照documentation

  

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

答案 2 :(得分:15)

此选项的最新版本更改为

scales: {
  yAxes: [{
    ticks: {
      stepSize: 1,
      beginAtZero: true,
    },
  }],
},

答案 3 :(得分:1)

最简单、最直接的解决方案是将这些配置添加到您的选项对象中:

    scales: {
  yAxes: [
    {
      ticks: {
        precision: 0,
        beginAtZero: true,
      },
    },
  ],
},

并根据您的带分数的轴定义轴(在我的情况下是 yAxes)

答案 4 :(得分:0)

您可以使optopn滑行;

decimalsInFloat:数字

y轴上有浮点值时要显示的分数数。 注意:如果您已在yaxis.labels.formatter中定义了自定义格式化程序功能,则此操作将无效。

答案 5 :(得分:0)

我使用这个:

yAxes: [
        {
            ticks: {
                    callback: function(val) {
                    return Number.isInteger(val) ? val : null;
                }
            }
        }
    ]

注意:使用回调函数可实现更好的粒度控制。我们检查val是否为整数而不是浮点十进制。如果是,我们返回该值。如果不是,则返回null。

相关问题