Chartjs-How to render default values from Django Serializer for charting purposes?

0👍

As you correctly guessed, this is best handled in the the frontend rather than in the backend.

You can define your x-axis as a time cartesian axis that accepts the data of your dataset as individual points through objects containing x and y properties each. Given the base data present in an array named baseData, such data can be created through Array.map() as follows:

baseData.map(o => ({ x: o.month, y: Number(o.total_cost) }))

To make sure, all 12 months are included in the chart, you’ll further have to define ticks.min and ticks.max options on the x-axis.

ticks: {
  min: '2020-01',
  max: '2020-12'
}

Please take a look at the following runnable code and see how it works.

Note that Chart.js internally uses Moment.js for the functionality of the time axis. Therefore you should use the bundled version of Chart.js that includes Moment.js in a single file.

const baseData = [
    { "month": "2020-01-01", "total_cost": "199.00" },
    { "month": "2020-02-01", "total_cost": "222.00" },
    { "month": "2020-03-01", "total_cost": "399.00" },
    { "month": "2020-04-01", "total_cost": "414.00" },
    { "month": "2020-05-01", "total_cost": "555.00" },
    { "month": "2020-06-01", "total_cost": "615.00" },
    { "month": "2020-07-01", "total_cost": "700.00" },
    { "month": "2020-08-01", "total_cost": "913.00" },
    { "month": "2020-09-01", "total_cost": "552.00" },
    { "month": "2020-10-01", "total_cost": "1000.00" }
];

new Chart(document.getElementById('myChart'), {
  type: 'line',  
  data: {
    datasets: [{
      label: 'My Dataset',
      data: baseData.map(o => ({ x: o.month, y: Number(o.total_cost) })),
      fill: false,
      backgroundColor: 'green',
      borderColor: 'green'
    }]
  },
  options: {
    responsive: true,
    scales: {
      xAxes: [{
        type: 'time',
        time: {
          unit: 'month',
          tooltipFormat: 'MMM YYYY'
        },
        ticks: {
          min: '2020-01',
          max: '2020-12'
        }
      }],
      yAxes: [{
        ticks: {
          beginAtZero: true,
          stepSize: 200
        }
      }]
    }
  }
});
<script src="https://cdnjs.cloudflare.com/ajax/libs/Chart.js/2.9.3/Chart.bundle.min.js"></script>
<canvas id="myChart" height="90"></canvas>

Leave a comment