How to add on click event to chart js - javascript

Hello I have a question concerning js charts. I have already created one in django application and i want to generate a javascript alert by clicking a certain point in the chart.
How can the alert get the value of the point that i choose?
For example with the value 92 like what is shown in the figure below:

This can be done with an onClick even handler as follows:
onClick: (event, elements, chart) => {
if (elements[0]) {
const i = elements[0].index;
alert(chart.data.labels[i] + ': ' + chart.data.datasets[0].data[i]);
}
}
Please take a look at below runnable code and see how it works.
new Chart('myChart', {
type: 'line',
data: {
labels: ["January", "February", "March", "April", "May", "June", "July"],
datasets: [{
label: '# of Votes',
data: [65, 59, 80, 81, 56, 55, 40],
borderColor: '#a00'
}]
},
options: {
onClick: (event, elements, chart) => {
if (elements[0]) {
const i = elements[0].index;
alert(chart.data.labels[i] + ': ' + chart.data.datasets[0].data[i]);
}
}
}
});
<script src="https://cdnjs.cloudflare.com/ajax/libs/Chart.js/3.7.1/chart.min.js"></script>
<canvas id="myChart" width="400" height="95"></canvas>

Related

Dynamic Chart on Popover Error - Cannot Acquire Context

I am trying to create a chart js popover but I am getting the error:
Failed to create chart: can't acquire context from the given item
I think that this is probably happening because the canvas tag is created dynamically, but I am not sure how to fix it. Any ideas? This is the js code I am using:
$(function() {
$('[data-toggle="popover"]').popover({
html: true,
content: '<canvas id="myChart" width="400" height="400"></canvas>',
}).on('shown.bs.popover', function() {
new Chart($('#myChart'), {
// The type of chart we want to create
type: 'line',
// The data for our dataset
data: {
labels: ["January", "February", "March", "April", "May", "June", "July"],
datasets: [{
label: "My First dataset",
backgroundColor: 'rgb(255, 99, 132)',
borderColor: 'rgb(255, 99, 132)',
data: [0, 10, 5, 2, 20, 30, 45],
}]
},
// Configuration options go here
options: {}
});
});
HTML:
<button type="button" class="btn btn-lg btn-primary" data-toggle="popover" title="Good vs. Evil Winrate" data-placement="bottom">Who's Winning?</button>

ChartJS replay chart animation when called by show()

I have a page full of charts that automatically generates all charts available (because the default page is "All Charts"). In it, there's a select department tag that will hide all charts other than those owned by the selected department. Here's my code:
$(window).load(function(){
$('#department').change(function(){
active_department($(this).val());
});
function active_department(department){
for(var i = 0; i < dept['namedept'].length; i++){
if(department!='All'){
$('.'+dept['namedept'][i]).hide(500);
} else {
if(typeof rCharts[dept['namedept'][i]] != 'undefined'){
$('.'+dept['namedept'][i]).show(500);
} else {
$('.no-chart-'+dept['namedept'][i]).hide(500);
}
}
}
if(typeof rCharts[department] != 'undefined'){
$('.'+department).show(500);
} else {
$('.no-chart-'+department).hide(500);
}
}
});
I want ChartJS animation to re-appear every time I select a department. So far I've tried easing, onProgress, and jQuery animate. none's working. Is it possible to re-animate the chart? If so, how?
From this answer and from the lack of options available in the Docs, it looks like the only feasible options would be these hacks:
redraw the chart with JS using new Chart or
change some minor configuration, or recreate an instance of the chart data and then call the update() method.
e.g.: Call the data through a function, and when you want the animation to happen, call the same function again. Because it now has a new array (even though it's the same data), the chart re-animates.
<script src="https://cdnjs.cloudflare.com/ajax/libs/Chart.js/2.5.0/Chart.min.js"></script>
<button onclick="updateChart()">Update</button>
<canvas id="myChart"></canvas>
<script>
var ctx = document.getElementById('myChart').getContext('2d');
var chartData = {
type: 'line',
data: {
labels: ["January", "February", "March", "April", "May", "June", "July"],
datasets: createDataset()
}
};
var chart = new Chart(ctx, chartData);
function updateChart(){
chartData.data.datasets = createDataset()
chart.update();
}
function createDataset(){
return [{
label: "My First dataset",
backgroundColor: 'rgb(255, 99, 132)',
borderColor: 'rgb(255, 99, 132)',
data: [0, 10, 5, 2, 20, 30, 45],
fill: false
}];
}
//ignore next line, it's to deal with a bug from chartjs cdn on stackoverflow
console.clear();
</script>

Chart.js update function (chart,labels,data) will not update the chart

I cannot debug the following code. I would like to update chart data (not add on top; delete current data and add completely new dataset). (Not)Working example on codepen:
https://codepen.io/anon/pen/bvBxpr
var config = {
type: 'line',
data: {
labels: ["January", "February", "March", "April", "May", "June", "July"],
datasets: [{
label: "My First dataset",
data: [65, 0, 80, 81, 56, 85, 40],
fill: false
}]
}
};
var ctx = document.getElementById("myChart").getContext("2d");
var myChart = new Chart(ctx, config);
labelsNew = ["Why", "u", "no", "work", "???"];
dataNew = [2, 4, 5, 6, 10];
function updateData(chart, label, data) {
removeData();
chart.data.labels.push(label);
chart.data.datasets.forEach((dataset) => {
dataset.data.push(data);
});
chart.update();
};
function removeData(chart) {
chart.data.labels.pop();
chart.data.datasets.forEach((dataset) => {
dataset.data.pop();
});
chart.update();
}
$('.button-container').on('click', 'button', updateData(myChart, labelsNew, dataNew));
I figured it out. This works:
function addData(chart, label, data) {
chart.data.labels = label
chart.data.datasets.forEach((dataset) => {
dataset.data = data;
});
chart.update();
}
$("#btn").click(function() {
addData (myChart, labelsNew, dataNew);
});
instead of pushing the data (which adds on), data needs to be allocated by " = ".
I see 2 problems:
in function updateData() missing chart argument to removeData(chart);
click handler for button, use simply:
$("#btn").click(function() {
updateData(myChart, labelsNew, dataNew)
});
var config = {
type: 'line',
data: {
labels: ["January", "February", "March", "April", "May", "June", "July"],
datasets: [{
label: "My First dataset",
data: [65, 0, 80, 81, 56, 85, 40],
fill: false
}]
}
};
var ctx = document.getElementById("myChart").getContext("2d");
var myChart = new Chart(ctx, config);
labelsNew = ["Why", "u", "no", "work", "???"];
dataNew = [2, 4, 5, 6, 10];
function addData(chart, label, data) {
chart.data.labels = label
chart.data.datasets.forEach((dataset) => {
dataset.data = data;
});
chart.update();
}
function clickupdate(){
addData(myChart, labelsNew, dataNew);
}
.chart-container {
height: 300px;
width: 500px;
position: relative;
}
canvas {
position: absolute;
}
<script src="https://cdn.jsdelivr.net/npm/chart.js"></script>
<div class="button-container">
<button onclick="clickupdate()">Change Data</button>
</div>
<div class="chart-container">
<canvas id="myChart"></canvas>
</div>

addData() dropped from latest chart.js 2.1.3 - whats up?

I've been reading the docs, and there are ways to replace the data then update the chart:
myLineChart.data.datasets[0].data[2] = 50; // Would update the first dataset's value of 'March' to be 50
myLineChart.update(); // Calling update now animates the position of March from 90 to 50.
https://github.com/chartjs/Chart.js/blob/master/docs/07-Advanced.md
But addData() appears to be gone, am I stuck with making my own addData for local data and then updating the whole chart? or am I missing something.
The update() handles adding data too. Just push your new data / labels into the config object that you passed when creating the chart and then call update()
For instance,
var config = {
type: 'line',
data: {
labels: ["January", "February", "March", "April", "May", "June", "July"],
datasets: [{
label: "My First dataset",
data: [65, 0, 80, 81, 56, 85, 40],
fill: false
}]
}
};
var ctx = document.getElementById("myChart").getContext("2d");
var myChart = new Chart(ctx, config);
setTimeout(function(){
config.data.labels.push('Test');
config.data.datasets[0].data.push(3);
myChart.update();
}, 1000);
Fiddle - http://jsfiddle.net/zpnx8ppb/

Meteor Collection to ChartJs Data

I have a Meteor Collection which I want to be presented into a graph using ChartJS. I was able to follow how ChartJS documentation.
My problem now is how to transform my collection and pass it on to ChartJS.
ChartJs Data format :
function drawChart() {
var data = {
labels: ["January", "February", "March", "April", "May", "June", "July"],
datasets: [{
data: [28, 48, 40, 19, 86, 27, 90]
}]
};
This is how my collection was saved :
Categories.insert({
categoryname : $('#categoryname').val(),
value : $('#categoryvalue').val()
});
I wanted to use the categoryname as the chart labels and the value as the data. How am I going to do this?
This is how I made it work after another try after I posted my question.
function drawChart() {
var cur = Categories.find();
collData = [];
cur.forEach(function(cat){
collData.push([cat.value]);
});
collLabel = [];
cur.forEach(function(cat){
collLabel.push([cat.categoryname]);
});
var data = {
labels: collLabel,
datasets: [{
data: collData
}]
};
};
I am not sure if this the right way to do it but it works for now.

Categories