[Chartjs]-Chart.js zeros handling

8👍

From reading the source code for Chart.js I’ve found that the it tries to sum each of the value fields in its datasource before rendering the chart (see the use of segmentTotal here).

To workaround this, use null for all the values and set one (or more) of the data points to a very small, near zero value. I’ve used a float notation here for one of the values:

var kPoints = null;
var mPoints = null;
var tPoints = null;
var cPoints = 1e-10;

After that, the example below re-renders the chart (after a 3 second delay) with different data values to show a case of the values updating from the default “dark” chart to a filled out version:

setTimeout(function () {

    // Generate a new, random value for each of the data points
    doughnutData.forEach(function (item) {
        item.value = Math.floor((Math.random() * 10) + 1);
    });

    var ctx = $("#profileChart").get(0).getContext("2d");
    var myDoughnut = new Chart(ctx).Doughnut(doughnutData);
}, 3000);

JSFiddle Example: http://jsfiddle.net/MasterXen/6S9DB/3/

0👍

Keep a running total of the values when building the doughnut data.
If there are zero data points, or the total value of all data points is zero, then simply inject an extra dummy point with a label like “No Data” along with an either imperceptible (near-zero) value or a dummy value like 1. In either case, you’ll end up with a valid chart with a single category like “No Data”.

Leave a comment