How to add data to pie chart Javascript - javascript

I am trying to display the percentage of pets per owner in a pie chart, how do i push data to the piechart? the for loop keeps getting a SyntaxError: Unexpected token var. here's my code.
window.onload = function() {
var count = "<?php echo($i)?>";
var name = [];
var per = [];
var j = -1;
var chart = new CanvasJS.Chart("chartContainer", {
animationEnabled: true,
title: {
text: "TB_PET"
},
data: [{
type: "pie",
startAngle: 240,
yValueFormatString: "##0.00\"%\"",
indexLabel: "{label} {y}",
Error here-->for(var i = 0; i < count; i++){
name[i] = document.getElementById(i).value;
per[j] = document.getElementById(j).value;
dataPoints: [
{y: per[j], label: name[i]}
]
j--;
}
}]
});
chart.render();
}

You cannot iterate inside the object literal (configuration for the chart) that is passed as a parameter to a function call.
Iterate over you data prior to the new CanvasJS.Chart(...) call, and pass the variable as part of the config object.
Iterate here
var dataPoints = [];
for(...){
dataPoints.push(..);
]
then pass dataPoints in as below
var chart = new CanvasJS.Chart("chartContainer", {
animationEnabled: true,
title: {
text: "TB_PET"
},
data: [
{
type: "pie",
startAngle: 240,
yValueFormatString: '##0.00"%"',
indexLabel: "{label} {y}",
dataPoints: dataPoints
}
]
});
chart.render();

Note: This would be a comment if my rep was higher
I'm not familiar with php returns, but I would first start with manually changing the 'count' variable to be an actual number before moving forward. It appears that your for loop is evaluating the 'count' variable as a string and then throwing the error you're seeing.
https://airbrake.io/blog/javascript-error-handling/unexpected-token

Related

How to load datapoints from array in CanvasJS to make a chart?

i want to make a chart with data from an array. But couldn't figure out why isn't any data showing up in my chart.
Can you guys help me to solve this problem?
var dataset = [];
$(data.items).each(function (index, item)
{
dataset.push(item.SQA);
});
console.log("5. item: " + dataset[5]);
console.log("array items: " + dataset);
var chart = new CanvasJS.Chart("wrapper_dia", {
animationEnabled: true,
theme: "light2",
title:{
text: "Simple Line Chart"
},
data: [{
type: "line",
indexLabelFontSize: 16,
dataPoints: dataset
}]
});
chart.render();
You can loop through the array and parsing it to the format accepted by CanvasJS before passing to the chart options. Check the below code snippet for the same.
var dps = [];
function parseDataPoints () {
for (var i = 0; i <= dataArray.length; i++)
dps.push({y: dataArray[i]});
};
parseDataPoints();
chart.options.data[0].dataPoints = dps;
chart.render();
Check out this JSFiddle for an example on the same.

Plot data on pie chart using database in canvasjs

I am using canvasjs I want to plot data from database into pie chart. I am able to get data from DB and pass it to an array.
array_push($dataPointskWh, array("label"=>$pr['name'],"y"=>$cr['sum_kwh_diff']));
JS
<script>
var arry_kwh = [];
arry_kwh = <?php echo json_encode($dataPointskWh, JSON_NUMERIC_CHECK); ?>;
console.log(arry_kwh);
var chart = new CanvasJS.Chart("chartContainer2", {
animationEnabled: true,
title: {
text: "Last Month Floor Wise kWh"
},
data: [{
type: "pie",
//startAngle: 240,
//showInLegend: true,
yValueFormatString: "##0.00\" kWh\"",
indexLabel: "{label} {y}",
dataPoints: [
// here I want to add the data points
]
}]
});
chart.render();
The console.log(array_kwh) gives me
0:
label: "Floor-1"
y: 1297
1:
label: "Floor-2"
y: 7.7
How can I plot them? Also, the data would increase so I want to plot in that way.
You need to add your label and y data which you get from arry_kwh to some array and passed this array to your dataPoints to plot the values in graph.
Demo Code :
//your data
var arry_kwh =[{
"label": "Floor-1",
"y": 1297
},{
"label": "Floor-2",
"y": 780}];
var dataPoints =[];
//loop through the array and add value to dataPoints array
$.each(arry_kwh , function(key, value){
dataPoints.push({ y :value.y , indexLabel : value.label});
});
var chart = new CanvasJS.Chart("chartContainer2", {
animationEnabled: true,
title: {
text: "Last Month Floor Wise kWh"
},
data: [{
type: "pie",
yValueFormatString: "##0.00\" kWh\"",
dataPoints:dataPoints //passing values
}]
});
chart.render();
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<script type="text/javascript" src="https://canvasjs.com/assets/script/canvasjs.min.js"></script>
<div id="chartContainer2" style="height: 300px; width: 100%;"></div>

How to Redraw chart in JavaScript

