How to render tooltip text on a different div with Chart.JS - chart.js

I'm using Chart.js to display some data using a bar chart.
My question is whether there is a way to extract the text of the tooltip and show it on a different div, so whenever I hover the bar chart I get the label and the value hovered in another place of the page.
I managed to alert the label or the value using the alert(label) function. but when I use the $('#mydiv').text(label) function, It does not work.
Here is my code :
<canvas id="widgetChart4"></canvas>
<id id="myDiv"></id>
<script>
var ctx = document.getElementById( "widgetChart4" );
ctx.height=50;
ctx.width=250;
var myChart = new Chart( ctx, {
type: 'bar',
data:
{
labels: [ "January", "February", "March", "April", "May", "June",
"July" ],
datasets: [
{
label: false,
data: [ 16, 32, 18, 26, 42, 33, 44 ]
}
]
},
options:
{
responsive: true,
tooltips:
{
callbacks:
{
label: function(tooltipItem, data) {
//this is working
alert( data['datasets'][0]['data'][tooltipItem['index']]);
//this is not working
$("#myDiv").text(data['datasets'][0]['data']
[tooltipItem['index']]);
return data['datasets'][0]['data'][tooltipItem['index']];
},
}
}
}
});
</script>

I managed to alert the label or the value using the alert(label)
function. but when I use the $('#mydiv').text(label) function, It does
not work.
I ran your code and it works perfectly so one possible reason why it's not working on your side is that you didn't import jQuery in your code.
var ctx = document.getElementById("widgetChart4");
ctx.height = 50;
ctx.width = 250;
var myChart = new Chart(ctx, {
type: 'bar',
data: {
labels: ["January", "February", "March", "April", "May", "June",
"July"
],
datasets: [{
label: false,
data: [16, 32, 18, 26, 42, 33, 44]
}]
},
options: {
responsive: true,
tooltips: {
callbacks: {
label: function(tooltipItem, data) {
$('#myDiv').html(data['datasets'][0]['data']
[tooltipItem['index']]);
return data['datasets'][0]['data'][tooltipItem['index']];
},
}
}
}
});
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/Chart.js/2.7.3/Chart.min.js"></script>
<canvas id="widgetChart4"></canvas>
<div id="myDiv"></div>

Related

chartjs Show tooltip automatically

I create charts for weather. I want to show automatically the tooltip on the last datapoint, when the chart is created. When the mouse is moved to another datapoint, the tootip should move to the new datapoint of the mouse or vanish if the mouse is outside.
https://www.chartjs.org/docs/3.8.0/samples/advanced/programmatic-events.html ist very close. Thanks!
function triggerTooltip(chart) {
const tooltip = chart.tooltip;
if (tooltip.getActiveElements().length > 0)
{ tooltip.setActiveElements([], {x: 0, y: 0}); }
else {
const chartArea = chart.chartArea;
tooltip.setActiveElements([
{
datasetIndex: 0,
index: 0,
}, {
datasetIndex: 1,
index: 0,
}],
{ x: (chartArea.left + chartArea.right) / 2,
y: (chartArea.top + chartArea.bottom) / 2, });
}
chart.update(); }
I did expect that the index controlls the bar, for the tooltip. But it makes no difference, whatever Index is set.
Also when I change x,y it is still on the same place (close to 3rd bar).
enter image description here
This can be done with the Plugin Core API in the afterDatasetUpdate hook as follows:
afterDatasetUpdate: chart => {
if (!chart.tooltip.getActiveElements().length) {
chart.tooltip.setActiveElements([{
datasetIndex: 0,
index: chart.data.datasets[0].data.length - 1
}]);
chart.update();
}
}
Please take a look at the runnable code snippet below and see how it works.
new Chart('myChart', {
type: 'line',
plugins: [{
afterDatasetUpdate: chart => {
if (!chart.tooltip.getActiveElements().length) {
chart.tooltip.setActiveElements([{
datasetIndex: 0,
index: chart.data.datasets[0].data.length - 1
}]);
chart.update();
}
}
}],
data: {
labels: ["January", "February", "March", "April", "May", "June", "July"],
datasets: [{
label: '# of Events',
data: [65, 59, 80, 81, 56, 55, 68],
borderColor: '#a00'
}]
}
});
<script src="https://cdnjs.cloudflare.com/ajax/libs/Chart.js/3.7.1/chart.min.js"></script>
<canvas id="myChart" width="400" height="95"></canvas>
thanks - it is exactly, what I am looking for!
The snippet in your answer works with visible tooltip on the last data point.
When I try it in test.html in my browser (I tested firefox, edge,chrome) the tooltip is not visible.
Where is the mistake in my test.html?
<!DOCTYPE html>
<html>
<body>
<script src="https://cdnjs.cloudflare.com/ajax/libs/Chart.js/3.7.1/chart.min.js"></script>
<canvas id="myChart" width="400" height="95"></canvas>
<script type="text/javascript">
new Chart('myChart', {
type: 'line',
plugins: [{
afterDatasetUpdate: chart => {
if (!chart.tooltip.getActiveElements().length) {
chart.tooltip.setActiveElements([{
datasetIndex: 0,
index: chart.data.datasets[0].data.length - 1
}]);
chart.update();
}
}
}],
data: {
labels: ["January", "February", "March", "April", "May", "June", "July"],
datasets: [{
label: '# of Events',
data: [65, 59, 80, 20, 81, 56, 55, 68],
borderColor: '#a00'
}]
}
});
</script>
</body>
</html>
that is my test:
https://www.zebrafell.de/test.html

