2017-02-19 253 views
1

这个问题的 Show N/A in datalabels, when value is null - Highcharts柱形图显示datalabel - Highcharts

dataLabels for bar chart in Highcharts not displaying for null values in 3.0.8

可能重复的,但建议的解决方法已停止highcharts的5.0.7版本工作。

formatter: function() { 
    if (this.y == null) { 
     var chart = this.series.chart, 
      categoryWidth = chart.plotWidth/chart.xAxis[0].categories.length, 
      offset = (this.point.x) * categoryWidth + categoryWidth/2, 
      text = chart.renderer.text('N/A', -999, -999).add(); 

     text.attr({ 
      x: chart.plotLeft + offset - text.getBBox().width/2, //center label 
      y: chart.plotTop + chart.plotHeight - 8 // padding 
     }); 

    } else { 
     return this.y; 
    } 
} 

这个问题似乎是在GitHub上仍处于打开状态: https://github.com/highcharts/highcharts/issues/2899

http://jsfiddle.net/90amxpc1/4/

有一种可能的解决方法,以显示类似 “N/A” 使用格式化功能或chart.renderer方法为列图中的空值?

回答

3

新版本的Highcharts格式化程序不再被称为空点。

让代码像以前一样工作的一种方法是将drawDataLabels()方法包装起来,并临时将某些值分配给无效点,例如, 0,并在格式化程序中检查point.isNull是否为真。

var H = Highcharts; 

H.wrap(H.Series.prototype, 'drawDataLabels', function (p) { 
    this.points.forEach(point => { 
    if (point.y === null) { 
     point.y = 0; 
    } 
    }); 

    p.call(this); 

    this.points.forEach(point => { 
    if (point.isNull) { 
     point.y = null; 
    } 
    }); 
}); 

在数据标签的配置:

dataLabels: { 
      formatter: function() { 
       if (this.point.isNull) { 
        var chart = this.series.chart, 
         categoryWidth = chart.plotWidth/chart.xAxis[0].categories.length, 
         offset = (this.point.x) * categoryWidth + categoryWidth/2, 
         text = chart.renderer.text('N/A', -999, -999).add(); 

        text.attr({ 
         x: chart.plotLeft + offset - text.getBBox().width/2, //center label 
         y: chart.plotTop + chart.plotHeight - 8 // padding 
        }); 

        return false; 
       } else { 
        return this.y; 
       } 
      }, 

例如:http://jsfiddle.net/xnxpwt67/

它的工作原理,但它不是一个优雅和高效的解决方案。绘制空值的标签要好得多,例如在加载事件。

chart: { 
    type: 'column', 
    events: { 
    load: function() { 
     const categoryWidth = this.plotWidth/this.xAxis[0].categories.length; 

     this.series[0].points.forEach(point => { 
     if (point.y === null) { 
      const offset = point.x * categoryWidth + categoryWidth/2; 
      const text = this.renderer.text('N/A', -999, -999).add(); 

      text.attr({ 
      x: this.plotLeft + offset - text.getBBox().width/2, 
      y: this.plotTop + this.plotHeight - 8 
      }); 
     } 
     }) 
    } 
    } 
}, 

例如:http://jsfiddle.net/xnxpwt67/1/

+0

谢谢。它运作良好,我能够将它推广到多个系列:https://jsfiddle.net/saad749/ss36jep0/1/ ..但标签的定位变得更加困难。此方法需要更多的空值预处理,但不需要手动定位标签。 https://github.com/highcharts/highcharts/issues/2899#issuecomment-281036396 –