get yLabel value onclick chart js

元气小坏坏 提交于 2021-02-07 08:30:07

问题


I want to have the y label value, when I click on the bar.

Like the above example, when I click on feb blue bar I want to have label value, which is 40

I looked for examples on stackOverFlow and other sites but they only have example of label for the legend show up.

some of the code I tried

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

回答1:


This demo gives the value in the bar chart when you click on it. I'm not a chart.js expert so there may be better solutions.

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);
    };


来源:https://stackoverflow.com/questions/50515985/get-ylabel-value-onclick-chart-js

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!