Skip to content Skip to sidebar Skip to footer

Modify Dojo Chart X Axis With Real Data

Question: How can I build an X axis for a dojo chart from a Date column? I'm trying to create a custom addAxis() function for the x axis of a Dojo multiseries line chart. Incoming

Solution 1:

The trick, it seems, is to add an "id" column to the JSON MySQL output, and also set that id field as the Memory object id via idProperty in the Memory constructor, as in this example:

in the PHP code:

...
$stmt = $conn->prepare("@i := 0");
$stmt->execute();
$stmt = $conn->prepare("SELECT @i:=@i+1 AS id, myDate, myVal1, myVal2 FROM T_BlahBlah");
$stmt->execute();
$data = $stmt->fetchAll(PDO::FETCH_ASSOC);

// Might need to convert some "null"s to NULL// Toss the "null" strings
array_walk_recursive($data, function(&$item, $key) {
    if ($item == 'null' || $item == NULL) $item = NULL;
});
echo json_encode($data, JSON_NUMERIC_CHECK);

Now, your JSON looks like:

[{"id":1,"myDate":"2014-12-01","myVal1":2.22,"myVal2":0.77},
 {"id":2,"myDate":"2014-12-02","myVal1":4.92,"myVal2":1.14},...

The JavaScript to grab this data looks like:

...
function(ready, Chart, StoreSeries, Claro, Legend,
         Default, Markers, Tooltip,
         Magnify, SelectableLegend,
         Memory, Observable, SimpleQueryEngine, lang, arr,
         xhr, domConstruct, dom, aspect){

         xhr.get({
             url: "blahDatum.php",
             sync: true,
             handleAs: "json"
         }).then(function(data){
             store = Observable(newMemory({data:data, idProperty:"id"}));
         });

         // Create the chart within it's "holding" nodevar chart = new dojox.charting.Chart("chartNode");

         // Set the theme
         chart.setTheme(Claro);

         chart.addPlot("default", {
             type: Markers,
             markers: true,
             interpolate: true,
             tension: "X"
         });

         chart.addAxis("x", {
             title: "Date",
             titleOrientation: "away",
             includeZero: false,
             rotation: -30,
             minorTicks: false,
             labelFunc: function(n) {
                 var row = store.get(n);
                 if (row !== null && row !== undefined) {
                     var date = newDate(row.Date);
                     return date.toLocaleDateString();
                 }
             }
         });
         .... // addSeries, legend, etc

Everything clicked into place once I set the idProperty in the Memory() constructor.

This answer also explains how you add an X axis using ISO dates from a database.

Post a Comment for "Modify Dojo Chart X Axis With Real Data"