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!

3 comments:

  1. I am trying to create column chart as well as line chart using highchart but I am not sure how to format the data for X-Axis and Series. I have a datatable with Product,Year,Sales column now I needs to show this in Column chart. Can you help me how to format this datatable to show column chart.

    ReplyDelete
  2. I am using ASP.net web form with C# as codebehind

    ReplyDelete
    Replies
    1. Pradeep,

      Take a look at the demo graphs at http://www.highcharts.com/demo. You can view the javascript that was used to create those graphs.

      In ASP.NET WebForms, one way to accomplish this is to have a page method (a method annotated with the WebMethod attribute) that returns the DataTable data in JSON format. On the client-side, it'll be a case of making an AJAX call to this page method to retrieve the data, then you can use the highcharts api to plot your graph. I used JQuery to make my AJAX calls to the server-side.

      Delete