How to get date label of line Chart?
Asked Answered
U

2

8

I use line of Chart.js( Version: 2.7.2 ) in my application and I open dialog when clicking on some element and I need to get label(date on xAxes) of the current element. Googling I found examples and trying to make as next :

        var lineCanvas = document.getElementById("canvasVotesByDays");
        var ctx = lineCanvas.getContext('2d');

        var lineChart = new Chart(ctx, {
            type: 'line',
            data: {
                labels: monthsXCoordItems,
                datasets: [
                    {
                        label: 'Correct Votes',
                ...

        lineCanvas.onclick = function (e) {
            console.log("INSIDE lineChart::")
            console.log(lineChart)

            var slice = lineChart.getPointsAtEvent(e);
            ...

But on the last line I got error :

Uncaught TypeError: lineChart.getPointsAtEvent is not a function
    at HTMLCanvasElement.lineCanvas.onclick 

In the console I see the propeerties of the lineChart object: https://i.sstatic.net/q8zuJ.jpg

Why error and how to get label property?

Thank you!

Utilize answered 4/10, 2018 at 6:37 Comment(1)
What is your element exactly?Mediant
A
2

According to the documentation the proper method seems to be either getElementAtEvent or getElementsAtEvent:

function clickHandler(evt) {
    var firstPoint = myChart.getElementAtEvent(evt)[0];

    if (firstPoint) {
        var label = myChart.data.labels[firstPoint._index];
        var value = myChart.data.datasets[firstPoint._datasetIndex].data[firstPoint._index];
    }
}
Appealing answered 6/10, 2018 at 8:51 Comment(2)
Could you, please, to look at this example(based on 2.7.2) jsfiddle.net/e8n4xd4z/19925 ? I got undefined variables of firstPoint and errors later...Utilize
Do not forget that getElementAtEvent returns an array - in your fiddle you are getting the array but then using the variable as if it was the first element of the array while it is still the whole array. Also, keep in mind that even though the area between the spline and the X-axe is painted in color - it is not part of the Chart.js element. The elements (at least for your case) are the dots on the spline - if you click outside a dot then you will get undefined from getElementAtEventAppealing
C
4

Ivan I have used your jsfidlle: jsfiddle.net/e8n4xd4z/19925 in it you have done console.log for all variable,
so i have seen that you are using Array as object, see here

var firstPoint = lineChart.getElementAtEvent(e)

linechart returning array with index 0, but you are directly accesing the property, you are using firstPoint._index, but really the property exist at one more level deep means it is at firstPoint[0]._index.

i have also forked your jsfiddle here is my jsfiddle, or i have also implemented your example in inbuilt snippet of stackoverflow see below the working example:

var options = {
  type: 'line',
  data: {
    labels: ["Red", "Blue", "Yellow", "Green", "Purple", "Orange"],
    datasets: [
	    {
	      label: '# of Votes',
	      data: [12, 19, 3, 5, 2, 3],
      	      borderWidth: 1
    	    },	
	    {
              label: '# of Points',
	      data: [7, 11, 5, 8, 3, 7],
	      borderWidth: 1
	    }
	  ]
  },
  options: {
  	scales: {
    	yAxes: [{
          ticks: { 
                    reverse: false
          }
        }]
     }
  } 
};

var lineCanvas = document.getElementById("chartJSContainer");
       
var ctx = lineCanvas.getContext('2d');
var lineChart = new Chart(ctx, options);

lineCanvas.onclick = function (e) {


   var firstPoint  = lineChart.getElementAtEvent(e)[0];
   if (firstPoint) {
     var first_point_index= firstPoint._index
     console.log("+1 first_point_index::")
     console.log( first_point_index )

     var firstPoint_dataset_index= firstPoint._datasetIndex
     console.log("+2 first_point_index::")
     console.log( first_point_index )
     
     var label = lineChart.data.labels[firstPoint._index];
     console.log("+3 label::")
     console.log( label )
     
     var value = lineChart.data.datasets[firstPoint._datasetIndex].data[firstPoint._index];
     alert( "label::"+(label) + "  value::"+(value) )
   }
}
canvas { 
  background-color : #eee;
}
<html>
 <head>   
   <script src="https://cdnjs.cloudflare.com/ajax/libs/Chart.js/2.7.2/Chart.min.js"></script>
 </head>
<body>
    <canvas id="chartJSContainer" width="600" height="400"></canvas>
</body>
 </html>
Cucumber answered 8/10, 2018 at 6:47 Comment(6)
In the fiddle example line Chart.getElementAtEvent(e)[0]; returns undefined. I tried to my app it also returns undefined. Which is valid decision ?Utilize
@Ivan please see in this fiddle (jsfiddle.net/e8n4xd4z/19925 ) you have written var firstPoint = lineChart.getElementAtEvent(e); instead of var firstPoint = lineChart.getElementAtEvent(e)[0];Cucumber
I fixed at var firstPoint = lineChart.getElementAtEvent(e)[0]; and get that firstPoint is undefined. Please, look at jsfiddle.net/e8n4xd4z/19938.Utilize
i have opened your new fiddle in my pc it is working fine, i think you have to hard refresh the page or you have to try empty cache and reload , shortcut ctrl+f5 or ctrl+shift+R or if you are using Mac then apply command+f5 to hard refresh.Cucumber
@Ivan I think you can run this demo in your local environment to test it.Cucumber
@Ivan May be you are clicking anywhere in graph, please click on circular dots on line which also display label when you hover on it like (Blue # votes : 19), then you will get the label and value on alert box.Cucumber
A
2

According to the documentation the proper method seems to be either getElementAtEvent or getElementsAtEvent:

function clickHandler(evt) {
    var firstPoint = myChart.getElementAtEvent(evt)[0];

    if (firstPoint) {
        var label = myChart.data.labels[firstPoint._index];
        var value = myChart.data.datasets[firstPoint._datasetIndex].data[firstPoint._index];
    }
}
Appealing answered 6/10, 2018 at 8:51 Comment(2)
Could you, please, to look at this example(based on 2.7.2) jsfiddle.net/e8n4xd4z/19925 ? I got undefined variables of firstPoint and errors later...Utilize
Do not forget that getElementAtEvent returns an array - in your fiddle you are getting the array but then using the variable as if it was the first element of the array while it is still the whole array. Also, keep in mind that even though the area between the spline and the X-axe is painted in color - it is not part of the Chart.js element. The elements (at least for your case) are the dots on the spline - if you click outside a dot then you will get undefined from getElementAtEventAppealing

© 2022 - 2024 — McMap. All rights reserved.