Javascript 在chartJS中跳过y轴上的小数点
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/37699485/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
Skip decimal points on y-axis in chartJS
提问by mohsinali1317
I am using thislibrary to draw charts in my web app. The issue is that I am having decimal points in my y-axis. You can see that in the image below
我正在使用这个库在我的网络应用程序中绘制图表。问题是我的 y 轴有小数点。你可以在下图中看到
Is there a way that I can restrict it to only have numbers?
有没有办法可以限制它只有数字?
This is my code
这是我的代码
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
})
回答by Quince
Update:please see an updated answer from @DreamTeK
that shows how this can now be done as part of the chartjs api https://stackoverflow.com/a/54006487/2737978
更新:请查看更新后的答案,@DreamTeK
该答案显示了现在如何将其作为 chartjs api 的一部分来完成https://stackoverflow.com/a/54006487/2737978
in chartjs 2.x you can pass an option for a userCallback
to the yaxis tick field. In this you can check if the label is a whole number
在 chartjs 2.x 中,您可以将 a 的选项传递userCallback
给 yaxis 刻度字段。在此您可以检查标签是否为整数
here is an example
这是一个例子
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;
}
},
}
}],
},
}
回答by DreamTeK
2019 Update
2019年更新
This can now easily be achieved using the precision
option:
现在可以使用以下precision
选项轻松实现这一点:
ticks: {
precision:0
}
As per the documentation.
根据文档。
If defined and stepSize is not specified, the step size will be rounded to this many decimal places.
如果已定义且未指定 stepSize,则步长将四舍五入到这么多小数位。
回答by John Rix
Another alternative is to use the fixedStepSize option as follows:
另一种选择是使用 fixedStepSize 选项,如下所示:
options = {
scales: {
yAxes: [{
ticks: {
fixedStepSize: 1
}
}],
},
};
回答by Mohammad
by the latest version this option changed to
到最新版本,此选项更改为
scales: {
yAxes: [{
ticks: {
stepSize: 1,
beginAtZero: true,
},
}],
},