You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

如何在Chart.js中移除数据集时同步删除对应Y轴?

解决Chart.js移除数据集后对应Y轴未删除的问题

Chart.js不会自动清理未被任何数据集引用的Y轴,因此移除数据集后需要手动检查并删除废弃的Y轴。具体实现步骤如下:

  • 移除数据集时,先记录该数据集绑定的yAxisID
  • 遍历剩余数据集,确认是否还有其他数据集使用该yAxisID
  • 若没有任何数据集使用,从图表的options.scales中删除对应Y轴
  • 调用chart.update()更新图表

修改后的完整代码

<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,
            scales: {
                "0": {
                    position: 'left'
                }
            }
        },
    });

    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(){
        const newAxisId = String(my_chart.data.datasets.length);
        temp = Array.from({length: 10}, () => Math.floor(Math.random() * 10));
        let data_store = {
            label: newAxisId,
            yAxisID: newAxisId,
            data: temp,
            backgroundColor: getRandomColor(),
        };
        my_chart.data.datasets.push(data_store);
        // 配置新Y轴位置为右侧,避免重叠
        my_chart.options.scales[newAxisId] = {
            position: 'right',
            grid: {
                drawOnChartArea: false
            }
        };
        my_chart.update();
    }

    function remove_dataset(){
        if (my_chart.data.datasets.length <= 1) return; // 保留至少一个数据集
        let temp_num = Math.floor(Math.random() * my_chart.data.datasets.length);
        const removedAxisId = my_chart.data.datasets[temp_num].yAxisID;
        
        // 移除目标数据集
        my_chart.data.datasets.splice(temp_num, 1);
        
        // 检查剩余数据集是否仍在使用该Y轴
        const hasActiveUsage = my_chart.data.datasets.some(ds => ds.yAxisID === removedAxisId);
        
        if (!hasActiveUsage) {
            // 删除废弃的Y轴
            delete my_chart.options.scales[removedAxisId];
        }
        
        my_chart.update();
    }
</script>

关键修改说明

  1. 添加数据集时手动配置Y轴:给每个新Y轴设置position: 'right'并关闭图表区域内的网格线,避免多轴重叠导致的视觉混乱。
  2. 移除数据集时清理废弃Y轴:先获取被删数据集的yAxisID,检查剩余数据集是否还有引用,无引用则删除对应的scales配置。

内容的提问来源于stack exchange,提问作者Aravind

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.08.14 01:50:25