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

Chart.js多轴配置问题:无法将折线图绑定至右侧Y轴

解决Chart.js组合图折线图绑定右侧Y轴的问题

要实现折线图(Sales)绑定右侧Y轴,需完成两个核心配置步骤:


1. 显式定义双Y轴

在图表的options.scales中配置两个Y轴,分别指定位置和唯一ID,区分左右侧:

  • 左侧Y轴绑定柱状图(Visitor)
  • 右侧Y轴绑定折线图(Sales)

2. 给数据集指定对应Y轴ID

在折线图的数据集配置里,通过yAxisID字段关联右侧Y轴的ID。


修改后的完整代码示例

const ctx = document.getElementById('combinedChart').getContext('2d');
const combinedChart = new Chart(ctx, {
    type: 'bar', // 主图表类型为柱状图,折线图在数据集里指定类型
    data: {
        labels: ['Jan', 'Feb', 'Mar', 'Apr', 'May', 'Jun'],
        datasets: [
            // 柱状图:访客数据(绑定左侧Y轴)
            {
                label: 'Visitors',
                data: [1500, 2200, 3100, 4500, 3800, 2900],
                backgroundColor: 'rgba(75, 192, 192, 0.6)',
                borderColor: 'rgba(75, 192, 192, 1)',
                borderWidth: 1,
                yAxisID: 'y-left'
            },
            // 折线图:销售数据(绑定右侧Y轴)
            {
                label: 'Sales',
                data: [180, 250, 320, 480, 410, 330],
                type: 'line', // 显式指定为折线图
                backgroundColor: 'rgba(255, 99, 132, 0.2)',
                borderColor: 'rgba(255, 99, 132, 1)',
                borderWidth: 2,
                fill: false,
                yAxisID: 'y-right' // 关键:绑定到右侧Y轴
            }
        ]
    },
    options: {
        scales: {
            // 左侧Y轴配置
            'y-left': {
                beginAtZero: true,
                title: {
                    display: true,
                    text: 'Visitor Count'
                },
                grid: {
                    color: 'rgba(0, 0, 0, 0.05)'
                }
            },
            // 右侧Y轴配置
            'y-right': {
                beginAtZero: true,
                position: 'right', // 设置为右侧轴
                title: {
                    display: true,
                    text: 'Sales Amount'
                },
                grid: {
                    drawOnChartArea: false // 隐藏右侧轴网格线,避免与左侧重叠
                }
            },
            // X轴配置
            x: {
                title: {
                    display: true,
                    text: 'Months'
                }
            }
        }
    }
});

关键配置说明

  • 右侧Y轴必须设置position: 'right',才能显示在图表右侧
  • 折线图数据集的yAxisID必须与右侧Y轴的ID完全匹配(示例中为y-right)
  • 关闭右侧轴的grid.drawOnChartArea是可选优化,能让图表更清晰,避免网格线重复

按照上述配置修改后,折线图的数值将映射到右侧Y轴,实现你期望的组合图效果。

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.07.18 19:22:58