how to programmatically make a line chart point active/highlighted - javascript

I'm using chart.js 2.0 beta2 and have several line charts on a page and a slider. I'd like to highlight the data point on each line chart that matches the slider position (they all have the same number of points). I can't figure out how to easily make a point active in the code. Thanks for any tips.

SOLUTION FOR 2.0 BETA
Extend the chart controller of your choice, and fire off a simulated click event to show the tooltip. Here is some code that works for 2.0 (here is a fiddle):
var data = {
labels: ["January", "February", "March", "April", "May", "June", "July"],
datasets: [
{
label: "My First dataset",
fill: false,
backgroundColor: "rgba(220,220,220,0.2)",
borderColor: "rgba(220,220,220,1)",
borderCapStyle: 'butt',
borderDash: [],
borderDashOffset: 0.0,
borderJoinStyle: 'miter',
pointBorderColor: "rgba(220,220,220,1)",
pointBackgroundColor: "#fff",
pointBorderWidth: 1,
pointHoverRadius: 5,
pointHoverBackgroundColor: "rgba(220,220,220,1)",
pointHoverBorderColor: "rgba(220,220,220,1)",
pointHoverBorderWidth: 2,
tension: 0.1,
data: [65, 59, 80, 81, 56, 55, 40]
},
{
label: "My Second dataset",
fill: true,
backgroundColor: "rgba(220,220,220,0.2)",
borderColor: "rgba(220,220,220,1)",
pointBorderColor: "rgba(220,220,220,1)",
pointBackgroundColor: "#fff",
pointBorderWidth: 1,
pointHoverRadius: 5,
pointHoverBackgroundColor: "rgba(220,220,220,1)",
pointHoverBorderColor: "rgba(220,220,220,1)",
pointHoverBorderWidth: 2,
data: [28, 48, 40, 19, 86, 27, 90]
}
]
};
var options = {
responsive: false
};
Chart.helpers.extend(Chart.controllers.line.prototype, {
fireSliderEvent: function(point, canvas, boundingRect){
var mouseX = Math.round((boundingRect.left + point._view.x) / (boundingRect.right - boundingRect.left) * canvas.width / this.chart.chart.currentDevicePixelRatio);
var mouseY = Math.round((boundingRect.top + point._view.y) / (boundingRect.bottom - boundingRect.top) * canvas.height / this.chart.chart.currentDevicePixelRatio);
var oEvent = document.createEvent('MouseEvents');
oEvent.initMouseEvent('click', true, true, document.defaultView,
0, mouseX, mouseY, mouseX, mouseY,
false, false, false, false, 0, canvas);
canvas.dispatchEvent(oEvent);
},
highlightPoints: function(point){
var canvas = this.chart.chart.canvas;
var boundingRect = canvas.getBoundingClientRect();
var points = this.getDataset().metaData;
this.fireSliderEvent(points[point], canvas, boundingRect);
}
});
var ctx = $("#canvas");
var myLine = new Chart(ctx, {
type: 'line',
data: data,
options: options
});
var highlight = function(dataset, point){
myLine.data.datasets[dataset].controller.highlightPoints(point);
}
$("#slider").slider({
max: myLine.data.datasets[0].data.length-1,
slide: function( event, ui ) { highlight(0, ui.value); }
});
<link rel="stylesheet" href="https://ajax.googleapis.com/ajax/libs/jqueryui/1.11.4/themes/smoothness/jquery-ui.css">
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.0.0/jquery.min.js"></script>
<script src="https://ajax.googleapis.com/ajax/libs/jqueryui/1.11.4/jquery-ui.min.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/Chart.js/2.0.0-beta/Chart.js"></script>
<div id="slider" style="width: 500px;"></div>
<canvas id="canvas" height="300" width="500"></canvas>

