如何在 Highchart 中交换数据表的行/列

问题描述 投票:0回答:1

我指的是那个案例,这与我的需求非常相似,因为我的数据表与使用的数据表非常相似。 我的问题不是指数据表,而是指 Hightcart:我需要使用行类型而不是列类型,在 x 轴上显示年份而不是类别,并将类别作为系列。

你知道我该如何修改代码吗?

`$(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
  });

});
javascript highcharts datatables
1个回答
0
投票

我建议使用 Highcharts

Data module
,如下所示:

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'
  },
});

演示: https://jsfiddle.net/BlackLabel/7egbdvfh/

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

© www.soinside.com 2019 - 2024. All rights reserved.