How to Modify Chartjs Tooltip So I Can Add Customized Strings in Tooltips

How to modify chartjs tooltip so i can add customized strings in tooltips

Redefine default global tooltip template as follows:

Chart.defaults.global.tooltipTemplate =
"<%if (label){%><%=label%>: <%}%><%= value %>";

Here is another example:

var ctx = document.getElementById("canvas").getContext("2d");

var myBarChart = new Chart(ctx).Bar(data, {
tooltipTemplate: "<%= value %> Files"
});

Charts.js - How to set custom tooltip text for each dataset

You can do this easily by referring to the current dataset index tooltipItems.datasetIndex and then based on that index set the tooltip text like:

label: function(tooltipItems, data) {
var text = tooltipItems.datasetIndex === 0 ? 'some text 1' : 'some text 2'
return tooltipItems.yLabel + ' ' + text;
}

Working Demo:

var ctx = document.getElementById('myChart').getContext('2d');var chart = new Chart(ctx, {  // The type of chart we want to create  type: "line",  // The data for our dataset  data: {    labels: Array.from({length: 5}, (x,i)=> `Label ${i+1}`),    datasets: [{      label: "Dataset 1",      data: [12, 123, 234, 32, 23],    }, {      label: "Dataset 2",      data: [4, 54, 765, 45, 5],    }]  },  // Configuration options go here  options: {    tooltips: {      enabled: true,      mode: 'single',      callbacks: {        label: function(tooltipItems, data) {          var text = tooltipItems.datasetIndex === 0 ? 'some text 1' : 'some text 2'          return tooltipItems.yLabel + ' ' + text;        }      }    }  }});
.chart-container {   width: 500px;}#myChart {  display: block;   width: 500px; }
<script src="https://cdn.jsdelivr.net/npm/chart.js@2.8.0"></script>
<div class="chart-container"> <canvas id="myChart"></canvas></div>

How to customize the tooltip of a Chart.js 2.0 Doughnut Chart?

You can customize the tooltips using the chart options tooltip configuration section, as explained here: http://www.chartjs.org/docs/latest/configuration/tooltip.html#tooltip-configuration

As shown in the example code below, you can change things like color, sizing and styles. Check out the documentation linked above for a full list of configurable options.

If you want to add the percentage to the tooltip display, you can use tooltip callbacks. The documentation has a list of all the possible customizable callback fields.

In the below example, I set the "title" to show the label name, "label" to show the value, and added the percentage to "afterLabel".

var myChart = new Chart(ctx, {
type: 'doughnut',
data: data,
options: {
tooltips: {
callbacks: {
title: function(tooltipItem, data) {
return data['labels'][tooltipItem[0]['index']];
},
label: function(tooltipItem, data) {
return data['datasets'][0]['data'][tooltipItem['index']];
},
afterLabel: function(tooltipItem, data) {
var dataset = data['datasets'][0];
var percent = Math.round((dataset['data'][tooltipItem['index']] / dataset["_meta"][0]['total']) * 100)
return '(' + percent + '%)';
}
},
backgroundColor: '#FFF',
titleFontSize: 16,
titleFontColor: '#0066ff',
bodyFontColor: '#000',
bodyFontSize: 14,
displayColors: false
}
}
});

Working JSFiddle: https://jsfiddle.net/m7s43hrs/

How to customize the tooltip of a Chart.js Line Chart?

You can define callback functions for the title and content of the tooltips using options.tooltips.callbacks.

const options = {
type: 'line',
options: {
tooltips: {
callbacks: {
title: function(t, d) {
return moment(d.labels[t[0].index]).format('dd MMM DD, YYYY');
},
label: function(t, d) {
const label = d.datasets[t.datasetIndex].label;
const value = d.datasets[t.datasetIndex].data[t.index];
const sign = value >= 0 ? '+' : '';
return `${label}: ${sign}${value.toFixed(2)}%`;
}
}
}
}
};
Demo

const dateRange = n =>
(now =>
new Array(n).fill(0).map((value, index) =>
new Date(now + (8.64e7 * index))))
(Date.now());

const palette = [{
hex: '#5946B0',
rgba: 'rgba(89, 70, 176, 0.33)'
}, {
hex: '#eab925',
rgba: 'rgba(234, 185, 37, 0.33)'
}];

const randRange = n =>
new Array(n).fill(0).map(() =>
chance.floating({ min: -100, max: 300 }))

const options = {
type: 'line',
data: {
labels: dateRange(7),
datasets: [{
label: 'Investment',
data: randRange(7),
borderColor: palette[0].hex,
backgroundColor: palette[0].rgba,
pointBackgroundColor: 'white',
borderWidth: 1
}, {
label: 'Return',
data: randRange(7),
borderColor: palette[1].hex,
backgroundColor: palette[1].rgba,
pointBackgroundColor: 'white',
borderWidth: 1
}]
},
options: {
scales: {
xAxes: [{
type: 'time',
time: {
unit: 'day'
}
}],
yAxes: [{
ticks: {
reverse: false
}
}]
},
tooltips: {
// See: https://stackoverflow.com/a/44010778/1762224
callbacks: {
title: function(t, d) {
return moment(d.labels[t[0].index]).format('dd MMM DD, YYYY');
},
label: function(t, d) {
const label = d.datasets[t.datasetIndex].label;
const value = d.datasets[t.datasetIndex].data[t.index];
const sign = value >= 0 ? '+' : '';
return `${label}: ${sign}${value.toFixed(2)}%`;
}
},
backgroundColor: "#FAFAFA",
borderColor: "lightgreen",
borderWidth: 1,
titleFontColor: "black",
titleFontStyle: "bold",
displayColors: false,
bodyFontColor: "black"
}
}
};

const ctx = document.getElementById('chart').getContext('2d');
new Chart(ctx, options);
<script src="https://cdnjs.cloudflare.com/ajax/libs/chance/1.0.18/chance.min.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/moment.js/2.29.1/moment.min.js"></script>
<link href="https://cdnjs.cloudflare.com/ajax/libs/Chart.js/2.9.4/Chart.min.css" rel="stylesheet" />
<script src="https://cdnjs.cloudflare.com/ajax/libs/Chart.js/2.9.4/Chart.min.js"></script>
<canvas id="chart" height="120"></canvas>

JavaScript Chart.js - Custom data formatting to display on tooltip

You want to specify a custom tooltip template in your chart options, like this :

 // String - Template string for single tooltips
tooltipTemplate: "<%if (label){%><%=label %>: <%}%><%= value + ' %' %>",
// String - Template string for multiple tooltips
multiTooltipTemplate: "<%= value + ' %' %>",

This way you can add a '%' sign after your values if that's what you want.

Here's a jsfiddle to illustrate this.

Note that tooltipTemplate applies if you only have one dataset, multiTooltipTemplate applies if you have several datasets.

This options are mentioned in the global chart configuration section of the documentation. Do have a look, it's worth checking for all the other options that can be customized in there.

Note that Your datasets should only contain numeric values. (No % signs or other stuff there).

Adding custom title in tooltips of chart.js

Use tooltipItem property index to reference the item in your tooltipsLabel array:

var tooltipsLabel = ['Dhaka', 'Rajshahi', 'NewYork', 'London']
var chartList = [5, 6, 7, 8];

function chart() { var ctx = document.getElementById("myChart").getContext('2d'); var myChart = new Chart(ctx, { type: 'bar', data: { labels: ["Red", "Blue", "green", "Yellow"], datasets: [{ label: '# of Votes', data: chartList, backgroundColor: [ 'rgba(255, 99, 132, 0.2)', 'rgba(54, 162, 235, 0.2)', 'rgba(255, 99, 132, 0.2)', 'rgba(54, 162, 235, 0.2)', ], borderColor: [ 'rgba(255,99,132,1)', 'rgba(54, 162, 235, 1)', 'rgba(255,99,132,1)', 'rgba(54, 162, 235, 1)', ], borderWidth: 1 }] }, options: { scales: { yAxes: [{ ticks: { beginAtZero: true } }] }, tooltips: { mode: 'index', intersect: true, callbacks: { title: function(tooltipItem, data) { console.log(tooltipItem); return tooltipsLabel[tooltipItem[0].index]; } } } } });
}
chart();
<script src="https://cdnjs.cloudflare.com/ajax/libs/Chart.js/2.7.1/Chart.bundle.min.js"></script><link href="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.7/css/bootstrap.min.css" rel="stylesheet" integrity="sha384-BVYiiSIFeK1dGmJRAkycuHAHRg32OmUcww7on3RYdg4Va+PmSTsz/K68vbdEjh4u" crossorigin="anonymous">
<div class="row"> <div class="col-lg-4"> <canvas id="myChart" width="100" height="100"></canvas> </div> <div class="col-lg-4"><canvas id="pieChart" width="100" height="100"></canvas></div></div>

Using chart js version 3, how to add custom data to external tooltip?

You can put any custom/advance datas to dataset for example (imgUrls, productIds, imgDataset ) :

var chartdata = {
labels: ["Swimming", "Golf", "Soccer"],
datasets: [{
label: "Choices",
data: [4, 10, 6],
backgroundColor: ["#a19828", "#b15928", "#fb9a99"],
imgDataUrls:['img1','img2','img3'],
imgDataSet:'imgDataset',
productIds:['id1','id2','id3'],
}]
};

Then you can use datasetIndex, dataIndex in Tooltip Item Context to get your custom/advance datas.

// Index of the dataset the item comes from
datasetIndex: number,

// Index of this data item in the dataset
dataIndex: number,

https://github.com/chartjs/Chart.js/blob/master/docs/samples/tooltip/html.md

Chart.js V2: Add prefix or suffix to tooltip label

In the V2.0 the tooltipTemplate option is deprecated. Instead you can use callbacks to modify the displayed tooltips. There is a sample for the usage of callbacks here and you can find the possible callbacks in the documentation under Chart.defaults.global.tooltips

In your case I would do the following:

window.myLine = new Chart(chart, {
type: 'line',
data: lineChartData,
options: {
tooltips: {
enabled: true,
mode: 'single',
callbacks: {
label: function(tooltipItems, data) {
return tooltipItems.yLabel + ' €';
}
}
},
}
});

Don't forget to set the HTML meta tag:

<meta charset="UTF-8">


Related Topics



Leave a reply



Submit