Chart.js v2: How to make tooltips always appear on line chart?

I have searched through for the solution but I have found solution to pie charts only. For example this one : Chart.js v2: How to make tooltips always appear on pie chart?
I just want make the tooltip visible without hovering. I have tried registering new pluginService but its not working and its producing this error
Uncaught TypeError: Cannot read property 'call' of undefined
this is what I have so far
Chart.pluginService.register({
beforeRender: function (chart) {
if (chart.config.options.showAllTooltips) {
// create an array of tooltips
// we can't use the chart tooltip because there is only one tooltip per chart
chart.pluginTooltips = [];
chart.config.data.datasets.forEach(function (dataset, i) {
chart.getDatasetMeta(i).data.forEach(function (sector, j) {
chart.pluginTooltips.push(new Chart.Tooltip({
_chart: chart.chart,
_chartInstance: chart,
_data: chart.data,
_options: chart.options,
_active: [sector]
}, chart));
});
});
// turn off normal tooltips
chart.options.tooltips.enabled = false;
}
},
afterDraw: function (chart, easing) {
if (chart.config.options.showAllTooltips) {
// we don't want the permanent tooltips to animate, so don't do anything till the animation runs atleast once
if (!chart.allTooltipsOnce) {
if (easing !== 1)
return;
chart.allTooltipsOnce = true;
}
// turn on tooltips
chart.options.tooltips.enabled = true;
Chart.helpers.each(chart.pluginTooltips, function (tooltip) {
tooltip.initialize();
tooltip.update();
// we don't actually need this since we are not animating tooltips
tooltip.pivot();
tooltip.transition(easing).draw();
});
chart.options.tooltips.enabled = false;
}
}
})
var myChart = new Chart(ctx, {
type: 'line',
data: {
labels: ["January", "February", "March", "April", "May", "June", "July"],
datasets: [{
label: "My First dataset",
fillColor: "rgba(220,220,220,0.2)",
strokeColor: "rgba(220,220,220,1)",
pointColor: "rgba(220,220,220,1)",
pointStrokeColor: "#fff",
pointHighlightFill: "#fff",
pointHighlightStroke: "rgba(220,220,220,1)",
data: [65, 59, 80, 81, 56, 55, 40]
}]
},
options: {
scales: {
yAxes: [{
ticks: {
beginAtZero: true
}
}]
},
showAllTooltips: true
}
});
appreciate any helps tq
When using the latest stable version of Chart.js (2.9.3), it works with the following changes.
Instead of Chart.pluginService.register, use Chart.plugin.register
Instead of change _options : chart.options write _options : chart.options.tooltips
Please have a look at your amended code below.
Chart.plugins.register({
beforeRender: function(chart) {
if (chart.config.options.showAllTooltips) {
// create an array of tooltips,
// we can't use the chart tooltip because there is only one tooltip per chart
chart.pluginTooltips = [];
chart.config.data.datasets.forEach(function(dataset, i) {
chart.getDatasetMeta(i).data.forEach(function(sector, j) {
chart.pluginTooltips.push(new Chart.Tooltip({
_chart: chart.chart,
_chartInstance: chart,
_data: chart.data,
_options: chart.options.tooltips,
_active: [sector]
}, chart));
});
});
chart.options.tooltips.enabled = false; // turn off normal tooltips
}
},
afterDraw: function(chart, easing) {
if (chart.config.options.showAllTooltips) {
if (!chart.allTooltipsOnce) {
if (easing !== 1) {
return;
}
chart.allTooltipsOnce = true;
}
chart.options.tooltips.enabled = true;
Chart.helpers.each(chart.pluginTooltips, function(tooltip) {
tooltip.initialize();
tooltip.update();
tooltip.pivot();
tooltip.transition(easing).draw();
});
chart.options.tooltips.enabled = false;
}
}
});
new Chart("chart", {
type: 'line',
data: {
labels: ["January", "February", "March", "April", "May", "June", "July"],
datasets: [{
label: "My First dataset",
fillColor: "rgba(220,220,220,0.2)",
strokeColor: "rgba(220,220,220,1)",
pointColor: "rgba(220,220,220,1)",
pointStrokeColor: "#fff",
pointHighlightFill: "#fff",
pointHighlightStroke: "rgba(220,220,220,1)",
data: [65, 59, 80, 81, 56, 55, 40]
}]
},
options: {
scales: {
yAxes: [{
ticks: {
beginAtZero: true
}
}]
},
showAllTooltips: true
}
});
<script src="https://cdnjs.cloudflare.com/ajax/libs/Chart.js/2.9.3/Chart.min.js"></script>
<canvas id="chart" height="100"></canvas>

