Tips on multiple charts in chart.js showing incorrect values

I use the latest Chart.bundle.js to create multiple stacked charts on one page. For example, I have 3 diagrams with 2 data sets. The graphs are correct, but the prompts on each of the diagrams are always the same and show incorrect values. link to the screenshot . All values ​​are zero, which is obviously incorrect.

Tooltip mode - index, the canvas for each chart has a different identifier, the data set variables are all different.

0
source share
2 answers

Trying to publish my code on jsfiddle, I managed to find a solution to this very strange problem. I had

var barCharData = { labels: ["2", "3", "4"], datasets: [] }; 

therefore, in the beginning there is no data in any of my diagrams (before receiving data from the database). For each graph, I did something like this:

  for(var i=1; i <= number_of_charts; i++){ bar_char_data_array.push(barChartData); var myBar = new Chart(ctx, { type: 'bar', data: bar_char_data_array[i-1], options: { tooltips: { mode: 'label', intersect: true } } }); } 

It turned out that javascript considers each element of the array "bar_char_data_array" as the same object and changes the data for one of the diagrams, which leads to a change in the data for the rest. I still don’t know why all the diagrams were correct until I hovered to see a hint. However, the solution to my problem was to remove the barChartData variable.

  for(var i=1; i <= number_of_charts; i++){ bar_char_data_array.push({ labels: ["2", "3", "4"], datasets: [] }); var myBar = new Chart(ctx, { type: 'bar', data: bar_char_data_array[i-1], options: { tooltips: { mode: 'label', intersect: true } } }); } 
0
source

My solution was somewhat similar to @ queen-juliet's answer.

I had a shared configuration variable with adding and updating a data key in a loop. Despite the fact that several chart.js objects that I had on the page displayed the correct data, tooltips were shown on only one (random) chart. The solution was to declare and populate the entire configuration inside my loop.

0
source

Source: https://habr.com/ru/post/972585/


All Articles