Draw Graphs with JSON Data

Previous post dealt with sending JSON data around. Now, I need to be able to draw it. After looking for graphing libraries, I’ve settled on Chart.js and on CanvasJS.

Common steps

All graphs need a canvas element to function:

First thing I wanted, was to get the data with AJAX. This way, my page would not really get blocked (hopefully). So, the AJAX bit (via jQuery) is quite simple:

When the data gets in, It’ll contain dictionaries with 2 items. The “x” field is a data sent as a string. We need to vonvert it. We also need to replace the transation values with a cummulative value. The code looks sonething like this (placed in the “Graph drawing here” scope:

At this point, we have the appropriate data and types in the “x” and “y” components.

CanvasJS

First, we need to iplort CanvasJS:

Plotting the data with CanvasJS was a breeze once I figured out how to do the labeling. First, I’ve created the configuration object (just after the data preparation) :

The above code sets:

  • The graph title
  • the X axis labels
  • The Y axis minimum range
  • The data plot (the dataset, graph and marker types)

Now we only have to actually draw the graph:

The result is below:

CanvasJS

Chart.js

We need to import Chart.js. We also need to import moment.js because we’ll use it to format the x-axis’ labels:

Chart.js has a similar approach, although configuration is more verbose:

We set up:

  • The data set (values, color…)
  • We hide the legend, because we know what’s plotted
  • We set up the x-axis’ labels via a callback

Now, we need to render the graph:

The result is:

Chart.js

Conclusion

As you’ve seen, the effort to plot data is roughly the same. You need dictionaries with “x” and “y” keys, where “x” contains the date and “y” contains the value. Chart.js is a bit more verbose to configure, but results are similar.


A little experiment: If you find this post and ad below useful, please check the ad out :-)

Leave a Reply

Your email address will not be published. Required fields are marked *

This site uses Akismet to reduce spam. Learn how your comment data is processed.

Scroll to top