Move tooltip further from data point for Chart.js? - javascript

I started messing with Chart.js today, and I'm really impressed so far by how easy it is to understand, even for a javascript beginner like myself.
I'm wanting to add some spacing horizontally between the tooltip and the data point on the graph. By default, the caret point touches the data point. I can't figure it out. I know there's a position option, but I don't quite get how it's used. I also tried using the tooltips: { x } option but no luck either. Guessing I'm misunderstanding what that is for.
Below is what I have so far for one chart...
Thanks, appreciate it!
//Global Chart.js options
Chart.defaults.global.defaultFontFamily = 'Lato';
Chart.defaults.global.elements.responsive = true;
Chart.defaults.global.tooltips.xPadding = 10;
Chart.defaults.global.tooltips.yPadding = 10;
Chart.defaults.global.tooltips.titleMarginBottom = 10;
Chart.defaults.global.tooltips.position = 'average';
//Individual chart config
var ctx = "myChart";
var myChart = new Chart(ctx, {
type: 'line',
options: {
title: {
display: true,
text: 'Precision-Recall Curve',
},
layout: {
padding: 32
},
tooltips: {
x: 20
},
},
data: {
labels: ['0%', '10%', '20%', '30%', '40%', '50%', '60%', '70%', '80%', '90%', '100%'],
datasets: [{
label: 'Precision',
data: [2, 42, 55, 50, 42, 38, 32, 24, 20, 18, 18],
borderColor: '#1abc9c',
backgroundColor: 'RGBA(26, 188, 156, .4)',
pointBorderColor: "#4BC0C0",
pointBackgroundColor: "#fff",
pointHitRadius: 10
}, {
label: 'Recall',
data: [2, 12, 24, 30, 39, 58, 70, 82, 86, 89, 93],
borderColor: '#34495e',
backgroundColor: 'RGBA(52, 73, 94, .3)',
pointBorderColor: "#34495e",
pointBackgroundColor: "#fff",
pointHitRadius: 10
}]
}
});
<div class="container">
<div>
<canvas id="myChart"></canvas>
</div>
</div>
<script src="https://cdnjs.cloudflare.com/ajax/libs/Chart.js/2.4.0/Chart.bundle.min.js"></script>

I have something close, tooltips can accept a position which is an alias for a function stored in Chart.Tooltip.positioners. This function returns the x and y position for the tooltip.
You can add a custom one to adjust the x at an offset.
The only issue is that by adjust the x the layout (left/right direction) of the tooltip can change meaning that even after working out if the tool tip is below half way or above half way bu adjusting the x it then switches its layout meaning on tooltip in the middle will look odd as it is offset in the wrong direction.
This could be fixed by knowing the width of the tooltip and taking this into account but looking through the data provided to the function this is not given.
Anyway leaving this as an answer it gets you most of the way there and you/someone might be able to figure out how to get rid of that annoying last part
//Global Chart.js options
Chart.defaults.global.defaultFontFamily = 'Lato';
Chart.defaults.global.elements.responsive = true;
Chart.defaults.global.tooltips.xPadding = 10;
Chart.defaults.global.tooltips.yPadding = 10;
Chart.defaults.global.tooltips.titleMarginBottom = 10;
Chart.defaults.global.tooltips.position = 'average';
//register custome positioner
Chart.Tooltip.positioners.custom = function(elements, position) {
if (!elements.length) {
return false;
}
var offset = 0;
//adjust the offset left or right depending on the event position
if (elements[0]._chart.width / 2 > position.x) {
offset = 20;
} else {
offset = -20;
}
return {
x: position.x + offset,
y: position.y
}
}
//Individual chart config
var ctx = "myChart";
var myChart = new Chart(ctx, {
type: 'line',
options: {
title: {
display: true,
text: 'Precision-Recall Curve',
},
layout: {
padding: 32
},
tooltips: {
//use our new custom position
position: 'custom'
},
},
data: {
labels: ['0%', '10%', '20%', '30%', '40%', '50%', '60%', '70%', '80%', '90%', '100%'],
datasets: [{
label: 'Precision',
data: [2, 42, 55, 50, 42, 38, 32, 24, 20, 18, 18],
borderColor: '#1abc9c',
backgroundColor: 'RGBA(26, 188, 156, .4)',
pointBorderColor: "#4BC0C0",
pointBackgroundColor: "#fff",
pointHitRadius: 10
}, {
label: 'Recall',
data: [2, 12, 24, 30, 39, 58, 70, 82, 86, 89, 93],
borderColor: '#34495e',
backgroundColor: 'RGBA(52, 73, 94, .3)',
pointBorderColor: "#34495e",
pointBackgroundColor: "#fff",
pointHitRadius: 10
}]
}
});
<div class="container">
<div>
<canvas id="myChart"></canvas>
</div>
</div>
<script src="https://cdnjs.cloudflare.com/ajax/libs/Chart.js/2.4.0/Chart.bundle.min.js"></script>

