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>
Related
I am trying to draw CanvasJs chart using data from json file but for some reason it does not work.
The data which I am trying to display are data which is in json file represented as number "####" and value "#"
Please take a look at the code below.
<!DOCTYPE HTML>
<html>
<head>
<script>
window.onload = function() {
var dataPoints = [];
var chart = new CanvasJS.Chart("chartContainer", {
animationEnabled: true,
theme: "light2",
title: {
text: "Years"
},
axisY: {
title: "Value",
titleFontSize: 24
},
data: [{
type: "column",
yValueFormatString: "# Value",
dataPoints: dataPoints
}]
});
function addData(data) {
for (var i = 0; i < data.length; i++) {
dataPoints.push({
x: new Year(data[i].date),
y: data[i].value
});
}
chart.render();
}
$.getJSON("https://api.worldbank.org/v2/countries/gbr/indicators/UIS.FOSEP.56.F600?format=json", addData);
}
</script>
</head>
<body>
<div id="chartContainer" style="height: 370px; width: 100%;"></div>
<script src="https://canvasjs.com/assets/script/jquery-1.11.1.min.js"></script>
<script src="https://canvasjs.com/assets/script/canvasjs.min.js"></script>
</body>
</html>
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
First you need to call the json, $.getJson gives a callback, so once the api gives the data you need to create the dataPoints, once its created create the chart.
I hope the below solution will solve the issue.
Note: If required you can add a loader for the mean time while its loading , so the user will know that some thing is loading
const chartCreation = (data) => {
$("#chartContainer").CanvasJSChart({
animationEnabled: true,
theme: "light2",
title: {
text: "Years"
},
axisY: {
title: "Value",
titleFontSize: 24
},
data: [{
type: "column",
yValueFormatString: "# Value",
dataPoints: dataPoints
}]
});
}
let dataPoints = [];
const addData = (data) => {
dataPoints = data[1].filter(obj => +(obj.date) >= 2010 && +(obj.date) <=2018
).map(obj => ({x: +(obj.date),
y: obj.value ? obj.value : 0}))
// once we have the data pass it to chart creation
// function
chartCreation(dataPoints);
}
$.getJSON("https://api.worldbank.org/v2/countries/gbr/indicators/UIS.FOSEP.56.F600?format=json", (data) =>{
// pass the data to function
addData(data);
});
return{
}
<script type="text/javascript" src="https://canvasjs.com/assets/script/jquery-1.11.1.min.js"></script>
<script type="text/javascript" src="https://canvasjs.com/assets/script/jquery.canvasjs.min.js"></script>
<div id="chartContainer" style="height: 370px; width: 100%;"></div>
Updated
As per the comment, first you can array.filter , once you filter you will get a new array where you can return the properties whatever that you want. using array.map to return what ever the properties.
My Pie chart but actually i want this
type of chart
I want to display dynamically label and label values in pie chart using chart
js but according to my code which i have written ,it display all label in one
label. I don't know where is the issue in my code.I don't know as much about
js. Please guide me.Thanks in advance.
$("#get_data").click(function(){
var employees = $("#employees").val();
//var fairs = $("#fairs").val();
$.ajax({
url : 'php_script/chart_values.php',
method : 'POST',
data : {employees:employees},
success : function(data){
var obj = JSON.parse(data);
var a = obj[0]; // labele data "Negotiation on
proposal","Won","Contracted","Intersted",
var b = obj[1]; // label values "100","90","70"
var labeldata;
for( i=0; i<a.length;i++){ // loop to fetch label data one by one
labeldata += [a][i];
}
console.log(labeldata);
var chart = new CanvasJS.Chart("chartContainer", {
title: {
//text: "Worldwide Smartphone sales by brand - 2012",
fontSize:15
},
axisY: {
title: "Products in %"
},
legend :{
verticalAlign: "center",
horizontalAlign: "right"
},
data: [{
type: "pie",
showInLegend: true,
toolTipContent: "{label} <br/> {y} %",
indexLabel: "{y} %",
dataPoints: [
{
label: [labeldata],y:19 // dispaly lable data here
}
/*{ label: "Apple", y: 19.1, legendText: "Apple" },
{ label: "Huawei", y: 4.0, legendText: "Huawei" },
{ label: "LG", y: 3.8, legendText: "LG Electronics"},
{ label: "Lenovo", y: 3.2, legendText: "Lenovo" },
{ label: "Others", y: 39.6, legendText: "Others" } */
]
}
]
});
chart.render();
}
});
});
This is my complete code and this is working perfectly.
$("#get_data").click(function(){
var employees = $("#employees").val();
//var fairs = $("#fairs").val();
$.ajax({
url : 'php_script/chart_values.php',
method : 'POST',
data : {employees:employees},
success : function(data){
$("#page_content").fadeIn();
$("#bar_chart_div").fadeOut();
var obj = JSON.parse(data);
var a = obj[0]; // labele data "Won","Contracted","Intersted"
var b = obj[1]; // label values "100","90","70"
var labeldata=[];
for( i=0; i<a.length;i++){
labeldata.push({label:a[i],y:parseInt(b[i]),legendText:a[i]});
}
debugger;
console.log(JSON.stringify(labeldata));
var chart = new CanvasJS.Chart("chartContainer", {
title: {
fontSize:15
},
axisY: {
title: "Products in %"
},
legend :{
verticalAlign: "center",
horizontalAlign: "right"
},
data: [{
type: "pie",
showInLegend: true,
toolTipContent: "{label} <br/> {y} ",
indexLabel: "{y} %",
dataPoints: labeldata
}]
});
chart.render();
}
});
});
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
I'm trying to figure out how to make a dynamic bar chart using CanvasJs.
The basic set up for the chart is as follows:
var chart = new CanvasJS.Chart("chartContainer", {
theme: "theme2",//theme1
title:{
text: "Basic Column Chart - CanvasJS"
},
animationEnabled: false, // change to true
data: [
{
// Change type to "bar", "area", "spline", "pie",etc.
type: "column",
dataPoints: [
{ label: "apple", y: 10 },
{ label: "orange", y: 15 },
{ label: "banana", y: 25 },
{ label: "mango", y: 30 },
{ label: "grape", y: 28 }
]
}
]
});
chart.render();
}
My goal is to use a simple variable to update the dataPoints instead of static numbers such as 10,15, 25.
User's will input numbers and the chart should update based on their input.
Is this possible to do? Setting "Y" to a variable breaks the chart thus far. I'm unsure how to make this work.
I've also tried setting var input = $('input').html
and setting y as input but it does not work.
Thanks!
If anyone else is trying to figure this out here is how this is handled:
Use variable to assign data points in creating CanvasJS graph?.
This also works with Charts.JS.
I am generating a pie chart from data stored in JSON format. I am trying to change color according to the JSON value.
Ex : if value # json[0]['data'][0][0] = "FAILED" //setColor(RED).
I was able to set the color for column stack charts using options.series.color, however when I tried to use this option with pie chart its converting data into series and unable to render the chart on a container.
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js">
function getData(id) {
$.getJSON("pie.php", {
id: id
}, function(json) {
option.series = json;
chart = new Highcharts.chart(options);
});
}
</script>
can we set the color in getData function only before calling 'chart' or do i need to use Highcharts.setOptions() and define the color codes.
The better option is to create series based on your json data. This is how you can do to specify color based on data.
var serie = {
data: []
};
var series = [serie];
jQuery.each(jsonData, function(index, pointData) {
var point = {
name: pointName,
y: pointData.Value,
color: pointData.Value == 'FAILED' ? 'ff0000' : '00ff00',
serverData: pointData
};
serie.data.push(point);
});
chart.series = series;
OR
Have a look at this easier version
JSFiddle
$( document ).ready(function() {
var data = [{
"name": "Tokyo",
"data": 3.0
}, {
"name": "NewYork",
"data": 2.0
}, {
"name": "Berlin",
"data": 3.5
}, {
"name": "London",
"data": 1.5
}];
// Highcharts requires the y option to be set
$.each(data, function (i, point) {
point.y = point.data;
point.color = parseFloat(point.data) > 3 ? '#ff0000' : '#00ff00';
});
var chart = new Highcharts.Chart({
chart: {
renderTo: 'container',
type: 'pie'
},
series: [{
data: data
}]
});
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<script src="http://code.highcharts.com/highcharts.js"></script>
<div id="container" style="height: 300px"></div>
we can set highchart custom color by setOption function which is as
Highcharts.setOptions({
colors: ['#F64A16', '#0ECDFD',]
});
It sets color to my pie chart.
Another solution for dynamic 3D color
Actually this customization for theme selection Here it is
3 colors sets to color variable
var colors = Highcharts.getOptions().colors;
$.each(colors, function(i, color) {
colors[i] = {
linearGradient: { x1: 0, y1: 0, x2: 1, y2: 0 },
stops: [
[0, '#0ECDFD'],
[0.3, '#F64A16'],
[1, color]
]
};
});
& assign directly in series
{
type : 'column',
name : 'bug',
data : [],
color : colors,
pointWidth : 28,
}