gpt4 book ai didi

chart.js - Chart.js 图的 x 轴仅显示第 n 个刻度线

转载 作者:行者123 更新时间:2023-12-04 22:42:07 37 4
gpt4 key购买 nike

一段时间以来,我一直在寻找解决方案,但由于大量已删除的文档和对以前版本的库的笨拙答案,我一直没有接近解决方案。

我正在使用 ChartJS v2 制作一个图表,沿 x 轴显示季度月份名称,并且我设置了标签,以便仅显示每 4 个标签(即每年一个)。结果是这样的:

enter image description here

但是,我希望刻度线也只出现在与标签相同的每 4 个 x 轴条目上。这可能吗?

我当前的脚本标签如下:

<script>
var ctx = document.getElementById("myChart").getContext('2d');
ctx.canvas.width = 600;
ctx.canvas.height = 420;
var myChart = new Chart(ctx, {
type: 'line',
data: {

< snipped for brevity >

},
options: {
tooltips: {
mode: 'index',
intersect: false
},
scales: {
xAxes: [{
ticks: {
userCallback: function(item, index) {
if (index%4) return "";
return item;
},
autoSkip: false
},
display: true
}],
yAxes: [{
ticks: {
beginAtZero:true
}
}]
}
}
});
</script>

这有可能实现吗?提前致谢。

最佳答案

更换您的滴答声 userCallback具有以下功能...

userCallback: function(item, index) {
if (!(index % 4)) return item;
}

基本上,您不需要为要隐藏的标签返回任何空字符串。如果您不返回任何内容(对于您不想要的标签),它将不会为该标签绘制任何刻度(以及网格线)。

ᴅᴇᴍᴏ

var ctx = document.getElementById("myChart").getContext('2d');
var myChart = new Chart(ctx, {
type: 'line',
data: {
labels: ['Jan', 'Feb', 'Mar', 'Apr', 'May', 'Jun', 'Jul', 'Aug', 'Sept'],
datasets: [{
label: 'Standard Rating',
data: [1, 2, 3, 4, 5, 6, 7, 8, 9],
backgroundColor: 'rgba(209, 230, 245, 0.5)',
borderColor: 'rgba(56, 163, 236, 1)',
borderWidth: 1
}]
},
options: {
responsive: false,
tooltips: {
mode: 'label',
intersect: false
},
scales: {
xAxes: [{
ticks: {
userCallback: function(item, index) {
if (!(index % 4)) return item;
},
autoSkip: false
}
}],
yAxes: [{
ticks: {
beginAtZero: true
}
}]
}
}
});
<script src="https://cdnjs.cloudflare.com/ajax/libs/Chart.js/2.5.0/Chart.min.js"></script>
<canvas id="myChart" width="350" height="200"></canvas>

关于chart.js - Chart.js 图的 x 轴仅显示第 n 个刻度线,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/44361991/

37 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com