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

如何在Chart.js中实现Y轴边框两侧显示刻度线?

实现Chart.js Y轴双侧刻度线的解决方案

要实现Y轴边框两侧都显示刻度线,Chart.js默认单轴无法直接实现,核心思路是添加一个镜像的右侧Y轴,仅保留刻度线,隐藏其他冗余元素,具体修改如下:

关键修改点

  • 在scales中新增一个右侧Y轴(命名为y1),位置设为right
  • 右侧轴继承左侧Y轴的刻度规则(stepSize、max、beginAtZero等)
  • 隐藏右侧轴的标签、网格线和边框,仅保留刻度线

修改后的完整代码

<canvas id="myChart"></canvas>
<script>
    var config = {
        type: 'line',
        data: {
            labels: ["17"],
            datasets: [{
                label: "My First dataset",
                data: [0],
                fill: false
            },
            {
                label: "My First dataset",
                data: [100],
                fill: false
            }]
        },
        options: {
            responsive: true,
            maintainAspectRatio: false,
            clip: false,
            scales: {
                x: {
                    grid: {
                        display: false
                    },
                    border: { display: false },
                    ticks: {
                        fontColor: "green",
                        fontSize: 18,
                        stepSize: 1,
                        beginAtZero: true
                    }
                },
                y: {
                    grid: {
                        display: true,
                        drawTicks: true,
                        borderColor: "transparent",
                        color: "transparent",
                        tickColor: "#868e96"
                    },
                    beginAtZero: true,
                    max: 100,
                    ticks: {
                        stepSize: 20,
                        crossAlign: 'far'
                    }
                },
                // 新增右侧Y轴,仅显示刻度线
                y1: {
                    position: 'right',
                    beginAtZero: true,
                    max: 100,
                    ticks: {
                        stepSize: 20,
                        display: false, // 隐藏标签文字
                        crossAlign: 'far'
                    },
                    grid: {
                        display: false, // 隐藏右侧网格线
                        drawTicks: true,
                        tickColor: "#868e96" // 刻度线颜色和左侧一致
                    },
                    border: {
                        display: false // 隐藏右侧边框
                    }
                }
            },
            plugins: {
                legend: {
                    display: false
                }
            }
        }
    };
    var ctx = document.getElementById("myChart").getContext("2d");
    var chart = new Chart(ctx, config);
</script>

说明

  • 两个Y轴的刻度规则完全同步,保证两侧刻度线对齐
  • 右侧轴仅保留刻度线元素,避免出现重复的标签和网格线
  • 如果后续需要调整刻度样式,只需同步修改两个轴的tickColor等参数即可

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.07.02 18:53:13