I think it's simpler by change the number of caretPadding. We can increase the distance from tooltip to data point by caretPadding
option: {
tooltip: {
caretPadding: 20,
}
}
caretPadding-image

Related

chart.js: Place tooltip for stacked bar charts on top of bar

When I have a bar in a simple bar chart, the tooltip is placed at the top of the bar:
If I hover on a stacked bar chart, the tooltip is placed on the average position:
Instead of this behaviour I want to place the tooltip always on the top for stacked bar charts (like it is for simple bar charts).
The only two options for configuring the position are average and nearest (https://www.chartjs.org/docs/latest/configuration/tooltip.html#position-modes).
I know there is the mentioned way of using Chart.Tooltip.positioners.custom, but on the one hand this would overwrite the behaviour for all charts (but I just need it for stacked bar charts) and on the other hand even if I could use that I have no clue how to get or calculate the top position of the chart bar.
So, is there a way to place the tooltip on top of the stacked bar? Thank you!
Thank you for replying, I found a way but its a hack and might not work for you. consider the following:
//register custom positioner
Chart.Tooltip.positioners.custom = function(elements, position) {
//debugger;
return {
x: position.x,
y: elements[0]._view.base - (elements[0].height() + elements[1].height())
}
}
//Individual chart config
var ctx = "myChart";
var myChart = new Chart(ctx, {
type: 'bar',
options: {
title: {
display: true,
text: 'Precision-Recall Curve',
},
layout: {
padding: 32
},
tooltips: {
mode: 'index',
intersect: true,
position: 'custom',
yAlign: 'bottom'
},
scales: {
xAxes: [{
stacked: true
}],
yAxes: [{
stacked: true
}]
}
},
data: {
labels: ['0%', '10%', '20%', '30%', '40%', '50%', '60%', '70%', '80%', '90%', '100%'],
datasets: [{
label: 'data1',
data: [5, 56, 90, 6, 42, 67, 32, 24, 20, 18, 56],
borderColor: '#1acc1c',
backgroundColor: 'rgba(26, 10, 55, .1)',
pointBorderColor: "#4Bd1C0",
pointBackgroundColor: "#fff",
pointHitRadius: 10
}, {
label: 'data2',
data: [2, 12, 24, 30, 39, 58, 10, 82, 34, 89, 5],
borderColor: '#34315a',
backgroundColor: 'rgba(132, 2, 34, .7)',
pointBorderColor: "#34495e",
pointBackgroundColor: "#fff",
pointHitRadius: 10
}]
}
});
<div class="container">
<div>
<canvas id="myChart"></canvas>
</div>
</div>
<script src="https://cdnjs.cloudflare.com/ajax/libs/Chart.js/2.4.0/Chart.bundle.min.js"></script>

How to fix the distance between horizontal points (x-axis) in chartJS

Problem: Hi all! i am using chart.js to draw the charts. chart is a dynamic sometimes shows 10 points and sometimes can be more than thousand i have applied a panel successfully so that my points can be shown at some distance to read them easily.
Right now i want to know if there is any option to set the distance between points in x-axis grid. right now it automatically adjust the points.
What i tried:
i tried to do the stepsize and scalewidth by searching other stackoverflow answers but did not succeed. Any kind of help would be much appreciated.
P.S: i m using chart.js2
This is my chartjs dataset
var data = {
labels: data.graph_date,
datasets: [
{
label: 'Assay Values',
fill: false,
lineTension: 0,
backgroundColor: "rgba(255, 0, 0,1)",
borderColor: "rgba(255, 0, 0,1)",
borderCapStyle: 'butt',
borderDash: [],
borderDashOffset: 0.0,
borderWidth: 1,
borderJoinStyle: 'miter',
pointBorderColor: "rgba(255, 0, 0,1)",
pointBackgroundColor: "#fff",
pointBorderWidth: 1,
pointHoverRadius: 5,
pointHoverBackgroundColor: "rgba(255, 0, 0,1)",
pointHoverBorderColor: "rgba(255, 0, 0,1)",
pointHoverBorderWidth: 2,
pointRadius: 1,
pointHitRadius: 10,
data: data.assay_value,
spanGaps: false
},var options = {
responsive: false,
title: {
display: true,
position: "top",
text: label,
fontSize: 18,
fontColor: "#111"
},
legend: {
display: true,
position: "bottom",
labels: {
fontColor: "#333",
fontSize: 16
}
},
tooltips: {
enabled: true,
mode: 'single',
callbacks: {
label: function(tooltipItems, data) {
var multistringText = ['Assay Value: '+tooltipItems.yLabel];
multistringText.push('Assigned Value: '+assigned_value[tooltipItems.index]);
multistringText.push('Sample ID: '+sample_id[tooltipItems.index]);
return multistringText;
}
}
},
scales:{
yAxes:[{
ticks:{
min:graph_min
}
}],
xAxes: [{
gridLines: {
display:false
}
}]
}
};
if(new_chart[ctx.canvas.id] != null)
new_chart[ctx.canvas.id].destroy();
new_chart[ctx.canvas.id] =new Chart(ctx, {
type: 'line',
data: data,
options: options
});
In x-axis there is data like this
[19-Aug-2015,21-Aug-2015,21-Aug-2015,21-Aug-2015,21-Aug-2015,22-Aug-2015,27-Aug-2015,29-Aug-2015,1-Sep-2015,2-Sep-2015,3-Sep-2015,]
in y-axis data is like this
[0.1,0.05,0.89,0.89,0.79,0.58,0.68,0.25,0.98]
The way to control distance between points it to set the X and Y axis with a min, max, and step size so that they never change regardless of the number of points that are in the chart.
Here is an example that sets the scales so that they will never change. Regardless of how many points appear on the chart everything will stay the same.
var ctx = document.getElementById("myChart");
var myChart = new Chart(ctx, {
type: 'line',
data: {
datasets: [{
label: 'Points',
data: [
{x: 0, y: 2},
{x: 1, y: 3},
{x: 2, y: 2},
{x: 1.02, y: 0.4},
{x: 0, y: -1}
],
backgroundColor: 'rgba(123, 83, 252, 0.8)',
borderColor: 'rgba(33, 232, 234, 1)',
borderWidth: 1,
fill: false,
showLine: false,
}],
},
options: {
title: {
display: true,
text: 'Chart.js - Fixed X and Y Axis',
},
scales: {
xAxes: [{
type: 'linear',
position: 'bottom',
ticks: {
min: -1,
max: 8,
stepSize: 1,
fixedStepSize: 1,
}
}],
yAxes: [{
ticks: {
min: -2,
max: 4,
stepSize: 1,
fixedStepSize: 1,
}
}]
}
}
});
Here is a codepen example that demonstrates what this looks like

Multiple bar widths in Chart.js bar chart

Is it possible to have different bar widths for different datasets? I have a couple datasets in one stack, and another dataset in its own stack. The single dataset should be narrower than the other stack
Example. Here I duplicated the left stack, resulting in it being twice the width of the right stack. This breaks certain effects, including nonzero borders
var data = {
labels: ["1", "2", "3", "4", "5"],
datasets: [
{
label: "d1",
backgroundColor: "rgba(182,127,0,1)",
borderColor: "rgba(117,61,41,1)",
borderWidth: 1,
data: [42, 78, 64, 90, 97],
stack: "s1"
},
{
label: "d2",
backgroundColor: "rgba(71,161,65,1)",
borderColor: "rgba(36,93,56,1)",
borderWidth: 1,
data: [27, 63, 46, 64, 43],
stack: "s1"
},
{
label: "d3",
backgroundColor: "rgba(255,141,106,1)",
borderColor: "rgba(99,60,32,1)",
borderWidth: 1,
data: [18, 50, 23, 83, 35],
stack: "s1"
},
{
label: "d1",
backgroundColor: "rgba(182,127,0,1)",
borderColor: "rgba(117,61,41,1)",
borderWidth: 1,
data: [42, 78, 64, 90, 97],
stack: "s1b"
},
{
label: "d2",
backgroundColor: "rgba(71,161,65,1)",
borderColor: "rgba(36,93,56,1)",
borderWidth: 1,
data: [27, 63, 46, 64, 43],
stack: "s1b"
},
{
label: "d3",
backgroundColor: "rgba(255,141,106,1)",
borderColor: "rgba(99,60,32,1)",
borderWidth: 1,
data: [18, 50, 23, 83, 35],
stack: "s1b"
},
{
label: "d4",
backgroundColor: "rgba(160,160,160,1)",
borderColor: "rgba(60,60,60,1)",
borderWidth: 1,
data: [152, 141, 170, 194, 128],
stack: "s2",
barPercentage: 0.3
}
]
};
var options = {
scales: {
xAxes: [{
categoryPercentage: 0.6,
barPercentage: 1
}]
},
legend: {
display: false
}
};
var barChart = new Chart($("#myChart"), {
type: 'bar',
data: data,
options: options
});
This actually is possible to do in chart.js, but the solution is a bit "hackish". The gist of it is that you can create a 2nd x axis scale and set the barThickness property to a value smaller than your other axis. Then you assign your dataset to this access and finally, set the scale display to false.
You end up with some datasets on 1 axis and another dataset on a different hidden axis. Everything else still works (no breaking effects like you mentioned in your question).
Here is what your options would look like.
var options = {
scales: {
xAxes: [{
categoryPercentage: 0.6,
barPercentage: 1,
}, {
id: 'x-axis-2',
type: 'category',
display: false,
categoryPercentage: 0.6,
barPercentage: 1,
barThickness: 20,
gridLines: {
offsetGridLines: true
}
}],
},
legend: {
display: false
}
};
You have to make sure you add xAxisID: 'x-axis-2' to whichever dataset you want to bind to the new axis.
Here is a codepen example demonstrating all of this.
You can even do this for a horizontal bar chart by changing the scales around. See this codepen example showing this.
The chart.js documentation shows a barThickness attribute available in the options for a chart, but no such option available at the data set level. I think you may be out of luck unless you want to create your own custom chart type.

Chart.js bar chart change the label position X-axis

I'm new to chart.js. I want to draw a bar chart with x axis label not centered, but in the place where two bars join.
This is what I need to create
https://i.imgsafe.org/12dcb3ea20.png
But in my current implementation (in the below image) labels are centered to the bar. I need the label to be in the middle place where two bars join like the above image.
https://i.imgsafe.org/12e75a5888.jpg
This is my code
window.onload = function() {
init();
};
function init() {
var ctx = $("#myChart").get(0).getContext("2d");
var data = {
labels: ["0%", "10%", "20%", "30%", "40%", "50%", "60%", "70%", "80%", "90%", "100%"],
datasets: [
{
label: "My First dataset",
fillColor : "rgba(0, 173, 165, 1)",
backgroundColor: "rgba(255,99,132,0.2)",
borderColor: "rgba(255,99,132,1)",
borderWidth: 1,
hoverBackgroundColor: "rgba(255,99,132,0.4)",
hoverBorderColor: "rgba(255,99,132,1)",
data: [5, 22, 30, 22, 26, 40, 60, 68, 40, 10],
}
]
};
var myNewChart = new Chart(ctx).Bar(data);
}
</script>
<div>
<section>
<article>
<canvas id="myChart" width="800" height="200">
</canvas>
</article>
</section>
</div>
Try to add these options :
options : {
scales : {
xAxes : [{
gridLines: {
offsetGridLines : true
}
}]
}
}

chartjs show dot point on hover over line chart

I am using Chartjs v.1.0.2 and trying to set a point dot only to appear on hover over chart. After it it should be removed. I have managed to show it, by changing the object value, but it is not fluid motion and it doesn't show point always. This also doesn't hide it on hover out.
How can it be fluid and hide when mouse is not over?
window.onload = function(){
var ctx = $("#chart1").get(0).getContext("2d");
var chart1 = new Chart(ctx).Line(data1, options);
$("#chart1").hover(function(e) {
var activeBars = chart1.getPointsAtEvent(e);
activeBars[0].display = true;
// console.log(activeBars[0]);
chart1.update();
});
};
var data1 = {
labels: ["January", "February", "March", "April", "May", "June", "July"],
datasets: [
{
label: "My First dataset",
fillColor: "rgba(95,186,88,0.7)",
strokeColor: "rgba(95,186,88,1)",
pointColor: "rgba(95,186,88,1)",
pointStrokeColor: "#fff",
pointHighlightFill: "#fff",
pointHighlightStroke: "rgba(220,220,220,1)",
data: [65, 59, 80, 81, 56, 55, 40]
}
]
};
var options = {
responsive: true,
bezierCurve : false,
scaleShowLabels: false,
scaleFontSize: 0,
pointDot : false,
scaleBeginAtZero: true,
scaleShowHorizontalLines: false,
scaleShowVerticalLines: true,
scaleGridLineColor : "rgba(232,232,232)",
showTooltips: true,
customTooltips: function (tooltip) {
var tooltipEl = $('#chartjs-tooltip');
if (!tooltip) {
tooltipEl.css({
opacity: 0
});
return;
}
tooltipEl.removeClass('above below');
tooltipEl.addClass(tooltip.yAlign);
// split out the label and value and make your own tooltip here
var parts = tooltip.text.split(":");
var innerHtml = '<span>' + parts[0].trim() + '</span> : <span><b>' + parts[1].trim() + '</b></span>';
tooltipEl.html(innerHtml);
tooltipEl.css({
opacity: 1,
left: tooltip.chart.canvas.offsetLeft + tooltip.x + 'px',
top: tooltip.chart.canvas.offsetTop + tooltip.y + 'px',
fontFamily: tooltip.fontFamily,
fontSize: tooltip.fontSize,
fontStyle: tooltip.fontStyle,
});
}
};
simplified fiddle
Tested with Chart.js v2.6.0
Global setting will do the trick:
Chart.defaults.global.hover.intersect = false;
Or directly in chart config:
options: {
hover: {
intersect: false;
}
}
And point settings for dataset.
initial color of the point should be transparent
hover color must be set to the desired color
e.g.
datasets: [{
label: 'My First dataset',
borderColor: 'rgb(255, 99, 132)',
backgroundColor: 'rgb(255, 99, 132)',
data: [10, 30, 46, 2, 8, 50, 0],
fill: false,
pointBorderColor: 'rgba(0, 0, 0, 0)',
pointBackgroundColor: 'rgba(0, 0, 0, 0)',
pointHoverBackgroundColor: 'rgb(255, 99, 132)',
pointHoverBorderColor: 'rgb(255, 99, 132)'}],...
window.onload = function() {
const mode = 'index';
const intersect = false;
const config = {
type: 'line',
data: {
labels: ['January', 'February', 'March', 'April', 'May', 'June', 'July'],
datasets: [{
label: 'My First dataset',
borderColor: 'rgb(255, 99, 132)',
backgroundColor: 'rgb(255, 99, 132)',
data: [10, 30, 46, 2, 8, 50, 0],
fill: false,
pointBorderColor: 'rgba(0, 0, 0, 0)',
pointBackgroundColor: 'rgba(0, 0, 0, 0)',
pointHoverBackgroundColor: 'rgb(255, 99, 132)',
pointHoverBorderColor: 'rgb(255, 99, 132)',
}, {
label: 'My Second dataset',
borderColor: 'rgb(54, 162, 235)',
backgroundColor: 'rgb(54, 162, 235)',
data: [7, 49, 46, 13, 25, 30, 22],
fill: false,
pointBorderColor: 'rgba(0, 0, 0, 0)',
pointBackgroundColor: 'rgba(0, 0, 0, 0)',
pointHoverBackgroundColor: 'rgb(54, 162, 235)',
pointHoverBorderColor: 'rgb(54, 162, 235)',
}]
},
options: {
responsive: true,
title: {
display: true,
text: 'Mode: index, intersect = false'
},
tooltips: {
mode: 'index',
intersect: intersect,
},
hover: {
mode: mode,
intersect: intersect
},
}
};
const ctx = document.getElementById('canvas').getContext('2d');
const chart = new Chart(ctx, config);
}
<canvas id="canvas"></canvas>
<script src="https://cdnjs.cloudflare.com/ajax/libs/Chart.js/2.6.0/Chart.min.js"></script>
Edit: The following solution is for Chart.js v1.0.2 (the latest version at the time this solution was proposed). Please refer to this answer which provides a solution for Chart.js v2.x.x.
I ran into a similar situation a while back and resolved this by making the default point dot "invisible" as follows:
setting pointDotRadius to 1
setting pointStrokeColor to white with the alpha set to 0
The two steps above make the default point dot very small, this, in combination with the transparent point stroke, makes the default point dot invisible. Now if we make the pointDotStrokeWidth large enough, we can achieve the desired hover effect. i.e.
set pointDotStrokeWidth to a larger value (I used 8)
set the desired values for pointColor, pointHighlightFill, pointHighlightStroke
[Note: the same effect can be achieved by making pointColor
transparent but if you are plotting multiple datasets, then the
tooltip wouldn't show the corresponding line color next to the data
value.]
Example below (or you can checkout this Fiddle: ChartJS - Show Points on Hover):
var data = {
labels: ["Point0", "Point1", "Point2", "Point3", "Point4"],
datasets: [
{
label: "My Chart",
fillColor: "rgba(87, 167, 134, 0.2)",
strokeColor: "rgba(87, 167, 134, 1)",
pointColor: "rgba(87, 167, 134, 1)",
pointStrokeColor: "rgba(255, 255, 255, 0)",
pointHighlightFill: "rgba(87, 167, 134, 0.7)",
pointHighlightStroke: "rgba(87, 167, 134, 1)",
data: [5, 39, 109, 19, 149]
}
]
};
var ctx = document.getElementById("my_chart").getContext("2d");
myChart = new Chart(ctx).Line(data, {
responsive : true,
bezierCurve: false,
datasetFill: true,
pointDotRadius: 1,
pointDotStrokeWidth: 8,
pointHitDetectionRadius: 20,
});
<script src="https://cdnjs.cloudflare.com/ajax/libs/Chart.js/1.0.2/Chart.min.js"></script>
<canvas id="my_chart"></canvas>
$("#chart1").mouseover(function(e) {
chart1.datasets[0].points[0].display = true;
chart1.update();
});
$("#chart1").mouseout(function(e) {
chart1.datasets[0].points[0].display = false;
chart1.update();
});
Try using mouseover and mouseout as shown below. Similarly you can also use mouseenter and mouseleave methods to handle events.
$("#chart1").mouseover(function(e) {
var activeBars = chart1.getPointsAtEvent(e);
activeBars[0].display = true;
chart1.update();
});
$("#chart1").mouseout(function(e) {
var activeBars = chart1.getPointsAtEvent(e);
activeBars[0].display = false;
chart1.update();
});
This is a six years old question but I think in 2022 we can use ChartJS version 4.0.1.
ChartJS supports interactions behavior, and they can be configured via interaction, hover or tooltips settings on the chart configuration.
For this we will use the hover setting and select the index mode. This mode finds an item at the same index. If the intersect setting is false the nearest item, in the x direction, is used to determine the index.
Here is a working snippet
const data = {
labels: ["Red", "Blue", "Yellow", "Green", "Purple", "Orange"],
datasets: [{
label: '# of Votes',
data: [12, 19, 3, 5, 2, 3],
borderWidth: 1
},
{
label: '# of Points',
data: [7, 11, 5, 8, 3, 7],
borderWidth: 1
}
]
}
const options = {
maintainAspectRatio: false,
elements: {
point: {
hoverRadius: 6,
},
},
hover: {
mode: 'index',
intersect: false,
},
}
const config = {
type: 'line',
data,
options,
}
const $chart = document.getElementById('chart')
const chart = new Chart($chart, config)
<div class="wrapper" style="width: 98vw; height: 180px">
<canvas id="chart"></canvas>
</div>
<script src="https://unpkg.com/chart.js#4.0.1/dist/chart.umd.js"></script>

Categories

Resources