Thursday, 17 January 2013

Highcharts JS Library - Overlapping Points

I'm currently working on a small ASP.NET MVC4 application that reports some live numerical data in a chart. My manager pointed me to Highcharts JS which is a neat and simple to setup library. The particular chart type we chose to use was this.

The chart sits in its own partial view. It is periodically polling an action that returns data in JSON format for it to plot along an X-axis representing time. If you take a look at the JavaScript for the demo of the chart we decided to use (link above), it has two places where points are plotted.

Firstly, it plots points when you define a series for the chart - this is where I am plotting all the initial data accumulated since the view was requested by a user. Then, I'm plotting any subsequent data that has just been accumulated using a timer that is defined in the load event for the chart (this is the part that polls the action I mentioned earlier).

When plotting the chart in this way, I ran into an issue when we had no initial data to plot. In this scenario, the chart initially (and correctly) displays as empty. However, as data was coming in from my timer calls to the action - only one point would ever be plotted. After investigating this, it turned out that it was because I was passing in the boolean value true for the "shift" parameter to the Series.addPoint function.

This parameter tells the chart library to shift the graph to the left (thus removing the left-most plot) and hence my last plotted point was always being lost on each poll to the action. This in-turn gave the illusion that my points were being overwritten. To fix this, I passed in a boolean expression that tests if the series has 30 points plotted - this ensured that the chart always displays 30 plotted points at the most and resolved the problem of "overwriting" plotted points!