Nathan
Nathan

Reputation: 2970

Chart.js: Dynamic Changing of Chart Type (Line to Bar as Example)

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

Upvotes: 17

Views: 35146

Answers (8)

Donzaala
Donzaala

Reputation: 123

Its 2024 and I am working on a Legacy Project so I am using Chart.js v2.7.2. If you are starting a new project use the current version. This is what worked for me

//in my adjax beforesend function
beforeSend: function(){
    helper.btnLoading(btn);
    //remove the canvas element entirely
    $("#chartResultWrapper").remove();
},

//in my adjax success function
success: function(response){
  let data = response.result;
  
  //add the canvas element to the dom with your targetted ID
  $("#resultsBody").prepend('<canvas id="chartResultWrapper"></canvas>');

  createChart(response.result, type);
},
<div class="card-body" id="resultsBody">
        <canvas id="chartResultWrapper"></canvas>
        <div class="mt-4" id="mainResult">
      <small class="text-muted">No data available</small>
    </div>
</div>

The rest of your code should remain same. Hopes it works for your case

Upvotes: 0

reinerCode
reinerCode

Reputation: 401

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

Upvotes: 6

mm_
mm_

Reputation: 1735

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();

Upvotes: 0

brodrigs
brodrigs

Reputation: 344

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();
}

Upvotes: 3

Rushow Khan
Rushow Khan

Reputation: 105

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();

Upvotes: 1

Douglas Timms
Douglas Timms

Reputation: 694

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.

Upvotes: 8

L Bahr
L Bahr

Reputation: 2901

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.

Upvotes: 24

Aman Sharma
Aman Sharma

Reputation: 1990

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.

Upvotes: 1

Related Questions