我使用chart.js 创建了一个具有负值的条形图。现在我不想在 Y 轴上显示 0(零)值。
我用谷歌搜索了很多东西,但我没有运气。
我也尝试了以下属性。
ticks: {
beginAtZero: false
}
scaleStartValue: -20, scaleStepWidth: 20, scaleSteps: 3, scaleBeginAtZero: false,
但我没有成功。
检查下图,我已经提到了我的预期结果。
这可以使用以下 y 轴刻度回调函数来实现:
callback: function(value, index) {
if (value !== 0) return value + '%';
}
或 - “将 0 值更改为 100%”:
callback: function(value, index) {
if (value === 0) return 100 + '%';
else return value + '%';
}
演示
var chart = new Chart(ctx, {
type: 'bar',
data: {
labels: ['Jan', 'Feb', 'Mar', 'Apr', 'May'],
datasets: [{
label: 'BAR',
data: [50, 20, -60, 55, -35],
backgroundColor: 'rgba(0, 119, 290, 0.2)',
borderColor: 'rgba(0, 119, 290, 0.6)',
borderWidth: 2
}]
},
options: {
scales: {
yAxes: [{
ticks: {
stepSize: 50,
callback: function(value, index) {
if (value !== 0) return value + '%';
/* OR *
if (value === 0) return 100 + '%';
else return value + '%'; */
}
}
}]
}
}
});
<script src="https://cdnjs.cloudflare.com/ajax/libs/Chart.js/2.6.0/Chart.min.js"></script>
<canvas id="ctx"></canvas>
ChartJS v4 和react-chartjs-2 v5。对于 x 轴,我使用了这个系统:
options: {
scales: {
x: {
ticks: {
callback: function(val, index) {
if (index === 0) return null;
return this.getLabelForValue(val);
}
}
}
}
}
从此文档中:勾选配置
因为val和index是相同的。所以我必须使用 getLabelForValue 来获取刻度标签。