How to add x axis from the line in bar line chart?

I have created a bar/line chart. See below:
The bar and the line are on different scales, namely: kilo's and euro's . Therefore, I want to show on the right side of the graph the xAxis scale of the line (euros). Is it also possible to add a label to the axes?
https://jsfiddle.net/qrwvvtxs/
var barChartData = {
labels: ["January", "February", "March", "April", "May", "June", "July"],
datasets: [{
label: 'Dataset 1',
yAxisID: "y-axis-1",
data: [3,2,7,4,5,7,6]
}, {
type: "line",
fill: false,
label: 'Dataset 2',
borderColor: '#faa',
backgroundColor: "#faa",
yAxisID: "y-axis-2",
data: [11,13,21,13,16,21,18]
}]
};
var ctx = document.getElementById("canvas").getContext("2d");
window.myBar = new Chart(ctx, {
type: 'bar',
data: barChartData,
options: {
responsive: true,
title:{
display:true,
text:"Chart.js Bar Chart - Multi Axis"
},
tooltips: {
mode: 'index',
intersect: true
},
scales: {
yAxes: [{
display: true,
position: "left",
id: "y-axis-1",
ticks: {
callback: function(value, index, values) {
return value + " Kg";
}
}
}, {
display: true,
position: "right",
id: "y-axis-2",
gridLines: {
drawOnChartArea: false
},
ticks: {
callback: function(value, index, values) {
return "€ " + value;
}
}
}],
}
}
});
.wrapper {
width: 100%;
}
<script src="https://cdnjs.cloudflare.com/ajax/libs/Chart.js/2.6.0/Chart.bundle.min.js"></script>
<div class="wrapper">
<canvas id="canvas"></canvas>
</div>

Hide legends in Chartjs

I want to hide legends in Chart.js in label and tooltips.
I am using v2.5.0
I am trying this way but its not hiding legend in tooltips
<canvas id="myChart" width="400" height="250"></canvas>
<script src="https://cdnjs.cloudflare.com/ajax/libs/Chart.js/2.5.0/Chart.min.js"></script>
<script>
window.onload = function(e){
var ctx = document.getElementById("myChart").getContext("2d");
var data = {
labels: ["January", "February", "March", "April", "May", "June1", "July"],
datasets: [
{
fill: false,
lineTension: 0.3,
pointRadius: 15,
pointHitRadius: 15,
pointHoverRadius: 15,
data: [65, 59, 80, 81, 56, 55, 40],
spanGaps: false,
}
]
};
var options={
legend: {
display: false
},
tooltips: {
callbacks: {
label: function(tooltipItem, data) {
return tooltipItem.yLabel;
}
}
}
};
var myLineChart = new Chart(ctx, {
type: 'line',
data: data,
options: options
});
}
</script>
jsfiddle
I have also tried in global values like this
Chart.defaults.global.legend= false;
But legends are still shown in tooltips, Please see and suggest any possible way to do this.
Thanks
I found the solution by adding displayColors:false in tooltips option like this
tooltips: {
displayColors:false,
callbacks: {
label: function(tooltipItem) {
return tooltipItem.yLabel;
}
}
}
Now the legend are not shown, I hope it helps someone with similar issue.

