Search code examples
javascriptgraphdatergraph

How can I use dates as values and along the X axis in RGraph?


I'm trying out the horizontal bar RGraph demo with this code and it works great:

var data = [1, 40, 30];
var hbar = new RGraph.HBar('myCanvas', data);
hbar.Set('chart.labels', ['Richard', 'Alex', 'Nick']);
hbar.Set('chart.background.barcolor1', 'white');
hbar.Set('chart.background.barcolor2', 'white');
hbar.Set('chart.background.grid', true);
hbar.Set('chart.colors', ['red']);
hbar.Draw();

Is there a way I can use Date objects instead of numbers? I couldn't get it to work with stuff like

var data = [new Date(1000), new Date(2000), new Date(3000)];

Solution

  • In that case, you can do something like :

    var data, dates = [new Date("11/16/2011"), new Date("11/17/2011"), new Date("11/18/2011")], labels = [];
    // Get the date from the date objects
    for(var i = 0, len = dates.length; i < len; i++) {
        // Data for the graph
        data[i] = dates[i].getDate();
    
        // Labels for each data entry
        labels[i] = dates[i].getDate() + "/" + dates[i].getMonth() + "/" + dates[i].getYear();  
    }
    var hbar = new RGraph.HBar('myCanvas', data);
    hbar.Set('chart.labels', labels);
    
    /// rest of the code 
    

    Date object on MDN : https://developer.mozilla.org/en/JavaScript/Reference/Global_Objects/Date