Chartjs Overlap click function doesnt work - chart.js

I have a simple line chart and I have problem when two or more points are too closer. The problem is: The tooltip show one point and the click function is for other point.
In this exemple you can see that when I click on the first point on the red line (value 2) the click event is for the black line (value 0)
Exemple:
https://codepen.io/ataufo/pen/NexppY
var canvas = document.getElementById("lineChart");
var ctx = canvas.getContext('2d');
var data = {
labels: ["Jan", "Feb", "Mar", "Apr", "May", "Jun", "Jul", "Aug", "Sep", "Oct", "Nov", "Dec"],
datasets: [{
label: "Stock A",
fill: false,
lineTension: 0.1,
backgroundColor: "rgba(225,0,0,0.4)",
borderColor: "red",
borderCapStyle: 'square',
pointBorderWidth: 0.1,
pointHoverRadius: 6,
pointHoverBorderWidth: 2,
pointRadius: 1,
data: [2, 59, 80, 81, 56],
spanGaps: false,
datalabels: {
enabled: true,
allowOverlap: true,
display: true,
listeners: {
click: function(context) {
alert(context.dataIndex + " Red line");
}
}
}
}, {
label: "Stock B",
fill: false,
lineTension: 0.1,
backgroundColor: "black",
borderColor: "black",
borderCapStyle: 'square',
pointBorderWidth: 0.1,
pointHoverRadius: 6,
pointHoverBorderWidth: 2,
pointRadius: 1,
data: [0, 20, 60, 95, 64],
spanGaps: false,
datalabels: {
enabled: true,
allowOverlap: true,
display: true,
listeners: {
click: function(context) {
alert(context.dataIndex + " Black Line");
}
}
}
}
]
};
// Chart declaration:
var myBarChart = new Chart(ctx, {
showTooltips: false,
type: 'line',
data: data
});
Does anyone have one idea to solve that?

You explicitly reference dataset 0. You need to pass the dataset index like so:
canvas.onclick = function(evt) {
var activePoints = myLineChart.getElementAtEvent(evt);
//console.log(activePoints);
if (activePoints[0]) {
var chartData = activePoints[0]['_chart'].config.data;
var idx = activePoints[0]['_index'];
var label = chartData.labels[idx];
// change the following line...
//var value = chartData.datasets[0].data[idx];
// to this:
var value = chartData.datasets[activePoints[0]._chart.tooltip._active[0]._datasetIndex].data[idx];
var url = "Mês:" + label + " Valor: " + value;
alert(url);
}
};
Edit: Fully working example.
var canvas = document.getElementById("lineChart");
var ctx = canvas.getContext('2d');
canvas.onclick = function(evt) {
var activePoints = myLineChart.getElementAtEvent(evt);
console.log(activePoints);
if (activePoints[0]) {
var chartData = activePoints[0]['_chart'].config.data;
var idx = activePoints[0]['_index'];
var label = chartData.labels[idx];
//var value = chartData.datasets[0].data[idx];
var value = chartData.datasets[activePoints[0]._chart.tooltip._active[0]._datasetIndex].data[idx];
var url = "Mês:" + label + " Valor: " + value;
alert(url);
}
};
var data = {
labels: ["Jan", "Feb", "Mar", "Apr", "May", "Jun", "Jul", "Aug", "Sep", "Oct", "Nov", "Dec"],
datasets: [{
label: "Stock A",
fill: false,
lineTension: 0.1,
backgroundColor: "rgba(225,0,0,0.4)",
borderColor: "red",
borderCapStyle: 'square',
pointBorderWidth: 0.1,
pointHoverRadius: 6,
pointHoverBorderWidth: 2,
pointRadius: 1,
data: [2, 59, 80, 81, 56],
spanGaps: false
}, {
label: "Stock B",
fill: false,
lineTension: 0.1,
backgroundColor: "black",
borderColor: "black",
borderCapStyle: 'square',
pointBorderWidth: 0.1,
pointHoverRadius: 6,
pointHoverBorderWidth: 2,
pointRadius: 1,
data: [0, 20, 60, 95, 64],
spanGaps: false
}
]
};
// Chart declaration:
var myLineChart = new Chart(ctx, {
type: 'line',
data: data,
options: {
tooltips: {
enabled: true
}
}
});
body{
background-color: #666;
}
#lineChart{
background-color: wheat;
}
<script src="https://cdnjs.cloudflare.com/ajax/libs/Chart.js/2.7.3/Chart.min.js"></script>
<div class="container">
<br />
<div class="row">
<div class="col-md-1"></div>
<div class="col-md-10">
<!-- Chart.js Canvas Tag -->
<canvas id="lineChart"></canvas>
</div>
<div class="col-md-1"></div>
</div>
</div>