Chartjs change grid line color

First I don't know what's it called. But how do you change its color from gray to white? Or is it even possibe?
It is possible to either remove the grid lines or have them display in a different color.
In both options.scales.xAxes and options.scales.yAxes you can add
gridLines: {
display: false ,
color: "#FFFFFF"
},
(obviously you do not need to assign a colour if you are not disaplying them)
var chartColors = {
red: 'rgb(255, 99, 132)',
orange: 'rgb(255, 159, 64)',
yellow: 'rgb(255, 205, 86)',
green: 'rgb(75, 192, 192)',
blue: 'rgb(54, 162, 235)',
purple: 'rgb(153, 102, 255)',
grey: 'rgb(231,233,237)'
};
var randomScalingFactor = function() {
return (Math.random() > 0.5 ? 1.0 : -1.0) * Math.round(Math.random() * 100);
}
var MONTHS = ["January", "February", "March", "April", "May", "June", "July", "August", "September", "October", "November", "December"];
var config = {
type: 'line',
data: {
labels: ["January", "February", "March", "April", "May", "June", "July"],
datasets: [{
label: "My First dataset",
backgroundColor: chartColors.red,
borderColor: chartColors.red,
data: [
randomScalingFactor(),
randomScalingFactor(),
randomScalingFactor(),
randomScalingFactor(),
randomScalingFactor(),
randomScalingFactor(),
randomScalingFactor()
],
fill: false,
}, {
label: "My Second dataset",
fill: false,
backgroundColor: chartColors.blue,
borderColor: chartColors.blue,
data: [
randomScalingFactor(),
randomScalingFactor(),
randomScalingFactor(),
randomScalingFactor(),
randomScalingFactor(),
randomScalingFactor(),
randomScalingFactor()
],
}]
},
options: {
responsive: true,
title: {
display: true,
text: 'Chart.js Line Chart'
},
tooltips: {
mode: 'label',
},
hover: {
mode: 'nearest',
intersect: true
},
scales: {
xAxes: [{
display: true,
gridLines: {
display: false
},
scaleLabel: {
display: true,
labelString: 'Month'
}
}],
yAxes: [{
display: true,
gridLines: {
display: false
},
scaleLabel: {
display: true,
labelString: 'Value'
}
}]
}
}
};
var ctx = document.getElementById("canvas").getContext("2d");
window.myLine = new Chart(ctx, config);
<script src="https://cdnjs.cloudflare.com/ajax/libs/Chart.js/2.2.1/Chart.js"></script>
<div style="width:100%;">
<canvas id="canvas"></canvas>
</div>
Since v3 the scales have been changed so if you want your gridlines to have a different color you will need to configure it in options.scales[scaleID].grid.color:
var options = {
type: 'line',
data: {
labels: ["Red", "Blue", "Yellow", "Green", "Purple", "Orange"],
datasets: [{
label: '# of Votes',
data: [12, 19, 3, 5, 2, 3],
borderColor: 'pink'
},
{
label: '# of Points',
data: [7, 11, 5, 8, 3, 7],
borderColor: 'orange'
}
]
},
options: {
scales: {
y: {
grid: {
color: 'white'
}
},
x: {
grid: {
color: 'red'
}
}
}
}
}
var ctx = document.getElementById('chartJSContainer').getContext('2d');
new Chart(ctx, options);
<body>
<canvas id="chartJSContainer" width="600" height="400"></canvas>
<script src="https://cdnjs.cloudflare.com/ajax/libs/Chart.js/3.6.0/chart.js"></script>
</body>
Try this:
options: {
scales: {
x: {
display: true,
grid: {
display: false
},
},
y: {
display: true,
grid: {
display: false
},
}
}
}