Iam trying to add an euro sign to the tooltips of my grouped bar chart using ChartJS. Snipped:
tooltips: {
mode: 'label',
callbacks: {
label: function(tooltipItem, data) {
return data['datasets'][0]['data'][tooltipItem['index']] + '€';
}
}
}
This code works for my linechart, but not for my grouped bar chart. I want my bar chart to look like the following, when I hover it:
But there is no euro sign in my chart, it just display its value. What am I doing wrong?
Thank you.
** Edit
So my full options looked like the following:
options: {
title: {
display: true,
text: 'Title',
},
scales: {
yAxes: [{
scaleLabel: {
display: true,
labelString: 'Wert in €'
}
}],
xAxes: [{
scaleLabel: {
display: true,
labelString: 'Zeitintervall'
}
}]
},
tooltips: {
mode: 'label',
callbacks: {
label: function(tooltipItem, data) {
return data['datasets'][0]['data'][tooltipItem['index']] + '€';
}
}
}
}
As soon as i removed the scales, it is showing the euro sign.
So my options now look like the following:
options: {
title: {
display: true,
text: 'Title'
},
tooltips: {
mode: 'label',
callbacks: {
label: function(tooltipItem, data) {
return data['datasets'][0]['data'][tooltipItem['index']] + ' €';
}
}
}
}
But now i got another problem, it shows the same value for two different bars:
You can see clearly that the values are not the same. Whats the problem here?
This can be achieved using the following tooltips label callback function :
tooltips: {
mode: 'label',
callbacks: {
label: function(t, d) {
var dstLabel = d.datasets[t.datasetIndex].label;
var yLabel = t.yLabel;
return dstLabel + ': ' + yLabel + ' €';
}
}
}
FYI: This has nothing to do with scales. It would work perfectly fine along with scales
ᴡᴏʀᴋɪɴɢ ᴇxᴀᴍᴘʟᴇ ⧩
var myChart = new Chart(ctx, {
type: 'bar',
data: {
labels: ['Jan', 'Feb', 'Mar', 'Apr', 'May'],
datasets: [{
label: 'DST1',
backgroundColor: '#3e95cd',
data: [3, 2, 4, 5, 1]
}, {
label: 'DST2',
backgroundColor: '#8e5ea2',
data: [2, 4, 1, 2, 5]
}]
},
options: {
scales: {
yAxes: [{
ticks: {
beginAtZero: true,
stepSize: 1
}
}]
},
title: {
display: true,
text: 'Title'
},
tooltips: {
mode: 'label',
callbacks: {
label: function(t, d) {
var dstLabel = d.datasets[t.datasetIndex].label;
var yLabel = t.yLabel;
return dstLabel + ': ' + yLabel + ' €';
}
}
}
}
});
<script src="https://cdnjs.cloudflare.com/ajax/libs/Chart.js/2.7.1/Chart.js"></script>
<canvas id="ctx"></canvas>
A bit late to the party, but I have recently discovered JavaScript's built-in formatter for currencies, that saves you having to play about with strings and could be helpful here, and is reusable elsewhere in your code!:
const gbp = new Intl.NumberFormat('en-GB', {
style: 'currency',
currency: 'GBP',
minimumFractionDigits: 2
});
Being English I have of course done it in GBP, but I found that changing the en-GB to de-DE and the 'GBP' to 'EUR' worked absolutely fine. Even formatting the decimal points and thousand separators correctly.
EDIT: including how to actually give the formatter a number to format would be useful wouldn't it!
gbp.format(10000); // Returns £10,000.00
Related
Wondering how I can move the text more to the left and create a new line between the labels. As you can see the "label" and "percentage" are on top of each other.
I'm using ChartJS v2.8.0 and ChartJS Plugin Labels 1.1.0
Current Look:
Desired Look:
Current code:
var chart = new Chart(ctx, {
type: 'pie',
data: {
labels: ['T-Shirts', 'Sweaters'],
datasets: [{
backgroundColor: [$('#chart-color-1').val(), $('#chart-color-2').val()],
data: [$('#attire_1_percent').val(), $('#attire_2_percent').val()],
borderWidth: 0
}]
},
options: {
maintainAspectRatio: false,
legend: {
display: false
},
plugins: {
labels: [{
render: "label",
fontColor: '#fff',
},
{
render: 'percentage',
fontColor: '#fff',
}
],
},
tooltips: {
callbacks: {
label: function(tooltipItem, data) {
return data.labels[tooltipItem.index] + ": " + data.datasets[0].data[tooltipItem.index] + "%"
}
},
},
}
});
I am currently trying to show a text stocked in the data in the tooltip, I can#t figure how to make it work, I have tried many things.
You can find below an example of what I#m trying to do, I want that the "text" value is displayed when hovering one of the bar.
I tried this
let data = [{
label: 'Available',
backgroundColor: '#3366ff',
data: [500],
text : "test1"
}, {
label: 'Budget',
backgroundColor: '#009999',
data: [5000, 6500],
text : "test2"
}, {
label: 'Actual',
backgroundColor: '#92d400',
data: [5200, 7245],
text : "test3"
}];
new Chart(document.getElementById("bar-chart-horizontal"), {
type: 'horizontalBar',
data: {
labels: ["Rooms", "Guests"],
datasets: data,
},
options: {
scales: {
xAxes: [{
ticks: {
beginAtZero: true
}
}]
},
tooltips: {
callbacks: {
label: function(tooltipItem, data) {
var item = data.datasets[tooltipItem.datasetIndex].data[tooltipItem.index];
return item.text;
}
}
}
}
});
But this is not working, it is not even displaying anything logical, only "Room" and "Guests".
What should I do to retrieve the correct informations ? I tried doing it like this : Fiddle
But it doesn't work when applied to my code... I'm probably missing something pretty stupid but I can't figure what.
Thanks to all the people that will read this and try to help me.
You just need to update the version of chart.js you are using to the latest V2 version since V3 has breaking changes.
Also you need to specify the x for the number for a horizontalBar instead of a y in both the dataset and the tooltip callback:
var ctx = document.getElementById('chartJSContainer').getContext('2d');
new Chart(ctx, {
type: 'horizontalBar',
data: {
labels: ['2017/06/12', '2017/06/23', '2017/07/12', '2017/07/23', '2017/08/12', '2017/08/23', '2017/09/12'],
datasets: [{
label: 'Values',
data: [{
x: 12,
value: 12,
text: "test1"
},
{
x: 3,
value: 13,
text: "test2"
},
{
x: 1,
value: 15,
text: "test3"
},
{
x: -3,
value: 5,
text: "test4"
},
{
x: 67,
value: 18,
text: "test5"
},
{
x: 12,
value: 11,
text: "test6"
},
{
x: 13,
value: 19,
text: "test7"
}
],
fill: false,
borderWidth: 2
}]
},
options: {
tooltips: {
callbacks: {
label: function(tooltipItem, data) {
var item = data.datasets[tooltipItem.datasetIndex].data[tooltipItem.index];
return item.x + ' ' + item.value + item.text;
}
}
},
responsive: true,
maintainAspectRatio: false,
scales: {
yAxes: [{
ticks: {
beginAtZero: true
}
}]
}
}
});
<body>
<canvas id="chartJSContainer" width="600" height="400"></canvas>
<script src="https://cdnjs.cloudflare.com/ajax/libs/Chart.js/2.9.4/Chart.js"></script>
</body>
This should work:
...
options: {
tooltips: {
callbacks: {
label: (context, data) => data.datasets[context.datasetIndex].data[context.index].text
}
}
...
jsfiddle
I generate a graph where I have 3 groups of data:
bottom
middle
top
Each bar has the top values at the top of the bar, then the middle value and then the bottom value.
When Chart.js displays the tooltip, I have first the bottom value, then the middle and the the top. So, it is the opposite of the order in the bar.
To display the values I added this code
var stackedBarChartOptions = {
responsive: true,
maintainAspectRatio: false,
tooltips: {
mode: 'label',
callbacks: {
label: function (tooltipItem, data) {
return data.datasets[tooltipItem.datasetIndex].label + ": " +
tooltipItem.yLabel;
}
}
}
}
Is it possible to order the list of tool tips?
in the tooltip label callback, we can choose any index to display.
in your callback, you're displaying the index passed to the callback.
tooltipItem.datasetIndex
instead, let's display the reverse order...
data.datasets.length - 1 - tooltipItem.datasetIndex
but we will also have to add the callback for labelColor,
to display the correct color box for the specific label.
see following working snippet...
var chart_canvas = document.getElementById('myChart');
var stackedLine = new Chart(chart_canvas, {
type: 'bar',
data: {
labels: ['A'],
fill: true,
datasets: [
{
label: 'Low',
data: [67.8],
backgroundColor: '#D6E9C6'
},
{
label: 'Moderate',
data: [20.7],
backgroundColor: '#FAEBCC'
},
{
label: 'High',
data: [11.4],
backgroundColor: '#EBCCD1'
}
]
},
options: {
responsive: true,
maintainAspectRatio: false,
tooltips: {
mode: 'label',
callbacks: {
labelColor: function (tooltipItem, data) {
return {backgroundColor: data.data.datasets[data.data.datasets.length - 1 - tooltipItem.datasetIndex].backgroundColor};
},
label: function (tooltipItem, data) {
return data.datasets[data.datasets.length - 1 - tooltipItem.datasetIndex].label + ": " + data.datasets[data.datasets.length - 1 - tooltipItem.datasetIndex].data[tooltipItem.index];
}
}
},
scales: {
xAxes: [{
stacked: true
}],
yAxes: [{
stacked: true
}]
}
}
});
<script src="https://cdnjs.cloudflare.com/ajax/libs/Chart.js/2.9.3/Chart.bundle.min.js"></script>
<canvas id="myChart"></canvas>
I'm working with a scatter chart in chart.js and I need to modify the info what I show when I'm above a point. I think the box that contains this information is called tooltip.
Below I show what I have now,
What I want to do is modify the first one, and put 14:52 like the x-axis.
In the x-axis was easy,
options: {
scales: {
xAxes: [{
type: 'linear',
position: 'bottom',
ticks: {
callback: function(value, index, values) {
var time = String(value);
if (time.length == 3){
time = '0' + time;
}
var hour = time[0] + time[1];
var min = time[2] + time[3];
var label = hour + ':' + min;
return label;
}
}
}]
}
}
And I suppose here I have to use the same function, but I don't know where. I'm not able to access to the box with the information, isn't its name tooltips? For example, I'm doing the code below but nothing change.
tooltips:{
title: "New title"
}
How can I modify that box?
Thank you very much
The title and other items on the tooltip can be customized using callback functions. The correct syntax looks as follows.
tooltips:{
callbacks: {
title: (tooltipItem, data) => "New title"
}
}
Please also have a look on the following more complex sample derived from https://www.chartjs.org/samples/latest/tooltips/callbacks.html. It should make no difference whether you work with a scatter or a line chart.
new Chart(document.getElementById('myChart'), {
type: 'line',
data: {
labels: ['January', 'February', 'March', 'April', 'May', 'June', 'July'],
datasets: [{
label: 'My First dataset',
borderColor: 'red',
backgroundColor: 'red',
data: [15, 22, 18, 28, 8, 13, 24],
fill: false,
}, {
label: 'My Second dataset',
borderColor: 'blue',
backgroundColor: 'blue',
data: [5, 31, 15, 22, 19, 29, 12],
fill: false,
}]
},
options: {
responsive: true,
title: {
display: true,
text: 'Chart.js Line Chart - Custom Information in Tooltip'
},
tooltips: {
mode: 'index',
callbacks: {
title: (tooltipItem, data) => data.labels[tooltipItem[0].index],
footer: (tooltipItems, data) => {
var sum = 0;
tooltipItems.forEach(function(tooltipItem) {
sum += data.datasets[tooltipItem.datasetIndex].data[tooltipItem.index];
});
return 'Sum: ' + sum;
},
},
footerFontStyle: 'normal'
},
hover: {
mode: 'index',
intersect: true
},
scales: {
xAxes: [{
display: true,
scaleLabel: {
show: true,
labelString: 'Month'
}
}],
yAxes: [{
display: true,
scaleLabel: {
show: true,
labelString: 'Value'
}
}]
}
}
});
<script src="https://cdnjs.cloudflare.com/ajax/libs/Chart.js/2.9.3/Chart.min.js"></script>
<canvas id="myChart" height="100"></canvas>
I am using HighCharts to visualize percentages from projects, which are downdrilled into variables which make the percentages!
I will give my code :
$(function () {
// Create the chart
var options = {
chart: {
renderTo: 'container',
type: 'column'
},
title: {
text: 'Comparison'
},
xAxis: {
type: 'category'
},
yAxis: {
title: {
enabled: true,
text: 'Percentages',
style: {
fontWeight: 'normal'
}
},
labels: {
format: '{value}%'
}
},
legend: {
enabled: false
},
plotOptions: {
series: {
borderWidth: 0,
dataLabels: {
enabled: true,
format: '{point.y:.1f}%'
}
}
},
tooltip: {
headerFormat: '<span style="font-size:11px">{series.name}</span><br>',
pointFormat: '<span style="color:{point.color}">{point.name}</span>: <b>{point.y:.2f}%</b> of total<br/>'
},
series: [{
name: '',
colorByPoint: true,
data: []
}],
credits: {
enabled: false
},
drilldown: {
series: [{
name : '',
id: '',
data: []
}]
}
};
$.getJSON('/uploads/fraction.json', function (list) {
options.series = list;
});
$.getJSON('/uploads/drilldown.json', function (list2) {
options.drilldown.series = list2;
var chart = new Highcharts.Chart(options);
});
});
Example of the JSONs:
fraction.json
[{"name":"","colorByPoint":true,"data":[{"name":1,"y":80,"drilldown":1},{"name":2,"y":87,"drilldown":2},{"name":3,"y":105.71428571429,"drilldown":3},{"name":5,"y":"","drilldown":5},{"name":6,"y":53.160248409091,"drilldown":6}]}]
drilldown.json
[{"name":1,"id":1,"data":[["Total",2],["Estimated",2.5]]},{"name":2,"id":2,"data":[["Total",3.9],["Estimated",4.5]]},{"name":3,"id":3,"data":[["Total",3.7],["Estimated",3.5]]},{"name":5,"id":5,"data":[["Total",""],["Estimated",0.44]]},{"name":6,"id":6,"data":[["Total",0.233905093],["Estimated",0.44]]}]
I would like the graph to show percentages above the column and on the yAxis when the graph is first loaded, but absolute values when the drilldown is activated. I didn't manage to get it until now. Could you help me?
There are two ways of doing those changes - a static and dynamic way. Static way - define data labels and tooltip options for drilldown series.
Dynamic way - apply the options on drilldown/drillup events.
events: {
drilldown: function(options) {
this.yAxis[0].update({
labels: {
format: '{value}'
}
}, false, false);
options.seriesOptions.dataLabels = {
format: '{point.y:.1f}'
};
options.seriesOptions.tooltip = {
pointFormat: '<span style="color:{point.color}">{point.name}</span>: <b>{point.y:.2f}</b> of total<br/>'
};
},
drillup: function () {
this.yAxis[0].update({
labels: {
format: '{value}%'
}
}, false, false);
}
}
example: http://jsfiddle.net/d4fmaeea/
Two warnings:
In your json files, you have points which has value equals to "" which is not a valid type (must be number/null) and it may cause some issues, e.g. column with value 0 will have the same height as the column with value 10.
$.getJSON() is an asynchronous function. You use getJSON to assign list to options.series but that part may be executed after the chart was created so you would end up with the chart with no top-level series, only the drilldown ones.
Async part of code:
$.getJSON('/uploads/fraction.json', function (list) {
options.series = list;
});
$.getJSON('/uploads/drilldown.json', function (list2) {
options.drilldown.series = list2;
var chart = new Highcharts.Chart(options);
});