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

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>

Related

How to render tooltip text on a different div with 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>

Show only nth tick LINE on x-axis for Chart.js diagram

I've been searching for a solution to this for a while but am getting no nearer to a solution due to the mass of deleted documentation and hacky answers for previous versions of the library.
I'm working on a chart with ChartJS v2 with quarterly-month names along the x-axis, and I've set my labels so that only every 4th label is shown (i.e. one per year). The result is this:
However, I would like to have it such that the tick lines also only appear on every 4th x-axis entry at the same point as the labels. Is this possible?
My current script tag is as follows:
<script>
var ctx = document.getElementById("myChart").getContext('2d');
ctx.canvas.width = 600;
ctx.canvas.height = 420;
var myChart = new Chart(ctx, {
type: 'line',
data: {
< snipped for brevity >
},
options: {
tooltips: {
mode: 'index',
intersect: false
},
scales: {
xAxes: [{
ticks: {
userCallback: function(item, index) {
if (index%4) return "";
return item;
},
autoSkip: false
},
display: true
}],
yAxes: [{
ticks: {
beginAtZero:true
}
}]
}
}
});
</script>
Is this possible to achieve? Thanks in advance.
Replace your tick­'s userCallback function with the following ...
userCallback: function(item, index) {
if (!(index % 4)) return item;
}
Basically, you don't need to return any empty string for the label that you wish to hide. If you do not return anything (for the label you don't want), it won't draw any tick (as well as gridline) for that label.
ᴅᴇᴍᴏ
var ctx = document.getElementById("myChart").getContext('2d');
var myChart = new Chart(ctx, {
type: 'line',
data: {
labels: ['Jan', 'Feb', 'Mar', 'Apr', 'May', 'Jun', 'Jul', 'Aug', 'Sept'],
datasets: [{
label: 'Standard Rating',
data: [1, 2, 3, 4, 5, 6, 7, 8, 9],
backgroundColor: 'rgba(209, 230, 245, 0.5)',
borderColor: 'rgba(56, 163, 236, 1)',
borderWidth: 1
}]
},
options: {
responsive: false,
tooltips: {
mode: 'label',
intersect: false
},
scales: {
xAxes: [{
ticks: {
userCallback: function(item, index) {
if (!(index % 4)) return item;
},
autoSkip: false
}
}],
yAxes: [{
ticks: {
beginAtZero: true
}
}]
}
}
});
<script src="https://cdnjs.cloudflare.com/ajax/libs/Chart.js/2.5.0/Chart.min.js"></script>
<canvas id="myChart" width="350" height="200"></canvas>

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
},
}
}
}

Disable chartJS tool tip on one dataset only

Is there a way so that one can disable the tool tips on one dataset on a Chart JS Chart and leave the tool tips present on the other dataset. Here is my current code:
var data = {
labels: [' . $labels . '],
datasets: [
{
label: "Portfolio Performance",
fillColor: "rgba(0,0,220,0.2)",
strokeColor: "rgba(0,220,220,1)",
pointColor: "rgba(0,0,0,1)",
pointStrokeColor: "#fff",
pointHighlightFill: "#fff",
pointHighlightStroke: "rgba(220,220,220,1)",
data: [' . $values . ']
},
{
label: "Portfolio Expendature",
fillColor: "rgba(0,0,220,0)",
strokeColor: "rgba(0,0,0,1)",
pointColor: "rgba(0,0,0,0)",
pointStrokeColor: "rgba(0,0,220,0)",
pointHighlightFill: "rgba(0,0,220,0)",
pointHighlightStroke: "rgba(220,220,220,0)",
data: [4450000,4450000,4450000,4450000,4450000]
}
]
};
var option = {
tooltipTemplate: "<%if (label){%><%=label%>: <%}%><%= \'£\' + FormatNumberBy3(Number(value).toFixed(2), \'.\' , \',\') %>",
maintainAspectRatio: false,
bezierCurve: false,
responsive: true,
scaleLabel: "<%= \'£\' + FormatNumberBy3(Number(value), \'.\' , \',\') %>"
};
var ctx = document.getElementById("graph").getContext("2d");
var myLineChart = new Chart(ctx).Line(data, option);
You can use custom tooltips to do this (basically you use an HTML element instead of using the canvas to render the tooltip alone). See https://github.com/nnnick/Chart.js/blob/v1.0.2/samples/line-customTooltips.html for an example for line charts.
In your case, you can adjust the loop at https://github.com/nnnick/Chart.js/blob/v1.0.2/samples/line-customTooltips.html#L68 to exclude / include the datasets as you see fit.
I make use of the custom tooltip configuration to achieve this(here it hides datasets that doesn't have "Income" label):
this.myChart = new Chart(this.ctx, {
type: 'bar',
data: {
labels: labels,
datasets: [{
label: "Income",
data: data3
},
{
label: "Tax",
data: data1,
backgroundColor: "#3EAFD5"
},
{
label: "Expenses",
data: data2,
backgroundColor: "#D24B47"
}
]
},
options: {
responsive: true,
tooltips: {
custom: function(tooltipModel) {
if (tooltipModel.body && tooltipModel.body[0].lines && tooltipModel.body[0].lines[0].indexOf("Income") == -1) {
tooltipModel.opacity = 0;
}
}
}
}
}