[Chartjs]-JavaScript after dynamically updating ChartJS

1👍

The main problem in your updateChart function is the following line.

chart.data.labels.push(labels);

This adds an array of labels to the existing chart.data.labels array. You should assign the new labels to chart.data.labels instead.

chart.data.labels = labels;

There were a few other minor problems that needed to be fixed. Please have a look at your amended code below.

function setEmptyChart() {
  let emptyChart = new Chart('myChart', {
    type: 'bar',
    data: {
      labels: [],
      datasets: [],
    },
    options: {
      scales: {
        yAxes: [{
          ticks: {
            beginAtZero: true
          }
        }]
      },
      legend: {
        display: true,
        position: 'right'
      },
      title: {
        display: true,
        text: 'Empty Chart'
      },
      layout: {
        padding: {
          left: 10,
          right: 0,
          top: 50,
          bottom: 0
        }
      }
    }
  });
  return emptyChart;
}

function updateChart(chart, chartType, title, labels, labelDataDict) {
  chart.data.labels = labels;

  // stacked
  if (chartType === 'stacked') {
    chart.type = 'bar';
    Object.keys(labelDataDict).forEach((k, i) => {
      randomColor = Math.floor(Math.random() * 48824545).toString(16);
      chart.data.datasets.push({
        'label': k,
        'data': labelDataDict[k],
        'backgroundColor': ['red', 'blue', 'green'][i]
      });
    });

    chart.options = {
      scales: {
        xAxes: [{
          stacked: true
        }],
        yAxes: [{
          stacked: true
        }]
      }
    };
  }

  // title
  if (title) {
    chart.options.title = {
      display: true,
      text: title
    };
  }

  chart.options.legend = {
    position: 'bottom'
  };
  chart.update();
}

var labels = ['A', 'B', 'C', 'D'];
var labelDataDict = {
  'category 1': [2, 3, 4, 5],
  'category 2': [4, 2, 5, 6],
  'category 3': [3, 4, 1, 5]
};

var emptyChart = setEmptyChart();
updateChart(emptyChart, 'stacked', 'Chart Title', labels, labelDataDict);
<script src="https://cdnjs.cloudflare.com/ajax/libs/Chart.js/2.9.3/Chart.js"></script>
<canvas id="myChart" height="100"></canvas>

Leave a comment