Search code examples
javascripthtmlhighchartsdatatables

How to display column headers in Y axis for a Datatable using HighCharts?


I am using Datatables and HighCharts. Please see my code below. I am not sure how to display this bar chart where Years are displayed in Y axis. I have added an image below to show how it looks like. I am new to HighCharts, so I am not sure of all the functions. Thanks. How can I get graph to show like this? I want years in Y axis. Thanks. enter image description here

http://live.datatables.net/febayaxa/1/edit

    $(document).ready(function() {
        var table = $("#example1").DataTable();
        var salary = getSalaries(table);
     
        // Declare axis for the column graph
        var axis = {
            id: "salary",
            min: 0,
            title: {
                text: "Number"
            }
        };
     
        // Declare inital series with the values from the getSalaries function
        var series = {
            name: "Overall",
            data: Object.values(salary)
        };
     
        var myChart = Highcharts.chart("container", {
            chart: {
                type: "column"
            },
            title: {
                text: "Test Data"
            },
            xAxis: {
                categories: Object.keys(salary)
            },
            yAxis: axis,
            series: [series]
        });
     
        // On draw, get updated salaries and refresh axis and series
        table.on("draw", function() {
            salary = getSalaries(table);
            myChart.axes[0].categories = Object.keys(salary);
            myChart.series[0].setData(Object.values(salary));
        });
    });
     
    function getSalaries(table) {
        var salaryCounts = {};
        var salary = {};
         
        // Get the row indexes for the rows displayed under the current search
        var indexes = table
            .rows({ search: "applied" })
            .indexes()
            .toArray();
         
        // For each row, extract the office and add the salary to the array
        for (var i = 0; i < indexes.length; i++) {
            var office = table.cell(indexes[i], 0).data();
            if (salaryCounts[office] === undefined) {
                salaryCounts[office] = [+table.cell(indexes[i], 1).data().replace(/[^0-9.]/g, "")];
            }
            else {
                salaryCounts[office].push(+table.cell(indexes[i], 1).data().replace(/[^0-9.]/g, ""));
            }
        }
         
        // Extract the office names that are present in the table
        var keys = Object.keys(salaryCounts);
         
        // For each office work out the average salary
        for (var i = 0; i < keys.length; i++) {
            var length = salaryCounts[keys[i]].length;
            var total = salaryCounts[keys[i]].reduce((a, b) => a + b, 0);
            salary[keys[i]] = total / length;
        }
     
        return salary;
    };
    <!DOCTYPE html>
    <html>
      <head>
        <script src="http://code.jquery.com/jquery-1.11.3.min.js"></script>

        <link href="https://nightly.datatables.net/css/jquery.dataTables.css" rel="stylesheet" type="text/css" />
        <script src="https://nightly.datatables.net/js/jquery.dataTables.js"></script>
     <script src="http://code.jquery.com/jquery-1.11.3.min.js"></script>

        <link href="https://nightly.datatables.net/css/jquery.dataTables.css" rel="stylesheet" type="text/css" />
        <script src="https://nightly.datatables.net/js/jquery.dataTables.js"></script>
    <script src="https://code.highcharts.com/highcharts.js"></script>
        <meta charset=utf-8 />

      </head>
      <body>

    <div id="container" style=" width: 100%; height: 400px;"></div>

    <div class="container">
    <table id="example1" class="display nowrap" width="100%"><thead>
    <tr><th>Year</th><th>2012</th><th>2013</th><th>2014</th><th>2015</th><th>2016</th><th>2017</th><th>2018</th><th>2019</th><th>2020</th><th>2021</th></tr></thead>
      
     <tr ><td> Data</td><td>3,823</td><td>3,823</td><td>3,954</td><td>3,959</td><td>3,955</td><td>3,956</td><td>3,843</td><td>3,699</td><td>3,472</td><td>3,551</td></tr></tbody> 
      </tbody></table>

Solution

  • I am going to assume you mean the x-axis (the horizontal axis) when you say that you want to use the years (from the table headings) from your DataTable for each bar's label in the chart.

    You can access these table headings using the DataTables API and some jQuery.

    Use this to get an array of table heading elements:

    api.columns().header()

    And then use $(element).html() to get the label (the year) from each heading.


    There is a lot of code in your example in the question which does not appear to be relevant to the chart you want to create, so in the following example, I removed all of that. If it is needed, you can put it back.

    $(document).ready(function() {
    
      var tableData = [];
      var tableCategories = []
    
      var table = $("#example1").DataTable({
        initComplete: function(settings, json) {
          let api = new $.fn.dataTable.Api(settings);
    
          // get the seris data as an array of numbers from the table row data:
          api.rows().data().toArray()[0].forEach(function(element, index) {
            if (index > 0) {
              tableData.push(parseFloat(element.replace(/,/g, '')));
            }
          });
    
          // get the x-axis caregories from the table headings:
          api.columns().header().toArray().forEach(function(element, index) {
            if (index > 0) {
              tableCategories.push($(element).html());
            }
          });
    
            
        }
      });
    
      var myChart = Highcharts.chart("container", {
        chart: {
          type: "column"
        },
        title: {
          text: "Test Data"
        },
        xAxis: {
          categories: tableCategories
        },
        series: [{
          data: tableData
        }]
      });
    
    });
    <!DOCTYPE html>
    <html>
    
    <head>
      <script src="http://code.jquery.com/jquery-1.11.3.min.js"></script>
    
      <link href="https://nightly.datatables.net/css/jquery.dataTables.css" rel="stylesheet" type="text/css" />
      <script src="https://nightly.datatables.net/js/jquery.dataTables.js"></script>
      <script src="http://code.jquery.com/jquery-1.11.3.min.js"></script>
    
      <link href="https://nightly.datatables.net/css/jquery.dataTables.css" rel="stylesheet" type="text/css" />
      <script src="https://nightly.datatables.net/js/jquery.dataTables.js"></script>
      <script src="https://code.highcharts.com/highcharts.js"></script>
      <meta charset=utf-8 />
    
    </head>
    
    <body>
    
      <div id="container" style=" width: 100%; height: 400px;"></div>
    
      <div class="container">
        <table id="example1" class="display nowrap" width="100%">
          <thead>
            <tr>
              <th>Year</th>
              <th>2012</th>
              <th>2013</th>
              <th>2014</th>
              <th>2015</th>
              <th>2016</th>
              <th>2017</th>
              <th>2018</th>
              <th>2019</th>
              <th>2020</th>
              <th>2021</th>
            </tr>
          </thead>
    
          <tr>
            <td> Data</td>
            <td>3,823</td>
            <td>3,823</td>
            <td>3,954</td>
            <td>3,959</td>
            <td>3,955</td>
            <td>3,956</td>
            <td>3,843</td>
            <td>3,699</td>
            <td>3,472</td>
            <td>3,551</td>
          </tr>
          </tbody>
    
    
    
          </tbody>
    
        </table>


    The output looks like this:

    enter image description here


    If you do actually want the years labels to be displayed on the y-axis (with horizontal bars, instead of vertical bars) then you can change the chart type by changing this part of the chart...

    chart: { type: "column" },
    

    to this:

    chart: { type: "bar" },