SOLUTION FOR 1.x
You should extend the chart type and add your own method to select the point. Here is some code that will show the tooltip for each point depending on slider position:
var lineChartData = {
"datasets": [{
"data": [
"85",
"87",
"70",
"80",
"78",
"69",
"150",
"93",
"59",
"88"],
"pointStrokeColor": "#fff",
"fillColor": "rgba(220,220,220,0.5)",
"pointColor": "rgba(220,220,220,1)",
"strokeColor": "rgba(220,220,220,1)"
}],
"labels": [
"2013-01-01",
"2013-01-04",
"2013-01-15",
"2013-02-03",
"2013-03-25",
"2013-04-03",
"2013-04-14",
"2013-05-27",
"2013-05-27",
"2013-08-03"],
};
var options = {showTooltips: false};
Chart.types.Line.extend({
name: "LineAlt",
highlightPoints: function(datasetIndex, pointIndexArray){
var activePoints = [];
var points = this.datasets[datasetIndex].points;
for(i in pointIndexArray){
if(points[pointIndexArray[i]]){
activePoints.push(points[pointIndexArray[i]]);
}
}
this.showTooltip(activePoints);
}
});
var myLine = new Chart(document.getElementById("canvas").getContext("2d")).LineAlt(lineChartData, options);
var highlight = function(index){
myLine.highlightPoints(0, [index]);
}
$("#slider").slider({
max: lineChartData.datasets[0].data.length-1,
slide: function( event, ui ) { highlight(ui.value); },
});
<link rel="stylesheet" href="https://ajax.googleapis.com/ajax/libs/jqueryui/1.11.4/themes/smoothness/jquery-ui.css">
<script src="https://cdnjs.cloudflare.com/ajax/libs/Chart.js/1.0.2/Chart.js"></script>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.0.1/jquery.min.js"></script>
<script src="https://ajax.googleapis.com/ajax/libs/jqueryui/1.11.4/jquery-ui.min.js"></script>
<div id="slider" style="width: 500px;"></div>
<canvas id="canvas" height="300" width="500"></canvas>

First BIG THANKS to JstnPwll for amazing answer that helped me a lot!
The ChartJS API has changed a lot and 2.0 BETA does not work
I needed this in ReactJS and the complexity of "extend" coordinator
was beyond my competence
This simpler works for Chart.JS 2.9
In original point is sometimes number sometimes object
So I made explicit using suffix num to clarify usage
Simply call fireSliderEvent(2,5);
fireSliderEvent = (datasetnum,pointnum)=>{
let myLine=this.chartRef.current.chartInstance;
//console.log(JSON.stringify(JSON.decycle(this.chartRef.current),null,2));
var canvas = myLine.canvas;
var boundingRect = canvas.getBoundingClientRect();
var meta = myLine.getDatasetMeta(datasetnum);
// https://stackoverflow.com/questions/6157929/how-to-simulate-a-mouse-click-using-javascript
var mouseX = Math.round((boundingRect.left + meta.dataset._children[pointnum]._view.x) / (boundingRect.right - boundingRect.left) * canvas.width / myLine.currentDevicePixelRatio);
var mouseY = Math.round((boundingRect.top + meta.dataset._children[pointnum]._view.y) / (boundingRect.bottom - boundingRect.top) * canvas.height / myLine.currentDevicePixelRatio);
var oEvent = document.createEvent('MouseEvents');
oEvent.initMouseEvent('click', true, true, document.defaultView,
0, mouseX, mouseY, mouseX, mouseY,
false, false, false, false, 0, canvas);
canvas.dispatchEvent(oEvent);
}

Related

Display "Thresholds" as horizontal lines with label in Chart.js

