javascriptchart.jschart.js3

How can I display `Null` value data on Y Axis using the Primitive dataset format in Chart.js V3.7.0?


I was wondering if there is a way to display or append Null values in Primitive Dataset.

So far this is a short explanation in code of what my code actually does and how I try to Achieve the same thing, but with no success.

PHP Code (I use php to format some data I have in the correct format according to the Primitive dataset documentation):

<?php
    //The Variable below is being appended with data.
    $values .= "$value_I_want_to_append ,";
?> 
// In the end the $values variable looks like this if printed:
   0.456 ,0,424 ,0.223 etc...

Chart's script where I use this variable:

 const data = {
   datasets: [{
      data: [ <? echo $values; ?> ],
   }],
 };

Question:

How can I append data that is of type equal to Null on the chart, without the chart breaking? (By the term breaking, I mean the chart is not displaying values at all when I have atleast one null value).

Thanks in advance for your time and effort. The Library is Called Chart.js and the version of the library is 3.7.0.


Solution

  • You can define spanGaps: true on your dataset.

    spanGaps: If true, lines will be drawn between points with no or null data.

    For further details, consult the Line Styling section of the Chart.js documentation.

    new Chart('chart', {
      type: 'line',
      data: {
        labels: ['A', 'B', 'C', 'D', 'E', 'F', 'G'],
        datasets: [{
          data: [15, null, 13, 8, null, 9, 10],
          backgroundColor: 'rgba(255, 0, 0, 0.5)',
          borderColor: 'rgb(255, 0, 0)',
          tension: 0.2,
          spanGaps: true
        }],
      },
      options: {
        scales: {
          y: {
            beginAtZero: true
          }
        }
      }
    });
    <script src="https://cdnjs.cloudflare.com/ajax/libs/Chart.js/3.7.0/chart.min.js"></script>
    <canvas id="chart"></canvas>