2016-12-13 85 views
0

我想知道ChartJS中是否有一個選項,如果我將鼠標懸停在折線圖上的單個點上,可以看到額外的信息。目前,我的數據是這樣的:在折線圖上爲每個點添加文本

function drawChart(dataSets) { 
    Chart.defaults.global.maintainAspectRatio = false; 
    Chart.defaults.global.responsive = false; 
    var data = { 
     labels: ["ID"] 
     , datasets: dataSets 
    }; 
    var options = { 
     title: { 
      display: true 
      , text: 'Custom Chart Title' 
     } 
     , scales: { 
      yAxes: [{ 
       ticks: { 
        beginAtZero: true 
       } 
      }] 
      , xAxes: [{ 
       type: "linear" 
       , position: "bottom" 
      }] 
     } 
     , tooltips: { 
      callbacks: { 
       label: function (tooltipItem, data) { 
        alert("Entered tooltip callback."); 
        return i18n.t('chart.count') + ': ' + getCount(tooltipItem, data.datasets); 
       } 
      } 
     } 
    }; 
    var myChart = Chart.Line(ctx, { 
     data: data 
     , options: options 
    }); 
} 

function getCount(tooltipItem, datasets) { 
    return datasets[tooltipItem.datasetIndex].data.find(datum => { 
     return datum.x === tooltipItem.xLabel && datum.y === tooltipItem.yLabel; 
    }).count; 
} 

這是一個數據點的樣子:

x:5 
, y:5 
, count:2 

alert「輸入提示」不會被調用,我在做什麼錯?相反,我得到這個錯誤我的控制檯(谷歌瀏覽器):

enter image description here

回答

1

我添加了自定義工具提示的方式。 首先我創建其中數據陣列I中加入附加的信息等的數據集「計數」

x: 10, 
y: 12, 
count: 2 

此計數不示於圖得到除非我手動得到它在選項下工具提示鉤。對於給定的數據集

tooltips: { 
     callbacks: { 
       label: function(tooltipItem, data) { 
        return i18n.t('chart.count') +': ' + getCount(tooltipItem, data.datasets); 
       } 
     } 
} 

獲取計數未在圖

function getCount(tooltipItem, datasets) { 
    return datasets[tooltipItem.datasetIndex].data.find(datum => { 
     return datum.x === tooltipItem.xLabel && datum.y === tooltipItem.yLabel; 
    }).count; 
} 

而結果表示: enter image description here 編輯:加入我的數據集的例子

return [{ 
    label: 'Example dataset', 
    backgroundColor: '#98cc99', 
    borderColor: '#98cc99', 
    pointHoverRadius: 3, 
    data: [ {x:1,y:2,count:3}, {x:2,y3,count:4}, ...] 
}]; 
+0

根據你的回答更新了我的最初問題,這將是非常好的,如果你可以再看看它。 – binaryBigInt

+0

Mkay我做了一個虛擬的數據集,可以使用給定的設置 –

+0

謝謝,現在回調函數被輸入,但我沒有定義「i18n」。這是什麼功能? – binaryBigInt

1

這看起來像是:

label: sensorID, 
data: [0,1,2,3], 
backgroundColor: [ 
     'rgba(' + rndColor() + ',' + rndColor() + ',' + rndColor() + ',0.2)' 
], 
borderColor: [ 
     'rgba(' + rndColor() + ',' + rndColor() + ',' + rndColor() + ',0.2)' 
], 
options: { 
    tooltips: { 
     enabled: true 
     custom: function(tooltip) { 
      // code here to customize a tooltip 
     } 
    } 
} 

http://www.chartjs.org/docs/#chart-configuration-tooltip-configuration

http://www.chartjs.org/docs/#advanced-usage-external-tooltips

見樣本/行-customTooltips.html有關如何獲得的示例開始。

+0

我希望有一個單一的每個數據點的工具提示,而不是每個數據集 – binaryBigInt

相關問題