I have application which needs to update the chart with the javascript. To do that I have created for loop. However It does not do that.
What is wrong with my code.
Any help is appreciated. Thank You.
JavaScript
plot = function() {
var array = {{preds}}
var classes = {{classes | safe}}
var path2 = "{{imgPut}}"
var img = document.createElement("img");
img.src = path2;
var src = document.getElementById("putimg");
src.appendChild(img);
for (var i = 0; i < array.length;i++) {
var preds = array[i];
console.log(preds)
var chart = new CanvasJS.Chart("chartContainer", {
theme: "light2", // "light1", "light2", "dark1", "dark2"
exportEnabled: true,
animationEnabled: true,
title: {
text: "Analysis Result"
},
data: [{
type: "bar",
legendText: "{label}",
indexLabelFontSize: 16,
indexLabel: "{label} - {y}%",
dataPoints: [
{y: preds[0], label: classes[0]},
{y: preds[1], label: classes[1]},
{y: preds[2], label: classes[2]},
{y: preds[3], label: classes[3]},
]
}]
});
chart.render();
demo();
console.log("After Sleep")
//chart.update();
}
I have tried the chart update as the other answer to the StackOverFlow questions suggested. However I cannot do it, it gives an error.
chart.options.title.text = "Updated Chart Title";
chart.options.data[0].dataPoints.push({y: 23}); // Add a new dataPoint to dataPoints array
chart.options.data[0].dataPoints[3].y = 27; // Update an existing dataPoint
chart.options.title.text = "Updates Chart Title";
chart.options.data = [array]; // Set Array of dataSeries
chart.options.data[0] = {object}; // Set/Replace dataSeries
chart.options.data.push({object}); // Add a new dataSeries
chart.options.data[0].dataPoints = [array]; // Set/Replace dataPoints (array) of dataSeries
chart.options.data[0].dataPoints.push({y: 23}); // Add a new dataPoint to dataPoints array
chart.options.data[0].dataPoints[3] = {y: 23}; // Add/Replace a dataPoint
chart.options.data[0].dataPoints[3].y = 27; // Update an existing dataPoint
chart.options.axisY.maximum = 60; // Set maximum of axisY
See Hear

Why am I getting only the last appended data in this - using canvasjs

$("#main-content").empty();
$("#main-content").append(
"<div class='tab-pane padding-bottom30 active fade in'>" +
"<div id='chartContainer' style='height: 300px; width: 100%;'>" +
"</div>" +
"</div>"
);
for(var i = 0; i < 5; i++) {
var chart = new CanvasJS.Chart("chartContainer", {
theme: "theme2", //theme1
title: {
text: "Basic Column Chart - CanvasJS"
},
animationEnabled: false, // change to true
data: [{
type: "column", // Change type to "bar", "splineArea", "area", "spline", "pie",etc.
dataPoints: [{ label: i, y: i * 2 }]
}]
});
chart.render();
}
I'm using canvasjs to display my graph. I want to show all data in graph from i = 0 to 4.... but I am only getting last appended data. how can I resolve this?
Probably because chart.render(); is inside your for loop, as well as your chart var itself, so it's rendering every time and when the loop hits the end, you'll have only the last iteration of the chart (along with the last values for your dataPoints). Move your chart definition outside of this loop, you'll only need it for your dataPoints... so it seems. Try the following
var dataPoints = [];
for (var i = 0; i < 5; i += 1) {
dataPoints.push({ 'label': i, 'y': (i * 2) })
}
var chart = new CanvasJS.Chart('chartContainer', {
theme: 'theme2',
title: {
text: 'Basic Column Chart - CanvasJS'
},
animationEnabled: false,
data: [
{
type: 'column',
dataPoints: dataPoints
}
]
});
chart.render();

Put 2 lines on highchart with ajax and dynamic updating

I'm trying to put a second line on a Highchart using ajax with dynamic (periodic) updating. First line works fine using ajax. I think the problem is the format of the incoming data, but also how I'm splitting the data for each of the lines.
I have control of the format of the ajax data so it be could posted in most any form but it works for the first line.
Here is the ajax data that is received with each request:
[Date.parse("2013/02/14 14:29:00 -0000"), 51, 216510]
This will create a point for the first line at 51 but not anything for the second line which should be at 216510.
The following is the javascript I'm using:
var chart; // global
/**
* Request data from the server, add it to the graph and set a timeout to request again
*/
function requestData() {
$.ajax({
url: '/htbin/count_since_total',
success: function(point) {
var series = chart.series[0],
shift = series.data.length > 30; // shift if the series is longer than 300 (drop oldest point)
// add the point
chart.series[0].addPoint(eval(point), true, shift);
// call it again after one second
setTimeout(requestData, 1000);
},
cache: false
});
}
$(document).ready(function() {
chart = new Highcharts.Chart({
chart: {
renderTo: 'container',
events: {
load: requestData
}
},
title: {
text: 'time'
},
xAxis: {
type: 'datetime'
},
yAxis: [{ // Primary yAxis
title: {text: 'count'},
opposite: false
}, { // Secondary yAxis
title: {text: 'Total'},
opposite: true
}],
series: [{
yAxis: 0,
name: 'number',
data: []
},{
yAxis: 1,
name: 'Total',
data: []
}],
});
});
EDIT 1:
Not working, no second line with suggested changes. I'm thinking that incoming data format is incorrect or it needs processing after receiving. Also how does the data get assigned to the proper line?
series: [{
yAxis: 0,
name: 'number',
data: []
},{
yAxis: 1,
name: 'Total',
data: []
}],
--------- end EDIT 1 ----------------
In your success-action/function, you are only updating series[0].
If you want to add a point to the second line, you'll have to add a point to series[1] as well.
Add a for loop to do the same for each serie.
success: function(point) {
for(var i = 0, length = chart.series.length; i < length; i++) {
var serie = chart.series[i],
// shift if the series is longer than 300 (drop oldest point)
var shift = serie.data.length > 30;
// add the point
serie.addPoint(eval(point), true, shift);
}
// call it again after one second
setTimeout(requestData, 1000);
}

Categories