I want to set maximum horizontal line in my chart like danger border line
In Above image, I have a line chart where I need to set horizontal line like blue color.
I have reviewed the ChartJS doc but not found any ref.
I have need to set same as below image
Consider this chart.js plugin
Courtesy of this link : http://www.java2s.com/example/javascript/chart.js/draw-horizontal-lines-in-chartjs.html
<html>
<head>
<meta name="viewport" content="width=device-width, initial-scale=1">
<script type="text/javascript" src="https://code.jquery.com/jquery-2.1.3.js"></script>
<script type="text/javascript" src="https://cdnjs.cloudflare.com/ajax/libs/Chart.js/2.1.6/Chart.bundle.min.js"></script>
<script type="text/javascript">
$(window).load(function(){//from www . j a va 2 s . c o m
var canvas = document.getElementById("myChart");
var ctx = canvas.getContext("2d");
var horizonalLinePlugin = {
afterDraw: function(chartInstance) {
var yScale = chartInstance.scales["y-axis-0"];
var canvas = chartInstance.chart;
var ctx = canvas.ctx;
var index;
var line;
var style;
if (chartInstance.options.horizontalLine) {
for (index = 0; index < chartInstance.options.horizontalLine.length; index++) {
line = chartInstance.options.horizontalLine[index];
if (!line.style) {
style = "rgba(169,169,169, .6)";
} else {
style = line.style;
}
if (line.y) {
yValue = yScale.getPixelForValue(line.y);
} else {
yValue = 0;
}
ctx.lineWidth = 3;
if (yValue) {
ctx.beginPath();
ctx.moveTo(0, yValue);
ctx.lineTo(canvas.width, yValue);
ctx.strokeStyle = style;
ctx.stroke();
}
if (line.text) {
ctx.fillStyle = style;
ctx.fillText(line.text, 0, yValue + ctx.lineWidth);
}
}
return;
};
}
};
Chart.pluginService.register(horizonalLinePlugin);
var data = {
labels: ["January", "February", "March", "April", "May", "June", "July"],
datasets: [{
label: "My First dataset",
fill: false,
lineTension: 0.1,
backgroundColor: "rgba(75,192,192,0.4)",
borderColor: "rgba(75,192,192,1)",
borderCapStyle: 'butt',
borderDash: [],
borderDashOffset: 0.0,
borderJoinStyle: 'miter',
pointBorderColor: "rgba(75,192,192,1)",
pointBackgroundColor: "#fff",
pointBorderWidth: 1,
pointHoverRadius: 5,
pointHoverBackgroundColor: "rgba(75,192,192,1)",
pointHoverBorderColor: "rgba(220,220,220,1)",
pointHoverBorderWidth: 2,
pointRadius: 1,
pointHitRadius: 10,
data: [65, 59, 80, 81, 56, 55, 40],
}]
};
var myChart = new Chart(ctx, {
type: 'line',
data: data,
options: {
"horizontalLine": [{
"y": 82,
"style": "rgba(255, 0, 0, .4)",
"text": "max"
}, {
"y": 60,
"style": "#00ffff",
}, {
"y": 44,
"text": "min"
}]
}
});
});
</script>
</head>
<body>
<canvas id="myChart" width="400" height="400"></canvas>
</body>
</html>

Chartjs real time graph x axis movement

I want to display a chart with Chartjs which displays real time data and slowly scrolls along the x axis, I have tried it here with js fiddle and it just jumps like crazy up and down: https://jsfiddle.net/rsnufpq7/
The graph should just move to the left side with the old points out of view without this animation like in the second example here: https://bost.ocks.org/mike/path/
var canvas = document.getElementById('myChart');
var data = {
labels: ["January", "February", "March", "April", "May", "June", "July"],
datasets: [
{
label: "My First dataset",
fill: false,
lineTension: 0.0,
backgroundColor: "rgba(75,192,192,0.4)",
borderColor: "rgba(75,192,192,1)",
borderCapStyle: 'butt',
borderDash: [],
borderDashOffset: 0.0,
borderJoinStyle: 'miter',
pointBorderColor: "rgba(75,192,192,1)",
pointBackgroundColor: "#fff",
pointBorderWidth: 1,
pointHoverRadius: 5,
pointHoverBackgroundColor: "rgba(75,192,192,1)",
pointHoverBorderColor: "rgba(220,220,220,1)",
pointHoverBorderWidth: 2,
pointRadius: 5,
pointHitRadius: 10,
data: [65, 59, 80, 0, 56, 55, 40],
}
]
};
var zero = 7;
function adddata(){
var value = Math.floor((Math.random() * 10) + 1);;
myLineChart.data.labels.push(zero);
myLineChart.data.labels.splice(0, 1);
myLineChart.data.datasets[0].data.splice(0, 1);
myLineChart.data.datasets[0].data.push(value);
myLineChart.update();
zero++;
}
setInterval(function(){
adddata();
},1000);
var option = {
showLines: true
};
var myLineChart = Chart.Line(canvas,{
data:data,
options:option
});
Your code works as expected, only thing that you are missing is your y axis does not have range defined and it is being dynamically adjusted.
In order to achieve this I have extended your options to look like this.
var option = {
showLines: true,
scales: {
yAxes: [{
display: true,
ticks: {
beginAtZero:true,
min: 0,
max: 100
}
}]
}
};
I have defined min and max value for y axis and it is not jumping anymore.
Here is a working fiddle

