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

Chart.js水平条形图:如何获取每个条形的Y轴位置?

解决Chart.js水平条形图中获取条形正确Y轴位置的问题

你当前的问题在于直接用Y轴刻度位置定位条形,但分组水平条形的实际位置会因数据集分组产生偏移,并非与刻度位置完全重合。正确做法是直接获取Chart.js内部维护的条形元素位置信息,而非通过刻度计算。

具体修改方案

在circles插件中替换ypos的获取逻辑:通过chart.getDatasetMeta(datasetIndex).data[index]获取对应条形的实例,该实例包含y(条形中心Y坐标)、top(条形顶部Y坐标)、bottom(条形底部Y坐标)等属性,直接使用这些属性即可得到准确位置。

修改后的完整代码

const data ={
  labels:[
    "Macht",
    "Ehre",
    "Besitz",
    [
      "Selbst-",
      "verwirklichung"
    ],
    "Wettbewerb",
    "Dienen",
    "Spiritualität"
  ],
  "datasets": [
    {
      "label": "first",
      "backgroundColor": "rgb(208,55,25)",
      "data": [4,8,5,4,1,1,3]
    },
    {
      "label": "second",
      "backgroundColor": "rgb(240,223,89)",
      "data": [1,4,5,2,5,3,3]
    }
  ]
}

const circles = {
  id: 'circles',
  afterDraw(chart, args, options) {
    const {ctx, scales:{x}} = chart;
    // 遍历插件数据集时同时获取数据集索引
    options.data.forEach((dataset, datasetIndex) => {
      dataset.data.forEach((value, index) => {
        // 获取对应条形的实例
        const bar = chart.getDatasetMeta(datasetIndex).data[index];
        // 使用条形的中心Y坐标
        const xpos = x.getPixelForValue(value);
        const ypos = bar.y; 

        ctx.save();
        ctx.fillStyle = dataset.backgroundColor;
        ctx.beginPath();
        ctx.arc(xpos, ypos, 10, 0, 2 * Math.PI);
        ctx.fill();
        ctx.stroke();
        ctx.restore();
      })
    })
  }
}

const chartOptions = {
  maintainAspectRatio: false,
  responsive:true,
  indexAxis: 'y',
  scales: {
    x:{
      min: 1,
      max: 9,
    },
    y:{
      ticks: {
        stepSize: 1,
        autoSkip: false,
      },
      min: 0,
      max: 6,
      position: 'left',
    },
  },
  plugins: {
    circles: {
      data: [
        {
          "label": "Selbseinschätzung",
          "backgroundColor": "rgb(208,55,25)",
          "data": [6,4,3,7,4,4,7]
        },
        {
          "label": "Selbseinschätzung",
          "backgroundColor": "rgb(240,223,89)",
          "data": [7,4,4,3,6,5,2]
        }
      ]
    }
  }
}

const ctx = document.getElementById('mts').getContext('2d');
const myChart = new Chart(ctx, {
    type: 'bar',
    data: data,
    options: chartOptions,
    plugins: [circles]
});

关键说明

  1. chart.getDatasetMeta(datasetIndex):获取对应数据集的元数据,包含该数据集所有条形的渲染信息。
  2. bar.y:直接返回条形的中心Y坐标,完全匹配条形实际位置,无需手动计算偏移。
  3. 若需要条形顶部或底部位置,可直接使用bar.top或bar.bottom属性。

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.08.17 13:20:28