Search code examples
javascripthighchartsdatatables

How to swap rows / columns of a Datatable in Highchart


I refer to that case, which is very similar to my need, as my datatable is very similar to the one used. My question does not refer to the Datatable but to the Hightcart: I need, using a line type rather than column type, to have the years on the xAxis rather than the categories, and the categories as series.

Would you know how I could amend the code?

`$(document).ready(function() {

  var allSeriesData = [];
  var categories = [];

  var table = $("#example1").DataTable({
    initComplete: function(settings, json) {
      let api = new $.fn.dataTable.Api(settings);

      // get the x-axis caregories from the table headings:
      var headers = api.columns().header().toArray();
      headers.forEach(function(heading, index) {
        if (index > 0 && index < headers.length - 1) {
          categories.push($(heading).html());
        }
      });

      // get the seris data as an array of numbers from the table row data:
      let rows = api.rows().data().toArray();
      rows.forEach(function(row) {
        group = {
          name: '',
          data: []
        };
        row.forEach(function(cell, idx) {
          if (idx == 0) {
            group.name = cell;
          } else if (idx < row.length - 1) {
            group.data.push(parseFloat(cell.replace(/,/g, '')));
          }
        });
        allSeriesData.push(group);
      });  
    }
  });

  var myChart = Highcharts.chart("container", {
    chart: {
      type: "line"
    },
    title: {
      text: "Test Data"
    },
    xAxis: {
      categories: categories
    },
    series: allSeriesData
  });

});

Solution

  • I would recommend using the Highcharts Data module as follows:

    HTML

    <script src="https://code.highcharts.com/highcharts.js"></script>
    <script src="https://code.highcharts.com/modules/data.js"></script>
    <div id="container"></div>
    <table id="datatable"> ... </table>
    

    JS

    Highcharts.chart("container", {
      data: {
        table: datatable,
        complete: function(options) {
          options.series.forEach(series => {
            series.data = series.data.map(function(data) {
              if (typeof data[1] === 'string') {
                return [data[0], parseInt(data[1].replace(/,/g, ''))];
              } else {
                return [data[0], data[1]];
              }
            });
          })
        }
      },
      chart: {
        type: "line"
      },
      title: {
        text: "Test Data"
      },
      xAxis: {
        type: 'category'
      },
    });
    

    Demo: https://jsfiddle.net/BlackLabel/7egbdvfh/

    API References: https://www.highcharts.com/docs/working-with-data/data-module https://api.highcharts.com/highcharts/data https://api.highcharts.com/highcharts/data.complete