Chartjs-Dataset legend color is not updating after changing background color of dataset and update (chartJs framework)

0đź‘Ť

âś…

First, for next time, you need to add a shortcode snippet of your code => Not Github with 2 long files & complex data – this is not a freelancer mission but Q 🙂. Also in the future, you may delete this GitHub project and this Q will be meaningful.

.
https://stackoverflow.com/help/how-to-ask

update()

It’s pretty common to want to update charts after they’ve been
created. When the chart data or options are changed, Chart.js will
animate to the new data values and options.
https://www.chartjs.org/docs/latest/developers/updates.html?h=update

Official Scriptable example (change colors & data by click):
https://www.chartjs.org/samples/latest/scriptable/bar.html

or her (under the scriptable title): https://www.chartjs.org/samples/latest/

myHorizontalBar is your chart object so remove window. (Syntax error – check console errors).

window.myHorizontalBar.update(); /* wrong syntax remove "window." */

“hello world” example

/* data */
var data = {
  labels: ["Africa", "Asia", "Europe", "America"],
  datasets: [{
    /* data */
    label: "Data label",
    backgroundColor: ["red", "#8e5ea2","#3cba9f", '#1d49b8'],
    data: [5.0,6.7,7.5, 8.6, 3.3, 4.4, 4.5]
  }]
};

var options = {
  responsive: true,
  title: {
    text: 'Hello',
    display: true
  },
  scales: {
    xAxes: [{
      stacked: false,
      ticks: {

      },
    }],
    yAxes: [{
      stacked: true,
      ticks: {

      }
    }]
  }
};

var myChart = new Chart(document.getElementById("chart"), {
  type: 'bar',
  data: data,
  options: options
});

document.getElementById('submitChange').addEventListener('click', function() {
  myChart.data.datasets[0].backgroundColor[0] = "green";
  myChart.update();
});
<button id="submitChange">Change Africa color to Green</button>
<canvas id="chart"></canvas>

<script src="https://cdnjs.cloudflare.com/ajax/libs/Chart.js/2.9.3/Chart.min.js"></script>

Leave a comment