get yLabel value onclick chart js

wwwo4jvm  于 12个月前  发布在  Chart.js
关注(0)|答案(4)|浏览(87)

我想有y标签值,当我点击酒吧。


的数据
像上面的例子,当我点击二月蓝条,我想有标签值,这是40
我在stackOverFlow和其他网站上寻找示例,但他们只有图例的标签示例。
我试过的一些代码

onClick: function(evt, element) {
      var activePoints = bar_chart.getElementAtEvent(evt);
      console.log(activePoints[0]._model.datasetLabel);
}

字符串

neskvpey

neskvpey1#

这个演示在你点击它的时候给出了条形图中的值。我不是chart.jsMaven,所以可能有更好的解决方案。
https://codepen.io/newschapmj1/pen/PerOzM

/* from https://github.com/chartjs/Chart.js/issues/2292 */
document.getElementById("myChart").onclick = function (evt) {
        var activePoints = myChart.getElementsAtEventForMode(evt, 'point', myChart.options);
        var firstPoint = activePoints[0];
        var label = myChart.data.labels[firstPoint._index];
        var value = myChart.data.datasets[firstPoint._datasetIndex].data[firstPoint._index];
        alert(label + ": " + value);
    };

字符串

ckocjqey

ckocjqey2#

Chart.js版本= 3.2.1
关于official documentation

onClick: (evt) => {
    const points = myChart.getElementsAtEventForMode(evt, 'nearest', { intersect: true }, true);

    if (points.length) {
        const firstPoint = points[0];
        var label = myChart.data.labels[firstPoint.index];
        var value = myChart.data.datasets[firstPoint.datasetIndex].data[firstPoint.index];
        alert(label +" : "+ value);
    }
}

字符串

djmepvbi

djmepvbi3#

我需要一种从回调函数中获取图表的方法,因为我对多个图表使用相同的回调函数,所以我不能只说myChart
这可以工作,传递给图表选项-第二个参数称为“activeElements”,可用于获取图表:

onClick: (event, activeElements) => {
    if(activeElements.length === 0){
      alert("Chart is clickable but you must click a data point to drill-down")
    }
    const chart = activeElements[0]._chart
    const activePoints = chart.getElementsAtEventForMode(event, 'point', chart.options);
    const firstPoint = activePoints[0];
    const label = chart.data.labels[firstPoint._index];
    const value = chart.data.datasets[firstPoint._datasetIndex].data[firstPoint._index];
    alert(label + ": " + value);
}

字符串

l7mqbcuq

l7mqbcuq4#

混合mikeb和Mrunalraj Redij答案。添加Hover并使用'index'和'intersect:false'来选择值,即使鼠标指针不在行上。

chartClickHoverCB(event, activeElements, chart) {
      const points = chart.getElementsAtEventForMode(event, 'index', { intersect: false }, true);

      if (points.length) {
          const firstPoint = points[0];
          var label = chart.data.labels[firstPoint.index];
          var value = chart.data.datasets[firstPoint.datasetIndex].data[firstPoint.index];
          console.log(label +" : "+ value);
      }
  }

chartOptions: ChartOptions = {
    ....
    onClick: this.chartClickHoverCB,
    onHover: this.chartClickHoverCB,
  };

字符串

相关问题