2017-03-31 67 views
0

我使用Chart.js繪製餅圖。在charts.js餅圖中的千分隔符

要繪製圖表我用

var ctx = document.getElementById("myChart").getContext('2d'); 
     var myChart = new Chart(ctx, { 
     type: 'pie', 
     data: { 
      labels: #{raw @labels.to_json}, 
      datasets: [{ 
      backgroundColor: #{raw @colors.to_json}, 
      data: #{@followers} 
      }] 
     } 
     }); 

要弄清這個數據就是這樣

data: { 
     labels: ["FAISAL","muhammadfaisali","faisaliqbal3699"], 
     datasets: [{ 
     backgroundColor: ["#00b638","#efaa30","#50c8ea"], 
     data: [500000, 75000, 100000] 
     }] 
    } 

我需要證明這些data: [500000, 75000, 100000]爲千位分隔符像["500,000", "75,000", "100,000"]

我嘗試了不同的

東西在結束性寫這個方法

function separator(numbers) 
     { data = [] 
     for (i = 0; i < numbers.length; ++i) { 
      data.push(numbers[i].toLocaleString()) 
     } 
     data 
     } 

,並試圖使用它像這樣

data: separator(#{@followers}) 

它格式的數據,我想,但給人錯誤,如Cannot read property 'custom' of undefined

什麼是顯示在千個分隔符數據的方式這裏

showing it like this now

+0

你可以先檢查[這裏](http://stackoverflow.com/questions/149055/how-can-i-format-numbers-as-money-in-javascript)?您通常在渲染前格式化數據。不知道在charts.js中何時發生這種情況。 當並非所有數據都是整數時,屬性錯誤可能會發生? –

回答

2

要在chart.js中執行此操作,您需要使用tooltips.callbacks.label回調屬性。此回調返回的值是用於生成工具提示文本的值。

以下是配置了工具提示回調的圖表,該回調爲您的數據值使用本地字符串表示形式。

var ctx = document.getElementById("chart-area").getContext("2d"); 
var myPie = new Chart(ctx, { 
    type: 'pie', 
    data: { 
    labels: ["FAISAL","muhammadfaisali","faisaliqbal3699"], 
    datasets: [{ 
     backgroundColor: ["#00b638","#efaa30","#50c8ea"], 
     data: [500000, 75000, 100000] 
    }], 
    }, 
    options: { 
    title: { 
     display: true, 
     text: 'Employee Overview', 
     fontStyle: 'bold', 
     fontSize: 20 
    }, 
    tooltips: { 
     callbacks: { 
     // this callback is used to create the tooltip label 
     label: function(tooltipItem, data) { 
      // get the data label and data value to display 
      // convert the data value to local string so it uses a comma seperated number 
      var dataLabel = data.labels[tooltipItem.index]; 
      var value = ': ' + data.datasets[tooltipItem.datasetIndex].data[tooltipItem.index].toLocaleString(); 

      // make this isn't a multi-line label (e.g. [["label 1 - line 1, "line 2, ], [etc...]]) 
      if (Chart.helpers.isArray(dataLabel)) { 
      // show value on first line of multiline label 
      // need to clone because we are changing the value 
      dataLabel = dataLabel.slice(); 
      dataLabel[0] += value; 
      } else { 
      dataLabel += value; 
      } 

      // return the text to display on the tooltip 
      return dataLabel; 
     } 
     } 
    } 
    } 
}); 

您可以在此codepen看到它的行動。

+0

非常感謝:) –