Chart.js – how to have statis lables and populate with dynamic data?

1πŸ‘

βœ…

Here is an example:

// create initial empty chart
var ctx_live = document.getElementById("chLine");
var myChart = new Chart(ctx_live, {
  type: 'bar',
  data: {
    labels: [],
    datasets: [{
      data: [],
      borderWidth: 1,
      borderColor: '#00c0ef',
      label: 'liveCount',
    }]
  },
  options: {
    responsive: true,
    title: {
      display: true,
      text: "Count Per Hour",
    },
    legend: {
      display: false
    },
    scales: {
      yAxes: [{
        ticks: {
          beginAtZero: true,
        }
      }]
    }
  }
});

// Some constants to be changed later:
const HOUR_TO_START = 0;
const HOUR_TO_END = 23;
// helper:
const intToAmPm = (i) => 
  i==0 ? '12 AM' :
  i==12 ? '12 PM' :
  i < 12 ? i + ' AM' :
  (i-12) + ' PM';

// logic to get new data
var getData = function() {
  var _data = [];
  var _labels = [];
  $ajax({
    url: 'chart_data',
    type: "get",
    success: function(data) {
      full_data = JSON.parse(data);
      let preparedData = {};
      full_data.forEach(function(key, index) {
        let hour = parseInt(String(key.timestamp).substring(0, 2));
        preparedData[hour] = key.true_count;
      });
      for (let i = HOUR_TO_START; i <= HOUR_TO_END; i++) {
        _data.push(preparedData[i] === undefined ? 0 : preparedData[i]);
        _labels.push(intToAmPm(i));
      }

      myChart.data.labels = _labels;
      myChart.data.datasets[0].data = _data;

      myChart.update();
    }
  });
};

// get new data every 3 seconds
//setInterval(getData, 3000);
getData();

// THIS IS FOR TESTING. IMITATE BACKEND
function $ajax(param) {
  param.success('[{"timestamp":"06:00:00.000000","true_count":2},{"timestamp":"07:00:00.000000","true_count":5},{"timestamp":"08:00:00.000000","true_count":7},{"timestamp":"09:00:00.000000","true_count":8},{"timestamp":"10:00:00.000000","true_count":12},{"timestamp":"11:00:00.000000","true_count":15},{"timestamp":"12:00:00.000000","true_count":20},{"timestamp":"13:00:00.000000","true_count":17},{"timestamp":"14:00:00.000000","true_count":14},{"timestamp":"16:00:00.000000","true_count":11},{"timestamp":"17:00:00.000000","true_count":19},{"timestamp":"18:00:00.000000","true_count":22},{"timestamp":"19:00:00.000000","true_count":16},{"timestamp":"20:00:00.000000","true_count":14},{"timestamp":"22:00:00.000000","true_count":7}]');
}
<script src="https://cdnjs.cloudflare.com/ajax/libs/Chart.js/2.9.3/Chart.min.js"></script>
<canvas id="chLine"></canvas>

Leave a comment