[Chartjs]-Chart.js: Dynamic Changing of Chart Type (Line to Bar as Example)

23👍

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.

8👍

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.

6👍

In chart.js 3.8.0 you can do it like this:


let chart = new Chart(ctx, {
  type: "line",
  data: {
    // ...
  },
  options: {
    // ...
  }
});

chart.config.type = "bar";
chart.update();

you can also change data and options this way

chart.js docs on updating:
https://www.chartjs.org/docs/latest/developers/updates.html

codepen example: https://codepen.io/3zbumban/pen/yLKMMJx

3👍

No need to destroy and re-create, you just have to change the type from the chart’s config variable then update the chart.

var chartCfg = {
    type: 'pie',
    data: data
};

var myChart = new Chart(ctx, chartCfg );

function changeToBar() {
    chartCfg.type = "bar";
    myChart.update();
}

1👍

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.

1👍

In ChartJS, the chart type can also be changed easily like chart data. Following example might be helpful

        my_chart.type = 'bar';
        my_chart.update();

0👍

In ChartJS 3, :

var options = // your options.
var data = { ...myChart.data }; // deep copy of the data
var ctx = document.getElementById('myChart_id').getContext('2d');

myChart.destroy()

/// Modify ctx or data if you need to.

myChart = new Chart(ctx, {
        type: chart_type,
        data: data
});

Chart.options = options;
myChart.update();

Leave a comment