问题
How I have to edit the tooltip template that i can add customized attributes from my json file ? Below the example:
ChartJS Example
In the x-axis are the Months with the first letter, but in the tooltip i want to show the first three letters of the month - How can i do this ?
EDIT: My JSON File:
{"modules":[{
"name":"Chart 1",
"link":"www.google.com",
"type":"Bar",
"series":"SeriesA",
"data":[[20,40,50,40,20,20,20,20,20,20,20,20]],
"labels":["M","J","J","A","S","O","N","D","J","F","M","A","M"],
"colors":[{
"fillColor":"blue"
}],
"options":{
"scaleShowGridLines":false
}
}]}
回答1:
Different Labels in Tooltip vs Scale
Just use the tooltipTemplate
option
Preview
Script
function Label(short, long) {
this.short = short;
this.long = long
}
Label.prototype.toString = function() {
return this.short;
}
var data = {
labels: [
new Label("J", "JAN"),
new Label("F", "FEB"),
new Label("M", "MAR"),
new Label("A", "APR"),
new Label("M", "MAY"),
new Label("J", "JUN"),
new Label("J", "JUL")
],
datasets: [
{
label: "My First dataset",
fillColor: "rgba(220,220,220,0.5)",
strokeColor: "rgba(220,220,220,0.8)",
highlightFill: "rgba(220,220,220,0.75)",
highlightStroke: "rgba(220,220,220,1)",
data: [65, 59, 80, 81, 56, 55, 40]
}
]
};
// create chart
var ctx = document.getElementById("chart").getContext('2d');
new Chart(ctx).Bar(data, {
tooltipTemplate: "<%if (label){%><%=label.long%>: <%}%><%= value %>",
});
Fiddle - https://jsfiddle.net/7z1s1feg/
回答2:
This part of the documentation explain you how to extend the tooltips elements.
var myPieChart = new Chart(ctx).Pie(data, {
customTooltips: function(tooltip) {
};
});
Plus, this example show you how to modify the HTML of the tooltip inside this function. The example from GitHub :
var innerHtml = '';
for (var i = tooltip.labels.length - 1; i >= 0; i--) {
innerHtml += [
'<div class="chartjs-tooltip-section">',
' <span class="chartjs-tooltip-key" style="background-color:' + tooltip.legendColors[i].fill + '"></span>',
' <span class="chartjs-tooltip-value">' + tooltip.labels[i] + '</span>',
'</div>'
].join('');
}
tooltipEl.html(innerHtml);
With these elements, you will be able to customize your tooltips however you want.
来源:https://stackoverflow.com/questions/34138456/how-to-modify-chartjs-tooltip-to-add-customized-attribute