我实现了一个带有四个水平条
的图表。最后一个有将近 35k 条记录,因此 stepSize
自动 为 2250。第一个柱只有 20 条记录。
第一个 bar 的
20 条记录没有显示任何颜色,因为与 stepSize
2250 相比,数字较少。
这是我的代码
scales: {
xAxes: [
{
ticks: {
beginAtZero: true,
stepSize: 50,
},
stacked: true
}
],
yAxes: [
{
ticks: {
fontSize: 12
},
stacked: true
}
]
},
animation: {
onComplete: function() {
var chartInstance = this.chart;
var ctx = chartInstance.ctx;
ctx.textAlign = "left";
ctx.fillStyle = "#fff";
//draw total count
charData.datasets[0].data.forEach(function(data, index) {
var total = this.data.datasets[0].data[index];
var meta = chartInstance.controller.getDatasetMeta(0);
var posX = meta.data[index]._model.x;
var posY = meta.data[index]._model.y;
ctx.fillStyle = "black";
if(total.toString().length>=5)
ctx.fillText(total, posX -40, posY + 2);
else if(total==0)
ctx.fillText(total, posX -4, posY + 4);
else
ctx.fillText(total, posX - 10, posY + 4);
}, this);
}
这是输出
我该如何解决这个问题?
最佳答案
您的问题与ticks.stepSize
无关,此选项仅控制如何创建刻度,但不会更改条形的大小。
您可以将 x 轴定义为 logarithmic cartesian axis如下面的可运行代码片段所示。
new Chart('myChart', {
type: 'horizontalBar',
data: {
labels: ['0-12 hr', '12-24 hr', '1-3 day', '3-15 day'],
datasets: [{
label: '',
data: [20, 0, 0, 34343],
backgroundColor: ["rgba(255, 99, 132, 0.2)", "rgba(255, 159, 64, 0.2)", "rgba(255, 205, 86, 0.2)", "rgba(75, 192, 192, 0.2)"],
borderColor: ["rgb(255, 99, 132)", "rgb(255, 159, 64)", "rgb(255, 205, 86)", "rgb(75, 192, 192)"],
borderWidth: 1
}]
},
options: {
legend: {
display: false
},
scales: {
xAxes: [{
type: 'logarithmic',
ticks: {
beginAtZero: true,
userCallback: (value, index) => {
const remain = value / (Math.pow(10, Math.floor(Chart.helpers.log10(value))));
if (remain == 1 || remain == 2 || remain == 5 || index == 0) {
return value.toLocaleString();
}
return '';
}
},
gridLines: {
display: false
}
}]
}
}
});
canvas {
max-width: 400px;
}
<script src="https://cdn.jsdelivr.net/npm/chart.js@2.8.0"></script>
<canvas id="myChart" height="150"></canvas>
关于javascript - 如何为 Chart.js 图中的每个水平条制作自定义步长,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/63629014/