I have a problem with Chart.js.
I want an an alert show me the ID value set in the dataset when I click on a point in the chart.
I have tried using getElementsAtEvent(evt);, but it doesn't work as I expected.
Can somebody help me? Thanks!
var ctx = document.getElementById("myChart");
var color = ["#ff6384", "#5959e6", "#2babab", "#8c4d15", "#8bc34a", "#607d8b", "#009688"];
var scatterChart = new Chart(ctx, {
type: 'line',
data: {
datasets: [{
label: 'Linea A',
backgroundColor: "transparent",
borderColor: color[1],
pointBackgroundColor: color[1],
pointBorderColor: color[1],
pointHoverBackgroundColor: color[1],
pointHoverBorderColor: color[1],
data: [{
x: "2014-09-02",
y: 90,
id: '1A'
}, {
x: "2014-11-02",
y: 96,
id: '2A'
}, {
x: "2014-12-03",
y: 97,
id: '3A'
}]
},
{
label: 'Linea B',
backgroundColor: "transparent",
borderColor: color[2],
pointBackgroundColor: color[2],
pointBorderColor: color[2],
pointHoverBackgroundColor: color[2],
pointHoverBorderColor: color[2],
data: [{
x: "2014-09-01",
y: 96,
id: "1B"
}, {
x: "2014-10-04",
y: 95.8,
id: "2B"
}, {
x: "2014-11-06",
y: 99,
id: "3B"
}]
}
]
},
options: {
title: {
display: true,
text: 'Polveri',
fontSize: 18
},
legend: {
display: true,
position: "bottom"
},
scales: {
xAxes: [{
type: 'time',
time: {
displayFormats: {
'millisecond': 'MM/YY',
'second': 'MM/YY',
'minute': 'MM/YY',
'hour': 'MM/YY',
'day': 'MM/YY',
'week': 'MM/YY',
'month': 'MM/YY',
'quarter': 'MM/YY',
'year': 'MM/YY',
},
tooltipFormat: "DD/MM/YY"
}
}]
}
}
});
document.getElementById("myChart").onclick = function(evt) {
var activePoints = scatterChart.getElementsAtEvent(evt);
var firstPoint = activePoints[1];
console.log(firstPoint._datasetIndex);
console.log(firstPoint._index);
var label = scatterChart.data.labels[firstPoint._index];
console.log(scatterChart.data.datasets[0].data[0].id);
var value = scatterChart.data.datasets[firstPoint._datasetIndex].data[firstPoint._index];
if (firstPoint !== undefined)
alert(label + ": " + value);
};
<script src="https://code.jquery.com/jquery-1.12.4.min.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/moment.js/2.29.0/moment.min.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/Chart.js/2.5.0/Chart.js">
</script>
<canvas id="myChart" width="400" height="100"></canvas>
You have to change your label variable assignment from,
var label = scatterChart.data.labels[firstPoint._index];
To,
var label = scatterChart.data.datasets[firstPoint._index].label;
And you may also need to change your alert statment as,
alert(label + ": " + value.x);
Here is the working DEMO: https://jsfiddle.net/dt6c9jev/
Hope this helps!.
You need to use the .getElementAtEvent() prototype method instead of .getElementsAtEvent(). The difference being the first only returns the single point that you clicked whereas the other returns all points at the X axis for that click.
Here is an example.
document.getElementById("canvas").onclick = function(evt) {
var activePoint = myLine.getElementAtEvent(event);
// make sure click was on an actual point
if (activePoint.length > 0) {
var clickedDatasetIndex = activePoint[0]._datasetIndex;
var clickedElementindex = activePoint[0]._index;
var label = myLine.data.labels[clickedElementindex];
var value = myLine.data.datasets[clickedDatasetIndex].data[clickedElementindex];
alert("Clicked: " + label + " - " + value);
}
};
You can see a demonstration at this codepen.
Related
I create a radar chart to display data which comes from my backend. The data is dynamic, but I would like to highlight the gridline at 60 as shown below. Does chartjs have any solution to achieve it?
const gray = "rgb(200, 200, 200)";
const color = Chart.helpers.color;
const config = {
type: 'radar',
data: {
labels: [['Eating', 'Dinner'], ['Drinking', 'Water'], 'Sleeping', ['Designing', 'Graphics'], 'Coding', 'Cycling', 'Running'],
datasets: [{
label: 'My dataset',
backgroundColor: color(gray).alpha(0.2).rgbString(),
borderColor: gray,
pointBackgroundColor: gray,
data: [
80,
90,
60,
65,
78,
97,
55
]
}]
},
options: {
scale: {
gridLines: {
circular: true,
color: [gray, gray, 'blue', gray, gray, gray, gray, gray, gray, gray]
},
ticks: {
beginAtZero: true,
stepsize: 20
},
}
}
};
window.onload = function () {
window.myRadar = new Chart(document.getElementById('chart'), config);
};
<body>
<canvas id="chart"></canvas>
<script src="https://cdnjs.cloudflare.com/ajax/libs/Chart.js/2.9.4/Chart.js" integrity="sha512-hZf9Qhp3rlDJBvAKvmiG+goaaKRZA6LKUO35oK6EsM0/kjPK32Yw7URqrq3Q+Nvbbt8Usss+IekL7CRn83dYmw==" crossorigin="anonymous"></script>
</body>
enter code hereSince your data is dynamic, you need to compute scale.gridLines.colors based on the data. This could be done as follows:
const data = [80, 90, 60, 65, 78, 97, 55];
const gridLinesStepSize = 20;
const highlightedGridLine = 60;
const gridLineColors = Array.from(Array(Math.ceil(Math.max(...data) / gridLinesStepSize) + 1).keys())
.map(n => n * 20)
.slice(1)
.map(v => v == highlightedGridLine ? 'blue' : gray);
Please take a look at your amended runnable code and see how it works.
const gray = "rgb(200, 200, 200)";
const color = Chart.helpers.color;
const data = [80, 90, 60, 65, 78, 97, 55];
const gridLinesStepSize = 20;
const highlightedGridLine = 60;
const gridLineColors = Array.from(Array(Math.ceil(Math.max(...data) / gridLinesStepSize) + 1).keys())
.map(n => n * 20)
.slice(1)
.map(v => v == highlightedGridLine ? 'blue' : gray);
new Chart('chart', {
type: 'radar',
data: {
labels: [
['Eating', 'Dinner'],
['Drinking', 'Water'], 'Sleeping', ['Designing', 'Graphics'], 'Coding', 'Cycling', 'Running'
],
datasets: [{
label: 'My dataset',
backgroundColor: color(gray).alpha(0.2).rgbString(),
borderColor: gray,
pointBackgroundColor: gray,
data: data
}]
},
options: {
scale: {
gridLines: {
circular: true,
color: gridLineColors
},
ticks: {
beginAtZero: true,
stepsize: gridLinesStepSize
}
}
}
});
<script src="https://cdnjs.cloudflare.com/ajax/libs/Chart.js/2.9.4/Chart.bundle.min.js"></script>
<canvas id="chart" height="120"></canvas>
How can I move my labels on my x axes in between another x axes label. Nothing seems to work and I was unable to find anything on the docs. Is there a workaround? I'm using line chart time series.
https://www.chartjs.org/samples/latest/scales/time/financial.html
Currently, with the code I have its generating the figure below:
var cfg = {
elements:{
point: {
radius: 4
}
},
data: {
datasets: [
{
label: 'vsy',
backgroundColor: color(window.chartColors.red).alpha(0.5).rgbString(),
borderColor: window.chartColors.red,
data: firstData,
type: 'line',
pointRadius: 2,
fill: false,
lineTension: 0,
borderWidth: 2
},
{
label: 'de vsy',
backgroundColor: color(window.chartColors.blue).alpha(0.5).rgbString(),
borderColor: window.chartColors.blue,
data: dataMaker(15),
type: 'line',
pointRadius: 2,
fill: false,
lineTension: 0,
borderWidth: 2
}
],
},
options: {
animation: {
duration: 0
},
scales: {
xAxes: [{
type: 'time',
distribution: 'series',
offset: true,
time: {
unit: 'month',
displayFormats: {
month: 'MMM'
}
},
ticks: {
autoSkip: true,
autoSkipPadding: 75,
sampleSize: 100
},
}],
yAxes: [{
gridLines: {
drawBorder: false
}
}]
},
tooltips: {
intersect: false,
mode: 'index',
}
}
};
This is what I have now:
I want the labels on the x-axis to be on center instead of below the y axis grid line.
Thanks to uminder, with his comment it solves the issue but now I have a conflicting tooltip which lie on a same grid. When I hover to april line first point it shows me mar 30 which lies just above it and vice versa.
I fixed it by changing the mode to nearest but why is it activating the another point?
The option you're looking for is offsetGridLines.
If true, grid lines will be shifted to be between labels.
xAxes: [{
...
gridLines: {
offsetGridLines: true
}
In most cases, this produces the expected result. Unfortunately it doesn't work for time axes as documented in Chart.js issue #403. Thanks to Antti Hukkanen, there exists a workaround.
Please have a look at below runnable code snippet to see how it works.
function generateData() {
var unit = 'day';
function randomNumber(min, max) {
return Math.random() * (max - min) + min;
}
function randomPoint(date, lastClose) {
var open = randomNumber(lastClose * 0.95, lastClose * 1.05).toFixed(2);
var close = randomNumber(open * 0.95, open * 1.05).toFixed(2);
return {
t: date.valueOf(),
y: close
};
}
var date = moment().subtract(1, 'years');
var now = moment();
var data = [];
for (; data.length < 600 && date.isBefore(now); date = date.clone().add(1, unit).startOf(unit)) {
data.push(randomPoint(date, data.length > 0 ? data[data.length - 1].y : 30));
}
return data;
}
var TimeCenterScale = Chart.scaleService.getScaleConstructor('time').extend({
getPixelForTick: function(index) {
var ticks = this.getTicks();
if (index < 0 || index >= ticks.length) {
return null;
}
// Get the pixel value for the current tick.
var px = this.getPixelForOffset(ticks[index].value);
// Get the next tick's pixel value.
var nextPx = this.right;
var nextTick = ticks[index + 1];
if (nextTick) {
nextPx = this.getPixelForOffset(nextTick.value);
}
// Align the labels in the middle of the current and next tick.
return px + (nextPx - px) / 2;
},
});
// Register the scale type
var defaults = Chart.scaleService.getScaleDefaults('time');
Chart.scaleService.registerScaleType('timecenter', TimeCenterScale, defaults);
var cfg = {
data: {
datasets: [{
label: 'CHRT - Chart.js Corporation',
backgroundColor: 'red',
borderColor: 'red',
data: generateData(),
type: 'line',
pointRadius: 0,
fill: false,
lineTension: 0,
borderWidth: 2
}]
},
options: {
animation: {
duration: 0
},
scales: {
xAxes: [{
type: 'timecenter',
time: {
unit: 'month',
stepSize: 1,
displayFormats: {
month: 'MMM'
}
},
gridLines: {
offsetGridLines: true
}
}],
yAxes: [{
gridLines: {
drawBorder: false
}
}]
},
tooltips: {
intersect: false,
mode: 'index'
}
}
};
var chart = new Chart('chart1', cfg);
<script src="https://cdnjs.cloudflare.com/ajax/libs/moment.js/2.18.1/moment.min.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/Chart.js/2.9.3/Chart.min.js"></script>
<canvas id="chart1" height="90"></canvas>
For chartJs v3 you can use offset property:
scales: {
x: {
grid: {
offset: true
}
},
...
}
I'm having some issues when trying to update a chart's data using $scope.
I know there's a function to update charts myChart.update(); but I can't get to update the char when I put it in a $scope.
The following code gets the chart's data and then tries to update the chart. The problem comes at $scope.lineChart.update();. It looks like chartjs can't detect any changes.
The following code is executed after triggering a select, so the chart has an initial data and the following code just tries to update it.
This does not work: $scope.lineChart.update();
$scope.getLineChartMaxData().then(function () {
$scope.getLineChartMinData().then(function () {
$scope.lineChart.update();
});
});
The chart function:
$scope.fillLineChart = function () {
console.log("FILLING LINE CHART");
const brandProduct = 'rgba(0,181,233,0.5)'
const brandService = 'rgba(0,173,95,0.5)'
var data1 = $scope.lineChartMaxWeekData;
var data2 = $scope.lineChartMinWeekData;
var maxValue1 = Math.max.apply(null, data1)
var maxValue2 = Math.max.apply(null, data2)
var minValue1 = Math.min.apply(null, data1)
var minValue2 = Math.min.apply(null, data2)
var maxValue;
var minValue;
if (maxValue1 >= maxValue2) {
maxValue = maxValue1;
} else {
maxValue = maxValue2;
}
if (minValue1 >= minValue2) {
minValue = minValue2;
} else {
minValue = minValue1;
}
$scope.minValue = minValue;
$scope.maxValue = maxValue;
var ctx = document.getElementById("recent-rep-chart");
if (ctx) {
ctx.height = 250;
$scope.lineChart = new Chart(ctx, {
type: 'line',
data: {
labels: $scope.lineChartMaxWeekLabels,
datasets: [{
label: 'Valor',
backgroundColor: brandService,
borderColor: 'transparent',
pointHoverBackgroundColor: '#fff',
borderWidth: 0,
data: data1
},
{
label: 'My Second dataset',
backgroundColor: brandProduct,
borderColor: 'transparent',
pointHoverBackgroundColor: '#fff',
borderWidth: 0,
data: data2
}
]
},
options: {
maintainAspectRatio: true,
legend: {
display: false
},
responsive: true,
scales: {
xAxes: [{
gridLines: {
drawOnChartArea: true,
color: '#f2f2f2'
},
ticks: {
fontFamily: "Poppins",
fontSize: 12
}
}],
yAxes: [{
ticks: {
beginAtZero: true,
maxTicksLimit: 5,
stepSize: 50,
max: maxValue,
fontFamily: "Poppins",
fontSize: 12
},
gridLines: {
display: true,
color: '#f2f2f2'
}
}]
},
elements: {
point: {
radius: 0,
hitRadius: 10,
hoverRadius: 4,
hoverBorderWidth: 3
}
}
}
});
}
};
UPDATE: $scope.lineChart.destroy(); works well, but I don't want to destroy the chart and build it again because it is built with another sizes.
I wanted to stream live data in the form of a chart. I'm new to Javascript, so I wanted to first experiment with the sample on this page.
https://web.archive.org/web/20211113012042/https://nagix.github.io/chartjs-plugin-streaming/latest/samples/charts/line-horizontal.html
The code is given as:
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(201, 203, 207)'
};
function randomScalingFactor() {
return (Math.random() > 0.5 ? 1.0 : -1.0) * Math.round(Math.random() * 100);
}
function onRefresh(chart) {
chart.config.data.datasets.forEach(function(dataset) {
dataset.data.push({
x: Date.now(),
y: randomScalingFactor()
});
});
}
var color = Chart.helpers.color;
var config = {
type: 'line',
data: {
datasets: [{
label: 'Dataset 1 (linear interpolation)',
backgroundColor: color(chartColors.red).alpha(0.5).rgbString(),
borderColor: chartColors.red,
fill: false,
lineTension: 0,
borderDash: [8, 4],
data: []
}, {
label: 'Dataset 2 (cubic interpolation)',
backgroundColor: color(chartColors.blue).alpha(0.5).rgbString(),
borderColor: chartColors.blue,
fill: false,
cubicInterpolationMode: 'monotone',
data: []
}]
},
options: {
title: {
display: true,
text: 'Line chart (hotizontal scroll) sample'
},
scales: {
xAxes: [{
type: 'realtime'
}],
yAxes: [{
scaleLabel: {
display: true,
labelString: 'value'
}
}]
},
tooltips: {
mode: 'nearest',
intersect: false
},
hover: {
mode: 'nearest',
intersect: false
},
plugins: {
streaming: {
duration: 20000,
refresh: 1000,
delay: 2000,
onRefresh: onRefresh
}
}
}
};
window.onload = function() {
var ctx = document.getElementById('myChart').getContext('2d');
window.myChart = new Chart(ctx, config);
};
document.getElementById('randomizeData').addEventListener('click', function() {
config.data.datasets.forEach(function(dataset) {
dataset.data.forEach(function(dataObj) {
dataObj.y = randomScalingFactor();
});
});
window.myChart.update();
});
var colorNames = Object.keys(chartColors);
document.getElementById('addDataset').addEventListener('click', function() {
var colorName = colorNames[config.data.datasets.length % colorNames.length];
var newColor = chartColors[colorName];
var newDataset = {
label: 'Dataset ' + (config.data.datasets.length + 1),
backgroundColor: color(newColor).alpha(0.5).rgbString(),
borderColor: newColor,
fill: false,
lineTension: 0,
data: []
};
config.data.datasets.push(newDataset);
window.myChart.update();
});
document.getElementById('removeDataset').addEventListener('click', function() {
config.data.datasets.pop();
window.myChart.update();
});
document.getElementById('addData').addEventListener('click', function() {
onRefresh(window.myChart);
window.myChart.update();
});
<head>
<script src="https://cdnjs.cloudflare.com/ajax/libs/moment.js/2.22.2/moment.min.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/Chart.js/2.7.2/Chart.min.js"></script>
<script src="https://github.com/nagix/chartjs-plugin-streaming/releases/download/v1.5.0/chartjs-plugin-streaming.min.js"></script>
</head>
<body>
<div>
<canvas id="myChart"></canvas>
</div>
<p>
<button id="randomizeData">Randomize Data</button>
<button id="addDataset">Add Dataset</button>
<button id="removeDataset">Remove Dataset</button>
<button id="addData">Add Data</button>
</p>
</body>
When I copy and paste it into jsfiddle, the first code snippet going into the Javascript section and the second going into the HTML section. However, nothing happens? Could someone explain why/help me edit it so that it works?
Note: the code above is not my own, it belongs to this guy
In JSFiddle, the load type is set to 'On Load' by default, so you cannot handle the load event. Setting the load type to 'No wrap - bottom of ' works (in the pop-up menu in the Javascript section).
Is it possible to change the dataset labels that show up in the tooltip for a bubble chart.js chart?
As it stands right now, the dataset is based off the x,y,r values, but I'd like to inject some additional content, so that instead of reading (5,55,27.5) it reads something like: (Day:5, Total:55). I'd like to leave off the radius of 27.5 in the tooltip.
Yes! It is possible.
To achieve that, you can use the following tooltip's label callback function :
tooltips: {
callbacks: {
label: function(t, d) {
return d.datasets[t.datasetIndex].label +
': (Day:' + t.xLabel + ', Total:' + t.yLabel + ')';
}
}
}
ᴡᴏʀᴋɪɴɢ ᴇxᴀᴍᴘʟᴇ
var chart = new Chart(ctx, {
type: 'bubble',
data: {
datasets: [{
label: 'Bubble',
data: [{
x: 5,
y: 55,
r: 27.5
}],
backgroundColor: 'rgba(0, 119, 290, 0.6)'
}]
},
options: {
tooltips: {
callbacks: {
label: function(t, d) {
return d.datasets[t.datasetIndex].label +
': (Day:' + t.xLabel + ', Total:' + t.yLabel + ')';
}
}
}
}
});
<script src="https://cdnjs.cloudflare.com/ajax/libs/Chart.js/2.6.0/Chart.min.js"></script>
<canvas id="ctx"></canvas>
The previous answer doesn't work as of Chart.JS V3 because of these changes:
https://github.com/chartjs/Chart.js/blob/master/docs/migration/v3-migration.md
The following code works in 4.1.1:
var chart = new Chart(ctx, {
type: 'bubble',
data: {
datasets: [{
label: 'Bubble',
data: [{
x: 5,
y: 55,
r: 27.5
}],
backgroundColor: 'rgba(0, 119, 290, 0.6)'
}]
},
options: {
plugins: {
tooltip: {
callbacks: {
label: function(item) {
return item.raw.r
}
}
}
}
}
});
<script src="https://npmcdn.com/chart.js#latest/dist/chart.umd.js"></script>
<canvas id="ctx"></canvas>