2017-02-19 245 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 –