ChartJS x轴标签全部显示


<script src="https://cdn.jsdelivr.net/npm/chart.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/chartjs-plugin-datalabels/2.0.0/chartjs-plugin-datalabels.min.js"></script>
<div style="width:50%">
<canvas id="chart2" style="width:100%"></canvas>
</div>
<script>
var yLabels = {
1 : 'New',
2 : 'Learning Phase',
3 : 'Good',
4 : 'Strong',
5 : 'Master'
}

Chart.register(ChartDataLabels);
new Chart('chart2', {
type: 'bar',
data: {
labels: ['Tommy','Fred'],
datasets: [{
data: [3,1],
}]
},
options: {

indexAxis: 'y',
layout: {
padding: {
right: 60
}
},
plugins: {
title: {
display: true,
text: "Skill Chart"
},
legend: {
display: false,
},
datalabels: {
color: 'blue',
formatter: (value) => {
if (value == 1) {
value = 'New';
return value;
}
if (value == 2) {
value = 'Learning Phase';
return value;
}

if (value == 3) {
value = 'Good';
return value;
}
if (value == 4) {
value = 'Strong';
return value;
}
if (value == 5) {
value = 'Master';
return value;
}
},
anchor: 'end',
align: 'right',
labels: {
title: {
font: {
weight: 'bold'
}
}
}
}
},
scales: {
y: {
grid: {
display: false
},
ticks: {
},
},
x: {
ticks:{
callback: function(value, index, values) {
return yLabels[value];
},
precision: 1,
},
grid: {
display: false,
}
}
}
}
});
</script>

上面是一个工作代码,但我现在面临的是,如何在x轴上显示变量ylabels中的所有标签?我试过autoSkip:false。它不起作用。

我想要的是,它显示了从(新到主(的所有标签,尽管数据只有3和1。如果我把标签改为"5",一切都会很顺利。

https://codepen.io/kennyl80841728/pen/jOxzLjy

您需要如下定义options.scales.x.max

options: {
scales: {
x: {
max: 5,
...

有关更多信息,请参阅Chart.js文档中的最小-最大配置

最新更新