Adding Chart.js line chart to Jinja2/Flask html page from JS file

I have the following code in a simple Bootstrap html file which displays a Chart.js line chart.
<div class="card-block chartjs">
<canvas id="line-chart" height="500"></canvas>
</div>
The js file that contains the chart's setup looks like this:
$(window).on("load", function(){
var ctx = $("#line-chart");
var chartOptions = {
responsive: true,
maintainAspectRatio: false,
legend: {
position: 'bottom',
},
hover: {
mode: 'label'
},
scales: {
xAxes: [{
display: true,
gridLines: {
color: "#f3f3f3",
drawTicks: false,
},
scaleLabel: {
display: true,
labelString: 'Month'
}
}],
yAxes: [{
display: true,
gridLines: {
color: "#f3f3f3",
drawTicks: false,
},
scaleLabel: {
display: true,
labelString: 'Value'
}
}]
},
title: {
display: true,
text: 'Chart.js Line Chart - Legend'
}
};
var chartData = {
labels: ["January", "February", "March", "April", "May", "June", "July"],
datasets: [{
label: "My First dataset",
data: [65, 59, 80, 81, 56, 55, 40],
fill: false,
borderDash: [5, 5],
borderColor: "#9C27B0",
pointBorderColor: "#9C27B0",
pointBackgroundColor: "#FFF",
pointBorderWidth: 2,
pointHoverBorderWidth: 2,
pointRadius: 4,
}, {
label: "My Second dataset",
data: [28, 48, 40, 19, 86, 27, 90],
fill: false,
borderDash: [5, 5],
borderColor: "#00A5A8",
pointBorderColor: "#00A5A8",
pointBackgroundColor: "#FFF",
pointBorderWidth: 2,
pointHoverBorderWidth: 2,
pointRadius: 4,
}, {
label: "My Third dataset - No bezier",
data: [45, 25, 16, 36, 67, 18, 76],
lineTension: 0,
fill: false,
borderColor: "#FF7D4D",
pointBorderColor: "#FF7D4D",
pointBackgroundColor: "#FFF",
pointBorderWidth: 2,
pointHoverBorderWidth: 2,
pointRadius: 4,
}]
};
var config = {
type: 'line',
options : chartOptions,
data : chartData
};
var lineChart = new Chart(ctx, config);
});
I would like to avoid using a separated javascript file and rather just have everything in my Jinja2/Flask html page. A working example can be found in this tutorial, this is the same way that I would like to follow. I have tried to copy any paste the js part to my html page and put between <script> tags, but unfortunately it doesn't work.
Here is how I tried:
# in my jinja2/flask html page
<div class="card-body collapse in">
<div class="card-block chartjs">
<canvas id="line-chart" height="500"></canvas>
</div>
</div>
<script>
var ctx = $("#line-chart");
var chartOptions = {
responsive: true,
maintainAspectRatio: false,
legend: {
position: 'bottom',
},
hover: {
mode: 'label'
},
scales: {
xAxes: [{
display: true,
gridLines: {
color: "#f3f3f3",
drawTicks: false,
},
scaleLabel: {
display: true,
labelString: 'Month'
}
}],
yAxes: [{
display: true,
gridLines: {
color: "#f3f3f3",
drawTicks: false,
},
scaleLabel: {
display: true,
labelString: 'Value'
}
}]
},
title: {
display: true,
text: 'Chart.js Line Chart - Legend'
}
};
// Chart Data
var chartData = {
labels: ["January", "February", "March", "April", "May", "June", "July"],
datasets: [{
label: "My First dataset",
data: [65, 59, 80, 81, 56, 55, 40],
fill: false,
borderDash: [5, 5],
borderColor: "#9C27B0",
pointBorderColor: "#9C27B0",
pointBackgroundColor: "#FFF",
pointBorderWidth: 2,
pointHoverBorderWidth: 2,
pointRadius: 4,
}, {
label: "My Second dataset",
data: [28, 48, 40, 19, 86, 27, 90],
fill: false,
borderDash: [5, 5],
borderColor: "#00A5A8",
pointBorderColor: "#00A5A8",
pointBackgroundColor: "#FFF",
pointBorderWidth: 2,
pointHoverBorderWidth: 2,
pointRadius: 4,
}, {
label: "My Third dataset - No bezier",
data: [45, 25, 16, 36, 67, 18, 76],
lineTension: 0,
fill: false,
borderColor: "#FF7D4D",
pointBorderColor: "#FF7D4D",
pointBackgroundColor: "#FFF",
pointBorderWidth: 2,
pointHoverBorderWidth: 2,
pointRadius: 4,
}]
};
var config = {
type: 'line',
// Chart Options
options : chartOptions,
data : chartData
};
// Create the chart
var lineChart = new Chart(ctx, config);
});
</script>
Unfortunately I'm not so familiar with JS and don't have more ideas about what should I do to display the chart in my Flask app. What do I need to implement to make it work?
First make sure the required JS is referenced in your template (or the template it extends).
Assuming you serve it from static/js folder:
<head>
...
<script src='/static/js/Chart.bundle.min.js'></script>
...
</head>
Your script tag content looks mostly fine, just a little modification getting the context, and you appear to have a trailing }); that you need to remove:
<script>
// get context
var ctx = document.getElementById("line-chart").getContext("2d");
....
// Create the chart
var lineChart = new Chart(ctx, config);
// REMOVE THIS FROM THE END OF YOUR SCRIPT
//});
</script>
As bgse said in his answer you need to load library first. I suggest you use CDN as that way you don't need to download ChartJS library.
Secondly, you're writing some JS that may be executed before library is fetched to the page. So what would I add is:
<div class="card-body collapse in">
<div class="card-block chartjs">
<canvas id="line-chart" height="500"></canvas>
</div>
</div>
<script src="https://cdnjs.cloudflare.com/ajax/libs/Chart.js/2.6.0/Chart.min.js"></script>
<script src="https://code.jquery.com/jquery-3.2.1.min.js" integrity="sha256-hwg4gsxgFZhOsEEamdOYGBf13FyQuiTwlAQgxVSNgt4=" crossorigin="anonymous"></script>
<script>
$(document).ready(function(){
// Your JS code here
// ...
});
</script>
This way script code will execute when all JS is loaded.

