[Chartjs]-Switching between Charts with chart.js using Buttons

1👍

regarding to this documentation

https://www.chartjs.org/docs/latest/developers/updates.html

this is what I have done, just when click happens, set the datasets then update the chart at the end

<canvas id="myChart"></canvas>
<canvas id="forecast" width="300" height="150"></canvas>
<button id="0" type="button">Overall (Monthly)</button>
<button id="1" type="button">Overall (Cumulative)</button>

<!-- Add jQuery lib here -->
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/Chart.js/2.7.3/Chart.min.js"></script>
<script>
    const ctx = document.getElementById('myChart').getContext('2d');
    const chart = new Chart(ctx, {
        type: 'bar',
        data: {
            labels: ['July', 'August', 'September', 'October', 'November', 'December', 'January', 'February', 'March', 'April', 'May', 'June'],
            datasets: [{
                label: "DataPoint1",
                data: [1635063, 1324343, 1880284, 1609026, 1243755, 1680117],

            }, {
                label: "DataPoint2",
                data: [962615, 1007211, 949080, 1109982, 902847, 1059045, 1191732, 1364279, 1244704, 1392971, 1352530, 1450456],
                borderDash: [10, 5],
                type: 'line'
            }, {
                label: "DataPoint3",
                backgroundColor: 'rgba(255, 255, 255, 0.9)',
                borderColor: 'rgba(191, 63, 63, 0.9)',
                data: [1596798, 1468975, 1528036, 1612536, 1356639, 1512534, 1557276, 1609376, 1522568, 1387752, 1463280, 1562757],
                borderDash: [10, 5],
                type: 'line'
            }],

        },
    });

    // using jQuery with es5 syntax
    $('#0').on('click', function (e) {
        e.preventDefault;
        chart.config.data = {
            labels: ['June', 'December', 'September', 'October', 'November', 'December', 'January', 'February', 'March', 'April', 'May', 'June'],
            datasets: [{
                label: "DataPoint1",
                data: [1680117, 1324343, 1324343, 1609026, 1243755, 1609026],

            }, {
                label: "DataPoint2",
                data: [1609376, 1007211, 949080, 1109982, 1528036, 1059045, 1191732, 1059045, 1244704, 1392971, 1352530, 1450456],
                borderDash: [10, 5],
                type: 'line'
            }, {
                label: "DataPoint3",
                backgroundColor: 'rgba(255, 255, 255, 0.9)',
                borderColor: 'rgba(191, 63, 63, 0.9)',
                data: [1596798, 1356639, 1528036, 1609026, 1609376, 949080, 1557276, 1609376, 1522568, 1387752, 1463280, 1562757],
                borderDash: [10, 5],
                type: 'line'
            }],
        }
        chart.update();
    });

    // using pure js but with es6 syntax
    document.getElementById("1").addEventListener('click', () => {
        chart.config.data = {
            labels: ['June', 'December', 'September', 'October', 'November', 'December', 'January', 'February', 'March', 'April', 'May', 'June'],
            datasets: [{
                label: "DataPoint1",
                data: [1680117, 1324343, 1324343, 1609026, 1243755, 1609026],

            }, {
                label: "DataPoint2",
                data: [949080, 1007211, 949080, 1109982, 902847, 1059045, 1191732, 1059045, 1244704, 1392971, 1352530, 1450456],
                borderDash: [10, 5],
                type: 'line'
            }, {
                label: "DataPoint3",
                backgroundColor: 'rgba(255, 255, 255, 0.9)',
                borderColor: 'rgba(191, 63, 63, 0.9)',
                data: [1596798, 1356639, 1528036, 1612536, 1609376, 1512534, 1557276, 1609376, 1522568, 1387752, 1463280, 1562757],
                borderDash: [10, 5],
                type: 'line'
            }],
        }
        chart.update();
    });
</script>

now load the page then click on the Overall (Monthly) button

Hope this helps

P.S. I am just setting new values to all three charts. If you are thinking of having one chart at a time. Just replace the data with one each time there is a click

2👍

