Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Chart.js zeros handling

I'm working with chart.js and to render a doughnut chart. I want to set the initial chart total value to zero so it can render a full " empty" chart. When I instatiate the chart with zeros it does not render. I cannot find how it handle zeros in the developer documentation.

var kPoints = 000;
var mPoints = 000;
var tPoints = 000;
var cPoints = 000;
var doughnutData = [ {
    value : kPoints,
    color : "#FF8000"
}, {
    value : mPoints,
    color : "#99CC00"
}, {
    value : tPoints,
    color : "#0099CC"
}, {
    value : cPoints,
    color : "#333333"
}, ];
var ctx = $("#profileChart").get(0).getContext("2d");
var myDoughnut = new Chart(ctx).Doughnut(doughnutData);
like image 753
Rodrigo E. Pinheiro Avatar asked May 29 '14 18:05

Rodrigo E. Pinheiro


1 Answers

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/

like image 118
Ishan Chatterjee Avatar answered Sep 25 '22 13:09

Ishan Chatterjee