drawing line chart with chartjs

I'm trying to draw a line chart with chartjs, but i can't get it working - keep getting 't is undefined' error.
here is my fiddle example: http://jsfiddle.net/6bjy9nxh/344/
can anyone figure out what im doing wrong here?
chartjs: http://www.chartjs.org/docs/#line-chart-example-usage
cdn: https://cdnjs.cloudflare.com/ajax/libs/Chart.js/1.0.2/Chart.min.js
html
<canvas id="myChart" width="500" height="350"></canvas>
javascript
var ctx = document.getElementById("myChart");
var data = {
labels: ["January", "February", "March", "April", "May", "June", "July"],
datasets: [
{
label: "My First dataset",
fill: false,
lineTension: 0.1,
backgroundColor: "rgba(75,192,192,0.4)",
borderColor: "rgba(75,192,192,1)",
borderCapStyle: 'butt',
borderDash: [],
borderDashOffset: 0.0,
borderJoinStyle: 'miter',
pointBorderColor: "rgba(75,192,192,1)",
pointBackgroundColor: "#fff",
pointBorderWidth: 1,
pointHoverRadius: 5,
pointHoverBackgroundColor: "rgba(75,192,192,1)",
pointHoverBorderColor: "rgba(220,220,220,1)",
pointHoverBorderWidth: 2,
pointRadius: 1,
pointHitRadius: 10,
data: [65, 59, 80, 81, 56, 55, 40],
}
]
};
var myLineChart = new Chart(ctx, {
type: 'line',
data: data,
});
You are including version 1, you need version 2 for Chart.js
https://cdnjs.cloudflare.com/ajax/libs/Chart.js/2.1.3/Chart.min.js
http://jsfiddle.net/x55sgzgf/

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