如何在chart.js中删除数据集时删除y轴



我需要向图表中添加多个数据集,并根据id从图表中删除数据集。我使用yAxisID为每个数据集添加不同的y轴。当我从图表中删除数据集时,y轴不会被删除。如何删除相应的y轴?

代码如下:

<script src="https://cdnjs.cloudflare.com/ajax/libs/Chart.js/3.5.1/chart.min.js"></script>
<div style="width: 400px;height: 200px;">
<canvas id="myChart"></canvas>
</div>
<button onclick="add_dataset()">add dataset </button>
<button onclick="remove_dataset()">remove random dataset</button>
<script>
const ctx = document.getElementById('myChart');
my_chart = new Chart(ctx, {
type: 'line',
data: {
labels: [0,1,2,3,4,5,6,7,8,9,10],
datasets: [{
label: "0",
yAxisID: "0",
data: Array.from({length: 10}, () => Math.floor(Math.random() * 10)),
backgroundColor: getRandomColor(),
}]
},
options: {
responsive: true,
},
});
function getRandomColor() {
var letters = '0123456789ABCDEF'.split('');
var color = '#';
for (var i = 0; i < 6; i++) {
color += letters[Math.floor(Math.random() * 16)];
}
return color;
}
function add_dataset(){
temp = Array.from({length: 10}, () => Math.floor(Math.random() * 10));
let data_store = {
label: String(my_chart.data.datasets.length),
yAxisID: String(my_chart.data.datasets.length),
data: temp,
backgroundColor: getRandomColor(),
};
my_chart.data.datasets.push(data_store)
my_chart.update();
}
function remove_dataset(){
let temp_num =  Math.floor(Math.random() * my_chart.data.datasets.length);
my_chart.data.datasets.splice(temp_num, 1);
my_chart.update();
}
</script>

我试着把天平从我的图表上取下来。但没有效果。

options对象中,尝试:

options: {
responsive: true,
scales: {
[yAxisId]: {
display: false,
},
},
}

最新更新