从React中的JSON文件的空值中删除Highcharts柱形图中的间隙

时间:2018-12-09 23:16:25

标签: javascript reactjs highcharts

我想按Highcharts柱形图上的类别对各列进行对齐,因此它可以更正空值。下面的功能是由Grzegorz编写的。但是,当我尝试在React官方包装器中添加函数时,它返回未定义的“ element”。我该如何适应React官方包装。记住,我只想忽略空值而不是零的间隔。这是我的代码的codesandbox,逻辑应该在Chart.js组件中。 Chart is in ./components/Chart.js

var justifyColumns = function (chart) {
    var categoriesWidth = chart.plotSizeX / (1 + chart.xAxis[0].max - chart.xAxis[0].min),
        distanceBetweenColumns = 0,
        each = Highcharts.each,
        sum, categories = chart.xAxis[0].categories,
        number;
    for (var i = 0; i < categories.length; i++) {
        sum = 0;
        each(chart.series, function (p, k) {
            if (p.visible) {
                each(p.data, function (ob, j) {
                    if (ob.category == categories[i]) {
                        sum++;
                    }
                });
            }
        });
        distanceBetweenColumns = categoriesWidth / (sum + 1);
        number = 1;
        each(chart.series, function (p, k) {
            if (p.visible) {
                each(p.data, function (ob, j) {
                    if (ob.category == categories[i]) {
                        ob.graphic.element.x.baseVal.value = i * categoriesWidth + distanceBetweenColumns * number - ob.pointWidth / 2;
                        number++;
                    }
                });
            }
        });
    }
};

1 个答案:

答案 0 :(得分:1)

您提供的函数不适用于null值,如果没有反应包装,您也会注意到这些值:http://jsfiddle.net/BlackLabel/2q18zkcj/

您需要更改函数的工作方式:

function justifyColumns(chart) {
  var categoriesWidth = chart.plotSizeX / (1 + chart.xAxis[0].max - chart.xAxis[0].min),
    distanceBetweenColumns = 0,
    each = Highcharts.each,
    sum, categories = chart.xAxis[0].categories,
    number;
  for (var i = 0; i < categories.length; i++) {
    sum = 0;
    each(chart.series, function (p, k) {
      if (p.visible) {
        each(p.data, function (ob, j) {
          if (ob.category == categories[i] && ob.y !== null) {
            sum++;
          }
        });
      }
    });
    distanceBetweenColumns = categoriesWidth / (sum + 1);
    number = 1;
    each(chart.series, function (p, k) {
      if (p.visible) {
        each(p.data, function (ob, j) {
          if (ob.category == categories[i] && ob.y !== null) {
            ob.graphic.element.x.baseVal.value = i * categoriesWidth + distanceBetweenColumns * number - ob.pointWidth / 2;
            number++;
          }
        });
      }
    });
  }
};

实时演示:https://codesandbox.io/s/p5j09zrz8q