Related

How can i change the every legend label font color using chart.js version 2.8.0 (spacial line chart)?

I am using Chart.js version 2.8.0. I have encountered a problem. The problem is that I have to change the color of the every legend label. How do I change the color of the every label in this version (2.8.0)
Note: (I have no way yo use latest version for this satiation)
data: {
labels: [
"Sep",
"oct",
"Nov",
"Dec",
2020,
"Feb",
"Mar",
"Apr",
"May",
"jun",
"Jul",
],
datasets: [
{
label: "Fees",
fill: true,
// backgroundColor: "#FCBB0A",
backgroundColor: "red",
pointBackgroundColor: "red",
borderColor: "red",
pointHighlightStroke: "red",
borderCapStyle: "butt",
stacked: true,
beginAtZero: true,
data: [-200, 200, -230, -100, -200, 190, 220, -350, 180, -200, 500],
},
{
label: "Interest",
fill: true,
// backgroundColor: "#FCBB0A",
backgroundColor: "green",
pointBackgroundColor: "green",
borderColor: "green",
pointHighlightStroke: "green",
borderCapStyle: "butt",
stacked: true,
beginAtZero: true,
data: [-200, 200, 230, -100, -200, 190, 220, 350, 180, -200, 0],
},
{
label: "Net Positive",
fill: true,
// backgroundColor: "#FCBB0A",
backgroundColor: "rgba(68,208,99,0.53)",
pointBackgroundColor: "rgba(68,208,99,0.53)",
borderColor: "rgba(68,208,99,0.53)",
pointHighlightStroke: "rgba(68,208,99,0.53)",
borderCapStyle: "butt",
stacked: true,
beginAtZero: true,
data: [-200, 200, 230, -100, -200, 190, 220, 350, 180, -200, 0],
},
{
label: "Net Negative",
fill: true,
// backgroundColor: "#FCBB0A",
backgroundColor: "rgba(243,86,86,0.53)",
pointBackgroundColor: "rgba(243,86,86,0.53)",
borderColor: "rgba(243,86,86,0.53)",
pointHighlightStroke: "rgba(243,86,86,0.53)",
borderCapStyle: "butt",
stacked: true,
beginAtZero: true,
data: [-200, 200, 230, -100, -200, 190, 220, 350, 180, -200, 0],
},
{
label: "Net Value",
fill: true,
// backgroundColor: "#FCBB0A",
backgroundColor: "rgba(86,170,243,0.53)",
pointBackgroundColor: "rgba(86,170,243,0.53)",
borderColor: "rgba(86,170,243,0.53)",
pointHighlightStroke: "rgba(86,170,243,0.53)",
borderCapStyle: "butt",
stacked: true,
beginAtZero: true,
data: [-200, 200, 230, -100, -200, 190, 220, 350, 180, -200, 0],
},
],
},
options: {
borderWidth: 0,
pointRadius: 0,
showPoints: false,
showLine: false,
stacked: true,
tooltips: {enabled: false},
responsive: true,
maintainAspectRatio: false,
line: {
borderWidth: 0,
showLine: false,
},
elements: {
point: {
radius: 0,
},
},
legend: {
position: "bottom",
align: "center",
labels: {
generateLabels: function(chart) {
let labels Chart.defaults.global.legend.labels.generateLabels(chart);
labels[0].fillStyle = 'blue';
labels[0].fontColor = '#666'
labels[0].strokeStyle = 'green'
labels[0].fontSize = 14
return labels;
}
}
},
animation: {
duration: 750,
},
},
But labels[0].fontColor = '#666' and labels[0].fontSize = 14 not working
How can solve this problem please help me anyone
Instead of trying to do it in the generateLabels part you need to set it as a property in the labels config like so:
options: {
legend: {
labels: {
fontColor: 'red'
}
}
}
Example:
var options = {
type: 'line',
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
}
]
},
options: {
legend: {
labels: {
fontColor: '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/2.8.0/Chart.js"></script>
</body>

Changing grid color in radar chart

//radar-chart
const data = {
labels: [
'Stick Slip',
'Whirl',
'Bit Balling',
'Bit Bounce',
'test'
],
datasets: [{
label: 'My First Dataset',
data: [0.2, 0.5, 0, 0, 1],
fill: true,
backgroundColor: 'rgba(255, 99, 132, 0.2)',
borderColor: 'rgb(255, 99, 132)',
pointBackgroundColor: 'rgb(255, 99, 132)',
pointBorderColor: '#fff',
pointHoverBackgroundColor: '#fff',
pointHoverBorderColor: 'rgb(255, 99, 132)'
},]
};
const config = {
maintainAspectRatio: false,
elements: {
line: {
borderWidth: 3,
}
},
scales: {
r: {
suggestedMin: 0,
suggestedMax: 1,
angleLines: {
color: 'red'
}
},
},
}
var ctx = document.getElementById('radar-chart-dysfunctions');
var myRadarChart = new Chart(ctx, {
type: 'radar',
data: data,
options: config,
});
How can I change the grey gridlines to another color?
This is my code: https://codepen.io/bahrikutlu/pen/QWdaEMp
I have found various solutions on Stack Overflow such as following but it does not work with version 3.0
With Chartjs Radar - how to modify the gray gridlines?
Thanks
You will have to edit the color of the grid in the scale option like the example below
var options = {
type: 'radar',
data: {
labels: ["Red", "Blue", "Yellow", "Green", "Purple", "Orange"],
datasets: [{
label: '# of Votes',
data: [12, 19, 3, 5, 2, 3],
borderWidth: 1
}]
},
options: {
scales: {
r: {
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.0.2/chart.js" integrity="sha512-n8DscwKN6+Yjr7rI6mL+m9nS4uCEgIrKRFcP0EOkIvzOLUyQgOjWK15hRfoCJQZe0s6XrARyXjpvGFo1w9N3xg==" crossorigin="anonymous"></script>
</body>

Y-Axis with different colors

I have tried to add different colors to the Y-axis but without success.
Is it possible to achive something like attached image shows?
In the chartjs-plugin-annotation plugin you can set the background but not scale colors.
Describing image
var config = {
type: 'line',
data: {
labels: ['January', 'February', 'March', 'April', 'May', 'June', 'July'],
datasets: [{
label: 'Dataset',
data: [1,2,3,4,5,6,7],
fill: false,
}]
},
options: {
responsive: true,
scales: {
yAxes: [{
display: true,
scaleLabel: {
display: true,
labelString: 'Colored scale'
},
gridLines: { color: ['rgba(255, 0, 0, 1)', 'rgba(0, 255, 0, 1)', 'rgba(0, 0, 255, 1)'] }
}]
}
}
};
window.onload = function () {
var ctx = document.getElementById('canvas').getContext('2d');
window.myLine = new Chart(ctx, config);
};
<!DOCTYPE html>
<head>
<script src="https://cdnjs.cloudflare.com/ajax/libs/Chart.js/2.3.0/Chart.bundle.min.js"></script>
</head>
<body>
<div style="width:75%;"><canvas id="canvas"></canvas></div>
</body>
In case you want the colored rectangles spread over the entire chart, you can draw individual boxes of different background color using chartjs-plugin-annotation.js.
new Chart(document.getElementById('canvas'), {
type: 'line',
data: {
labels: ['January', 'February', 'March', 'April', 'May', 'June', 'July'],
datasets: [{
label: 'Dataset',
data: [1, 2, 3, 4, 5, 6, 7],
fill: false,
backgroundColor: 'rgb(0, 0, 0)',
borderColor: 'rgb(0, 0, 0)'
}]
},
options: {
responsive: true,
scales: {
yAxes: [{
display: true,
scaleLabel: {
display: true,
labelString: 'Colored scale'
}
}]
},
annotation: {
annotations: [{
drawTime: "beforeDatasetsDraw",
type: "box",
xScaleID: "x-axis-0",
yScaleID: "y-axis-0",
yMin: 4.5,
yMax: 8,
backgroundColor: "rgba(255, 0, 0, 1)",
borderWidth: 0
},
{
drawTime: "beforeDatasetsDraw",
type: "box",
xScaleID: "x-axis-0",
yScaleID: "y-axis-0",
yMin: 3.5,
yMax: 4.5,
backgroundColor: "rgba(255, 165, 0, 1)",
borderWidth: 0
},
{
drawTime: "beforeDatasetsDraw",
type: "box",
xScaleID: "x-axis-0",
yScaleID: "y-axis-0",
xMin: 0,
xMax: 100,
yMin: 0,
yMax: 3.5,
backgroundColor: "rgba(50, 250, 50, 1)",
borderWidth: 0
}
]
}
}
});
<script src="https://cdnjs.cloudflare.com/ajax/libs/Chart.js/2.9.3/Chart.bundle.min.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/chartjs-plugin-annotation/0.5.7/chartjs-plugin-annotation.js"></script>
<canvas id="canvas" height="90">
You can draw individual boxes directly on the canvas using the Plugin Core API. The API offers a range of hooks that may be used for performing custom code.
In below code snippet, I use the beforeDraw hook to draw the rectangles of different background color each.
new Chart(document.getElementById('canvas'), {
type: 'line',
plugins: [{
beforeDraw: chart => {
var ctx = chart.chart.ctx;
var xAxis = chart.scales['x-axis-0'];
var yAxis = chart.scales['y-axis-0'];
ctx.save();
ctx.fillStyle = 'green';
ctx.beginPath();
var yGreen = yAxis.getPixelForValue(3.5);
ctx.fillRect(xAxis.left - 6, yGreen, 6, yAxis.bottom - yGreen);
ctx.stroke();
ctx.fillStyle = 'orange';
ctx.beginPath();
var yOrange = yAxis.getPixelForValue(4.5);
ctx.fillRect(xAxis.left - 6, yOrange, 6, yGreen - yOrange);
ctx.stroke();
ctx.fillStyle = 'red';
ctx.beginPath();
var yRed = yAxis.getPixelForValue(7);
ctx.fillRect(xAxis.left - 6, yRed, 6, yOrange- yRed);
ctx.stroke();
ctx.restore();
}
}],
data: {
labels: ['January', 'February', 'March', 'April', 'May', 'June', 'July'],
datasets: [{
label: 'Dataset',
data: [1, 2, 3, 4, 5, 6, 7],
fill: false
}]
},
options: {
responsive: true,
scales: {
yAxes: [{
gridLines: {
tickMarkLength: 15
},
ticks: {
padding: 6
},
scaleLabel: {
display: true,
labelString: 'Colored scale'
}
}]
}
}
});
<script src="https://cdnjs.cloudflare.com/ajax/libs/Chart.js/2.9.3/Chart.bundle.min.js"></script>
<canvas id="canvas" height="90">

Chartjs: Custom text on y axis at certain level

Is there any way to add a custom text to a certain level of the y axis of a chart created with Chartjs?
Something like this:
I've checked thick configuration options, but couldn't find anything that would result this kind of annotation.
Here is an example of what you can do using annotation plugin and custom drawing on canvas:
var data_set = [{x: 1, y: 12}, {x: 2, y: 3}, {x: 3, y: 2}, {x: 4, y: 1}, {x: 5, y: 8}, {x: 6, y: 8}, {x: 7, y: 2}, {x: 8, y: 2}, {x: 9, y: 3}, {x: 10, y: 5}, {x: 11, y: 11}, {x: 12, y: 1}];
var labels = ["JAN", "FEB", "MAR", "APR", "MAY", "JUN", "JUL", "AUG", "SEP", "OCT", "NOV", "DEC"];
var lines = [], id = 0;
var linesOn = false;
var data = {
labels: labels,
datasets: [{
label: "My First dataset",
backgroundColor: "rgba(5,215,2,0.2)",
borderColor: "rgba(5,215,2,1)",
borderWidth: 2,
hoverBackgroundColor: "rgba(5,215,2,0.4)",
hoverBorderColor: "rgba(5,215,2,1)",
data: data_set,
}]
};
addLine(7);
var option = {
legend: false,
title: {
display: true,
},
annotation: {
drawTime: "afterDraw",
annotations: lines
},
scales: {
xAxes: [{
id: 'x-axis',
type: 'linear',
position: 'bottom',
ticks: {
max: 12,
min: 1,
stepSize: 1,
callback: function(value, index, values) {
return data.labels[index];
}
}
}],
yAxes: [{
id: 'y-axis',
type: 'linear',
}],
},
animation: {
duration: 1,
onComplete: function () {
var ctx = this.chart.ctx;
console.log("onComplete", this,Chart.defaults.global)
ctx.font = Chart.helpers.fontString(Chart.defaults.global.defaultFontSize, Chart.defaults.global.defaultFontStyle, Chart.defaults.global.defaultFontFamily);
ctx.textAlign = "center";
ctx.textBaseline = "bottom";
var line = this.chart.annotation.elements.line1,
x = line._model.x1-15,
y = line._model.y1+5;
ctx.fillStyle = line.options.label.fontColor;
ctx.fillText("Y",x,y);
}
}
};
var myLineChart = Chart.Line('myChart', {
data: data,
options: option
});
function addLine(value) {
id++;
var ln = {
id: "line" + id,
type: "line",
mode: "horizontal",
scaleID: "y-axis",
value: value,
borderWidth: 2,
borderColor: "red",
label: {
enabled: false,
fontColor: "red",
}
};
lines.push(ln);
}
<script src="https://cdnjs.cloudflare.com/ajax/libs/Chart.js/2.7.1/Chart.bundle.min.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/chartjs-plugin-annotation/0.5.7/chartjs-plugin-annotation.min.js"></script>
<canvas id="myChart" width="400" height="400"></canvas>
In the example I disabled annotation label showing and added a custom label on yAxis (see animation.onComplete() handler).

ChartJS do not render any legend if the label is falsy

I am using ChartJS 2.4 and I want to predefine lots of settings in the datasets already. But use an empty data array and an undefined label. Now I want to stop ChartJS from rendering the legend which is then shown as "null" or "undefined". Later I am setting a proper label and start to push data to the dataSet and finally call update() on the chart which works fine.
Here is a basic fiddle with this code:
var data = {
labels: ["January", "February", "March", "April", "May", "June", "July"],
datasets: [
{
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: 5,
pointHitRadius: 10,
data: [],
}
]
};
var myLineChart = new Chart("myChart", {
type: "line",
data: data
});
setTimeout(function(){
data.datasets[0].label = "The Label"
data.datasets[0].data.push(10, 20)
myLineChart.update()
}, 2000)
I have tried to overwrite generateLabels but I had no luck with that. And the setting dateaset.hidden only strikes through the legend if true but not really "hides".
EDIT 1: On the other hand setting options.legend.display to false hides all the legends and for ever, this is also not what I need.
Let us create a plugin that, at the start of every update, decides whether to display the legend or not based on whether the label of the first dataset is (respectively) defined or not. The autoDisplayLegend chart option enables the plugin, if set to true.
A working fiddle is here. The code is also available below.
var autoDisplayLegendPlugin = {
// Called at start of update.
beforeUpdate: function(chartInstance) {
if (chartInstance.options.autoDisplayLegend) {
// The first (and, assuming, only) dataset.
var dataset = chartInstance.data.datasets[0];
if (dataset.label)
chartInstance.options.legend.display = true;
else
chartInstance.options.legend.display = false;
}
}
};
Chart.pluginService.register(autoDisplayLegendPlugin);
var data = {
labels: ["January", "February", "March", "April", "May", "June", "July"],
datasets: [{
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: 5,
pointHitRadius: 10,
data: [],
}]
};
var myLineChart = new Chart("myChart", {
type: "line",
data: data,
options: {
// Option to auto display the legend.
autoDisplayLegend: true
}
});
setTimeout(function() {
data.datasets[0].label = "The Label"
data.datasets[0].data.push(10, 20)
myLineChart.update()
}, 2000)
<script src="https://cdnjs.cloudflare.com/ajax/libs/Chart.js/2.4.0/Chart.bundle.js"></script>
<canvas id="myChart" width="400" height="250"></canvas>
if you want, you can delete the dataset so the legend will not display:
var autoDisplayLegendPlugin = {
beforeUpdate: function(chartInstance) {
if (chartInstance.canvas.id == 'chart6') {
// The first (and, assuming, only) dataset.
var dataset = chartInstance.data.datasets[2];
if (dataset.data.length != 0){ // delete only if there is no data in dataset
console.log(chartInstance);
chartInstance.options.legend.display = true;
}
else{
chartInstance.options.legend.display = true;
chartInstance.data.datasets.pop(); // if is the last datasets you don't want the legend to appear
}
}
}};
You can filter the labels and use that to remove a falsy text
const data = {
labels: ["January", "February", "March", "April", "May", "June", "July"],
datasets: [{
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: 5,
pointHitRadius: 10,
data: [],
}]
};
const myLineChart = new Chart("myChart", {
type: "line",
data: data,
options: {
plugins: {
legend: {
labels: {
filter: (legendItem) => (!!legendItem.text)
}
}
}
}
});
setTimeout(function() {
data.datasets[0].label = "The Label"
data.datasets[0].data.push(10, 20)
myLineChart.update()
}, 2000)
<script src="https://cdnjs.cloudflare.com/ajax/libs/Chart.js/3.7.1/chart.js"></script>
<canvas id="myChart" width="400" height="250"></canvas>
The main reason is ,it's showing
undefined
because you haven't defined the label property for your datasets.
datasets: [{
data: [1,2,6,3,8,9,5],
label:'your label',
borderColor: "red",
fill: false
}]