[英]How to use the tooltipTemplate on Chart.JS 2.0
我正在嘗試將圓環圖與多個數據集一起使用,並使用 tooltipTemplate 功能自定義工具提示內的文本,但沒有任何效果。 這在以前的 Chart js 版本中有效,但不支持多個數據集。 任何人都可以幫忙嗎? 下面是我的代碼:
options: {
tooltips: {
tooltipTemplate: "<%if (label){%><%=value%><%} else {%> No data <%}%>",
},
}
正如potatopeelings 在評論中提到的,您必須為工具提示設置回調。
下面是一個例子:
options: {
tooltips: {
callbacks: {
label: function(tooltipItem, data) {
var datasetLabel = data.datasets[tooltipItem.datasetIndex].label || 'Other';
var label = data.labels[tooltipItem.index];
return datasetLabel + ': ' + label;
}
}
}
}
現場演示
var ctx = document.getElementById("myChart"); var myChart = new Chart(ctx, { type: 'doughnut', data: { labels: ["Men", "Women", "Unknown"], datasets: [{ label: 'Sweden', data: [60, 40, 20], backgroundColor: ['rgba(158, 216, 202, 0.75)', 'rgba(255, 150, 162, 0.75)', 'rgba(160, 160, 160, 0.75)'] }, { label: 'Netherlands', data: [40, 70, 10], backgroundColor: ['rgba(158, 216, 202, 0.5)', 'rgba(255, 150, 162, 0.5)', 'rgba(160, 160, 160, 0.5)'] }, { data: [33, 33, 34], backgroundColor: ['rgba(158, 216, 202, 0.25)', 'rgba(255, 150, 162, 0.25)', 'rgba(160, 160, 160, 0.25)'] }] }, options: { tooltips: { callbacks: { label: function(tooltipItem, data) { var datasetLabel = data.datasets[tooltipItem.datasetIndex].label || 'Other'; var label = data.labels[tooltipItem.index]; return datasetLabel + ': ' + label; } } } } });
<script src="https://cdnjs.cloudflare.com/ajax/libs/Chart.js/2.1.2/Chart.min.js"></script> <canvas id="myChart" width="400" height="200"></canvas>
Chart.js 1.x tooltipsTemplate 等效於 Chart.js 2.x 中的options.tooltips.callbacks.title
:
var ctx = document.getElementById("myChart"); var myChart = new Chart(ctx, { type: 'doughnut', data: { labels: [ "Men", "Women", "Unknown" ], datasets: [{ label: 'Sweden', data: [60, 40, 20], backgroundColor: [ 'rgba(158, 216, 202, 0.75)', 'rgba(255, 150, 162, 0.75)', 'rgba(160, 160, 160, 0.75)' ] }, { label: 'Netherlands', data: [40, 70, 10], backgroundColor: [ 'rgba(158, 216, 202, 0.5)', 'rgba(255, 150, 162, 0.5)', 'rgba(160, 160, 160, 0.5)' ] }, { data: [33, 33, 34], backgroundColor: [ 'rgba(158, 216, 202, 0.25)', 'rgba(255, 150, 162, 0.25)', 'rgba(160, 160, 160, 0.25)' ] }] }, options: { tooltips: { callbacks: { label: function(tooltipItem, data) { return 'This value ' + tooltipItem.yLabel; }, title: function(tooltipItem, data) { return 'The tooltip title ' + tooltipItem[0].xLabel; } } } } });
<script src="https://cdnjs.cloudflare.com/ajax/libs/Chart.js/2.1.2/Chart.min.js"></script> <canvas id="myChart" width="400" height="200"></canvas>
您必須將工具提示mode
options
設置為label
以顯示多個工具提示
options: {
tooltips: {
mode : 'label'
}
}
如果你想隱藏標簽,你可以簡單地試試這個
options =
{
tooltips :{
titleFontSize : 0,
titleMarginBottom:-0.5
}
}
工具提示參考https://www.chartjs.org/docs/latest/configuration/tooltip.html
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.