Monday, August 25, 2014

Charting

For my SLPassist app I wanted to be able to create reports for each student. Additionally, I wanted to implement at least some simple graphs, for a quick and dirty visualization of a student's progress.

Following RailsCasts tutorials, I implemented a Highcharts graph showing a student's percentage of correct vs. incorrect responses per day. My graph was intended to be a stacked column graph like this:



Since I do not expect that the xAxis will have regularly spaced values (a student may use the app as often as once a month), it appeared reasonable to create xAxis values as an array of dates instead of using 'datetime' intervals like in the tutorial. However, it appeared to be problematic to pass a variable from a controller (a variable holding an array of dates) to a javascript function. Whenever a variable was passed, the categories were either rendered incorrectly (parenthesis and other marks were not properly escaped), or errors were raised.

Thanks to the wisdom of SO, the recommendation was to pass the variable as a JSON object. The final code looked like so (only showing the problematic line, cats):

<script type="text/javascript" charset="utf-8">

     var cats = <%= raw @student.dates.to_json %>;

        var chart = new Highcharts.Chart({
               ....
                xAxis: {
                    categories: cats
                },
              ....  
            });
</script>

No comments :

Post a Comment