Meteor Collection to ChartJs Data - javascript

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.

Related

How to add on click event to chart js

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>

Chart.js chart positions variable at 0 even though value is >0

I am trying to display a chart by assigning values to an array that will be referenced in charts data.
For whatever reason the chart registers the value in the Array but does not position the value correctly in the chart. I thought it was something to do with the type of the variable, so I tried casting and parsing to no avail.
What can I do to resolve this?
Edit1 - I can add and subtract with the JSON variable, so must be something else rather than a type issue.
Here is my test script
var applied = new Array();
month = ("0" + (date.getMonth() + 1)).slice(-2);
applied.push(2);
applied.push(23);
applied.push(21);
applied.push(2);
applied.push(2);
applied.push(2);
applied.push(2);
applied.push(2);
applied.push(2);
applied.push(2);
var json = $.get("../rest/hello?from=01/"+month+"/2018&to=31/"+month+"/2018", function (data){
applied.push(parseInt(data);
console.log(applied[0]);
});
Here is my chart script
const months = ["January", "February", "March", "April", "May", "June",
"July", "August", "September", "October", "November", "December"
];
var chartlabels = new Array();
for(var i = 11; i > -1; i--){
var date = new Date();
date.setMonth(date.getMonth()-i)
chartlabels.push(months[date.getMonth()]);
}
var ctx = document.getElementById("approvedtoemployed");
var myChart = new Chart(ctx, {
type : 'line',
data : {
labels: chartlabels,
datasets : [ {
label : '# of approved',
data : applied,
backgroundColor : [
'rgba(255, 99, 132, 0)'
],
borderColor : [
'rgba(255, 99, 132, 1)',
],
borderWidth : 1
}]
},
options : {
responsive : false,
maintainAspectRatio : false,
legend: {
display: true,
position: 'bottom',
boxWidth: '15'
},
}
});
Issue must sit with how and when JSON data is loaded.
The chart has to be built within the $.get method, once this is done the chart maps variable correctly.

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>

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/

change y axis values in angular chart

I am creating a project in angularjs. In my project i am using angular chart.I want to change the y axis values of the chart,but i dont know how can i do this. Here is my code:
In Controller:
$scope.labels = ["January", "February", "March", "April", "May", "June", "July"];
// $scope.series = ['Series A', 'Series B'];
$scope.data = [
[65, 59, 80, 81, 56, 55, 40],
[28, 48, 40, 19, 86, 27, 90]
];
In html:
<canvas id="line" class="chart chart-line" chart-data="data"
chart-labels="labels" chart-legend="true"
chart-click="onClick" >
</canvas>
I used an Angular-Charts bar-chart on a recent project and discovered that there is a way of changing the y-axis setting.
What you need to do, is add an extra value at the end of the $scope.data array(s) that sets the minimum value you want on the Y-axis; in my case it was zero, but it can be any other number you need. So long as you don't add any further chart-labels, this extra data value doesn't generate its own bar, but it does stop a real value acting as the y-axis baseline.
Hope that helps.

Categories