We help IT Professionals succeed at work.

Highcharts from table (cross-tab/pivot format)

av8or16
av8or16 asked
on
I need to visualize table data in highcharts, but I have two formats for how data is displayed in a table.

The first method works just fine when the series data are in columns see highcharts example  , but I run into problems when my data table is setup in cross-tab/pivot format (series data are in rows).

<table id="datatable" class="tablesorter">
<thead>
		<tr>
			<th>Company</th><th>2005</th><th>2006</th><th>2007</th>
		</tr>
	</thead>
	<tbody>
		<tr>
			<td>test1</td><td>5647</td><td>1678</td><td>2564</td>
		</tr>
		<tr>
			<td>test2</td><td>4647</td><td>2678</td><td>3564</td>
		</tr>
		<tr>
			<td>test3</td><td>3647</td><td>3678</td><td>4564</td>
		</tr>
	</tbody>	
</table>

Open in new window


Is there a modification I can make to the table parse to generate the way I need it?
header is the x-axis (i have already modified the code to make this work, not shown below)
first column of each row is the series name (shown in legend)
and data are all subsequent columns in the row

this is the standard parse that works with my regular tables:

options.xAxis.categories = [];
   $('tbody th', table).each( function(i) {
      options.xAxis.categories.push(this.innerHTML);
   });
   
   // the data series
   options.series = [];
   $('tr', table).each( function(i) {
      var tr = this;
      $('th, td', tr).each( function(j) {
         if (j > 0) { // skip first column
            if (i == 0) { // get the name and init the series
               options.series[j - 1] = { 
                  name: this.innerHTML,
                  data: []
               };
            } else { // add values
               options.series[j - 1].data.push(parseFloat(this.innerHTML));
            }
         }
      });
   });

Open in new window


Thanks in advance
Comment
Watch Question

Commented:
Figured it out... dumb question

needed to change the index variable name to reflect the change--see difference from code above

options.series = [];
   $('tr', table).each( function(i) {
      var tr = this;
      $('th,td', tr).each( function(j) {
         if (i > 0) { // skip first column
            if (j == 0) { // get the name and init the series
               options.series[i - 1] = {
                  name: this.innerHTML,
                  data: []
               };
            } else { // add values
               options.series[i - 1].data.push(parseFloat(this.innerHTML));
            }
         }
      });
   });