What you’ll want to do is supply the Chart with only the data you want the Chart to display at one time. So, if you have a couple of different views you want to toggle between, create the data for those views as separate external objects that you feed to the Chart. All destroy does is let you destroy some previous instantiation of Chart, so that you can always be sure you’re only creating one Chart.

<canvas id="myChart"></canvas>
<canvas id="forecast" width="300" height="150"></canvas>
<button id="0" type="button" >Overall (Monthly)</button>
<button id="1" type="button" >Overall (Cumulative)</button>

<script>
// gather the monthly dataset
const monthlyData = {
    labels: ['July', 'August', 'September', 'October', 'November', 'December', 'January', 'February', 'March', 'April', 'May', 'June'],
    datasets: [{
    label: "DataPoint1",       
    data: [1635063, 1324343, 1880284, 1609026, 1243755, 1680117],

  }, {
    label: "DataPoint2",            
    data: [962615, 1007211, 949080, 1109982, 902847, 1059045, 1191732, 1364279, 1244704, 1392971, 1352530, 1450456],
    borderDash: [10,5],           
    type: 'line'
  }, {
    label: "DataPoint3",
    backgroundColor: 'rgba(255, 255, 255, 0.9)',
    borderColor: 'rgba(191, 63, 63, 0.9)',
    data: [1596798, 1468975, 1528036, 1612536, 1356639, 1512534, 1557276, 1609376, 1522568, 1387752, 1463280, 1562757],
    borderDash: [10,5],
    type: 'line'
  }]
}

// gather the cumulative dataset
const cumulativeData = {
    ...
}

// define the default configuration
const defaultConfig = {
    type: 'bar',
    data: monthlyData;
    options: options
}

// create the chart with the default configuration
var ctx = document.getElementById('myChart').getContext('2d');
var chart = new Chart(ctx, defaultConfig);

// add event listeners for the buttons
document.getElementById("0").addEventListener('click', () => {
  const chart = document.getElementById("myChart");
  chart.config.format = { monthly format };
  chart.data = monthlyData;
  chart.options = { monthly options };
  chart.update();
}

document.getElementById("1").addEventListener('click', () => {
  const chart = document.getElementById("myChart");
  chart.config.format = { cumulative format };
  chart.data= cumulativeData;
  chart.options = { cumulative options };
  chart.update();
}

</script>

All you need to do is add an event listener on a button (listening for a ‘click’ event), and then add a callback function to that listener to update the chart object using ‘=’ and then run chart.update().

Let me know if this helps!

EDIT: Even though there was another answer in JQuery, I included this one in vanilla Javascript because you may not be using JQuery. That user also included this documentation, which is very helpful: https://www.chartjs.org/docs/latest/developers/updates.html

1👍

Thank you so much to the top answer, it worked for me as well.

I have a few buttons that change the chart view, so the way to have unlimited change views would be to define the chart Element like so:

document.getElementById('graph').innerHTML = chart.generateLegend();

then have your Jquery button callbacks edit the entire config, labels included like so:

chart.config.data = {
    labels: myLabels,
    datasets: [{
      myDataSet
    }]
  };

then finally update! (still inside the button call)

    salesChart.update();

full example with my the variables I’m using in my project:

var salesChart = new Chart(salesChartCanvas, {
    type: 'line',
    data: areaData,
    options: areaOptions
  });

  document.getElementById('sales-statistics-legend').innerHTML = salesChart.generateLegend();
  $("#sales-statistics_switch_1").click(function () {
    salesChart.config.data = {
    labels: myData,
    datasets: [{
      data: myData,
      borderColor: infoColor,
      backgroundColor: gradientStrokeFill_1,
      borderWidth: 2
    }]
  };
    salesChart.update();
  });
  $("#sales-statistics_switch_2").click(function () {
    salesChart.config.data = {
    labels: myData4,
    datasets: [{
      data: myData4,
      borderColor: infoColor,
      backgroundColor: gradientStrokeFill_1,
      borderWidth: 2
    }]
  };
    salesChart.update();
  });

Leave a comment