Chart.js: Dynamic Changing of Chart Type (Line to

2020-03-01 10:14发布

I am trying to hot swap chart types based on select box changes. If data needs to be updated, it changes.

So for example, on page load I create a chart like this:

var config = {
     type: 'line',
     data: {
        labels: this.labels,
        datasets: [{
            label: 'Some Label',
            data: this.values
        }]
     },
     options: {
         responsive: true
     }
}
var context = document.getElementById('canvas').getContext('2d');
window.mychart = new Chart(context, config);

But then I change the combo box to a bar chart. I have tested the data with bar chart on page load, and it worked great.

Here's how I am trying to change the chart.

window.mychart.destroy();

// chartType = 'bar'
config.type = chartType;

var context = document.getElementById('canvas').getContext('2d');
window.mychart = new Chart(context, config);

window.mychart.update();
window.mychart.render();

But nothing happens. The line chart remains. How can I dynamically change the chart type? (Even if it means destroying & re-creating the chart canvas).

UPDATE

Note it looks like it is actually destroying the chart, but keeps redrawing a line chart, even though I do console.log(config.type); and it returns bar, not line

3条回答
别忘想泡老子
2楼-- · 2020-03-01 10:55

The Fix

  • Destroy the old chart (to remove event listeners and clear the canvas)
  • Make a deep copy of the config object
  • Change the type of the copy
  • Pass the copy instead of the original object.

Here is a working jsfiddle example

Example Overview:

var temp = jQuery.extend(true, {}, config);
temp.type = 'bar'; // The new chart type
myChart = new Chart(ctx, temp);

NOTE: Using version 2.0.1 of Chart.js

Why this works

Chart.js modifies the config object you pass in. Because of that you can not just change 'config.type'. You could go into the modified object and change everything to the type you want, but it is much easier to just save the original config object.

查看更多
疯言疯语
3楼-- · 2020-03-01 11:01

Just to follow up that this is now fixed in v.2.1.3, as followed through by https://stackoverflow.com/users/239375/nathan

document.getElementById('changeToLine').onclick = function() {
  myChart.destroy();
  myChart = new Chart(ctx, {
    type: 'line',
    data: chartData
  });
};

Confirmed fixed in latest version. Check out http://codepen.io/anon/pen/ezJGPB and press the button under the chart to change it from a bar to a line chart.

查看更多
我欲成王,谁敢阻挡
4楼-- · 2020-03-01 11:06

The alternate solution can be as simple as creating both the charts in separate Div elements. Then as per your condition just make one visible and hide other in the javascript. This should serve the purpose you may have for changing the chart type for your requirement.

查看更多
登录 后发表回答