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

双Y轴配置异常求助:数据集与指定Y轴关联失效

双Y轴配置异常排查及解决方法

问题现象

配置双Y轴时出现以下异常:

  • id为'y1'的Y轴显示在左侧(预期应在右侧)
  • 绑定'y'轴的datasets[0]数据集错误关联到'y1'轴,轴绑定属性未正确匹配对应坐标轴

异常代码

const data = {
  labels: ['a', 'b', 'c', 'd', 'e'],
  datasets: [
    {
      type: 'bar',
      label: this.$t('numberOfBuilding'),
      data: [100, 20, 30, 5, 5],
      backgroundColor: [
        'rgba(255, 99, 132, 0.2)',
        'rgba(255, 159, 64, 0.2)',
        'rgba(255, 205, 86, 0.2)',
        'rgba(75, 192, 192, 0.2)',
        'rgba(54, 162, 235, 0.2)'
      ],
      borderColor: ['rgb(255, 99, 132)', 'rgb(255, 159, 64)', 'rgb(255, 205, 86)', 'rgb(75, 192, 192)', 'rgb(54, 162, 235)'],
      borderWidth: 1,
      yAxisId: 'y'
    },
    {
      type: 'line',
      fill: true,
      label: this.$t('output') + '(' + this.$t('sum') + ')', 
      data: [300, 100, 700, 249, 588],
      borderColor: 'rgba(55, 201, 14, 1)',
      backgroundColor: 'rgba(55, 201, 14, 0.5)',
      lineTension: 0.2,
      yAxisId: 'y1'
    }
  ]
}
const config = {
  type: 'scatter',
  data: data,
  options: {
    scales: {
      y: {
        beginAtZero: true,
        position: 'left'
      },
      y1: {
        position: 'right',
        grid: {
          drawOnChartArea: false
        }
      }
    }
  }
}

正常参考代码

const data = {
  labels: [
    1 + this.$t('month'),
    2 + this.$t('month'),
    3 + this.$t('month'),
    4 + this.$t('month'),
    5 + this.$t('month'),
    6 + this.$t('month'),
    7 + this.$t('month'),
    8 + this.$t('month'),
    9 + this.$t('month'),
    10 + this.$t('month'),
    11 + this.$t('month'),
    12 + this.$t('month')
  ],
  datasets: [
    {
      type: 'bar',
      label: this.$t('totalConsumption') + '(' + this.unit + ')',
      data: this.consumptionData,
      borderColor: 'rgb(255, 99, 132)',
      backgroundColor: 'rgba(255, 99, 132, 0.2)',
      yAxisID: 'y'
    },
    {
      type: 'line',
      label: this.$t('temperatureAVG') + '(℃)',
      data: this.temperatureData,
      fill: false,
      borderColor: 'rgb(54, 162, 235)',
      yAxisID: 'y1'
    }
  ]
}
const config = {
  type: 'scatter',
  data: data,
  options: {
    maintainAspectRatio: false,
    scales: {
      y: {
        beginAtZero: true,
        position: 'left'
      },
      y1: {
        position: 'right',
        grid: {
          drawOnChartArea: false
        }
      }
    }
  }
}

问题原因

两段代码的核心差异在于数据集绑定Y轴的属性名:

  • 异常代码使用yAxisId(最后一个字母为小写d)
  • 正常代码使用yAxisID(最后一个字母为大写D)

Chart.js的API规范中,绑定Y轴的属性名是**yAxisID**(驼峰命名,最后一个D大写)。使用小写的yAxisId会被识别为无效属性,导致Chart.js无法正确匹配坐标轴,进而出现轴位置错误、数据集关联错误的问题。

解决方法

将异常代码中所有数据集的yAxisId修改为yAxisID即可:

// 修改后的数据集中的属性
yAxisID: 'y'
// 和
yAxisID: 'y1'

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.08.01 15:55:17