0
votes

In my project I have I have ten graphs in a table with each graph showing two datasets. I want to toggle the visibility of each dataset by clicking it which is default behaviour in ChartJS.

All the charts are held in an array and following the built in toggle method of ChartJS, every chart is updated to the dataset of the first chart. So to be clear, when the page loads, each chart is shown correctly, but if I made the dataset invisible and visible again, it becomes visible but with the wrong data.

I tried writing my own update function to toggle the visibility.

 var option = {

        legend: {
            onClick: ToggleDatasetVisibility,
        }}

and then

function ToggleDatasetVisibility() {

   this.chart.getDatasetMeta(1).hidden = !this.chart.getDatasetMeta(1).hidden;
    //  this.chart.update();
}

However exactly the same thing happens. After the update,

*Note, I'm only toggling the second dataset of each DatasetMeta so that's why the 1 is hardcoded in this example. That's not the chart in question.

In case it's useful, we is the code when the charts are primed with data when the page loads and here the update shows the correct data.

    for (var i = 0; i < 10; i++) {

        var MyArray= await fetch("http://localhost:1234/Demo/FetchResults?model_id=" + i);


        //Add the recorded tunnel data to dataset 0
        LineChartArray[i].data.datasets[0].data = ResultsArray;
        LineChartArray[i].data.datasets[0].label = '';
        LineChartArray[i].data.datasets[1].data = MyArray;
        LineChartArray[i].data.datasets[1].label = 'LabelXYZ';


        LineChartArray[i].update(); //This update updates the graph with the correct data.

    }
}
1

1 Answers

0
votes

So, I don't know if there's a bug with chart JS or a correct determine which chart to update but I discovered that the render method works. This updates the chart following the visibility toggle loads the correct data back in when made visible. I thought it might be my use of the 'this' command but it works fine with the render method.

I just updated the toggle function like so,

function ToggleDatasetVisibility() {

   this.chart.getDatasetMeta(1).hidden = !this.chart.getDatasetMeta(1).hidden;
   this.chart.render();

}