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.
Related
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
$("#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();
I am new to using HighCharts and JSON. I am pulling data from my database and it is producing the following JSON:
{"GS10":[{"data_date":-528656400,"value":2.83},{"data_date":-526064400,"value":3.05},{"data_date":-523386000,"value":3.11},{"data_date":-520794000,"value":2.93},{"data_date":-518115600,"value":2.95},{"data_date":-515437200,"value":2.87},{"data_date":-512845200,"value":2.66},{"data_date":-510166800,"value":2.68},{"data_date":-507574800,"value":2.59},{"data_date":-504896400,"value":2.48},{"data_date":-502218000,"value":2.47},{"data_date":-499798800,"value":2.37},{"data_date":-497120400,"value":2.29},{"data_date":-494528400,"value":2.37},{"data_date":-491850000,"value":2.38},{"data_date":-489258000,"value":2.3},{"data_date":-486579600,"value":2.36},{"data_date":-483901200,"value":2.38}]}
This JSON is then to be rendered into a line chart using HighCharts. The script is below. It renders a graph, but the graph is blank. I am currently only testing with one series, but the intent is to be able to use multiple series once I can successfully graph one. Any help would be appreciated, thanks.
<script>
$(function () {
var test_point = 'GS10';
$(document).ready(function() {
$.getJSON("get_data.php", function(json) {
var seriesArr = [];
var series = {
name: test_point,
data: []
};
$.each(json[test_point], function(key, data){
series.data.push({
date: data.data_date,
value: data.value
});
});
seriesArr.push(series);
var options = {
chart: {
renderTo: 'container',
defaultSeriesType: 'line'
},
xAxis: {
type: 'datetime'
},
series: seriesArr
};
var chart = new Highcharts.Chart(options);
});
});
});
</script>
The problem is with that part:
series.data.push({
date: data.data_date,
value: data.value
});
It shouldn't be data/value but rather x/y:
series.data.push({
x: data.data_date,
y: data.value
});
I made a spline chart using Highcharts library containing two series of data loaded from two different CSV files and it works fine. Now I need another spline chart, but with 54 data series.
I used PHP to create the 54 CSV files, then my Javascript code generating the chart is:
<script type="text/javascript">
$(function () {
var chart;
$(document).ready(function() {
var options = {
chart: {
renderTo: 'chart_day',
type: 'spline'
},
title: {
text: 'Andamento giornaliero temperatura.'
},
xAxis: {
type: 'datetime',
second: '%H:%M:%S'
},
yAxis: {
title: {
text: 'Temperatura (°C)'
},
},
tooltip: {
formatter: function() {
return '<b>'+ this.series.name +'</b><br/>'+
Highcharts.dateFormat('%H:%M:%S', this.x) +': '+ this.y +' °C';
}
},
series: [ <?php for($i=0;$i<52;$i++)
echo "{ name: \"Sensor".($i+1)."\", data: []},";
echo "{ name: \"Sensor".($i+1)."\", data: []}";
?>]
};
for( i=1; i<=54; i++){
if(i!=5){
$.get('file/file'+i+'.txt', function(data) {
// Split the lines
var lines = data.split('\n');
// Iterate over the lines and add categories or series
$.each(lines, function(lineNo,line) {
if (line != "") {
var items = line.split(',');
var timeElements = items[0].split(':');
var date = Date.UTC(2004, 2, 1, timeElements[0], timeElements[1], timeElements[2], 0);
options.series[i-1].data.push([date,parseFloat(items[1])]);
}
});
if(i==54)
chart = new Highcharts.Chart(options);
});
}
}
});
});
</script>
There is an error in the JS consolle:
"Uncaught TypeError: Cannot read property 'data' of undefined "
Seems like your series initialization is broken. Try this
var series = [];
for(i=0;i<52;i++)
{
series.push({name: ('Sensor' + (i + 1)), data: []});
}
and set this series object at your options:
var options = {
..
series: series
};
×212414
×123754
I am calling a PageMethod in codebehind.aspx.cs file which returns me a string array[] in the javascript code in the aspx page the problem at hand is that string array returns Time(X axis-Value),Data/Name(Y axis Value),Type(Defines the type of chart (Spline or Column)) from a WEB SERVICE. I am using that data to add series dynamically to the chart. Using the function chart.AddSeries() but I am unable to do so.
Can anyone please guide me how to do that and upon doing that I want to add points to the particular Series.
Please Note that I would be displaying to types{Spline and Column} on the same chart.
<script type="text/javascript">
alert("Bingo");
$(function () {
$(document).ready(function () {
Highcharts.setOptions({
global: {
useUTC: false
}
});
var chart;
chart = new Highcharts.Chart({
chart: {
renderTo: 'ltrChart',
type: 'spline',
marginRight: 10,
events: {
load: function () {
PageMethods.GetSingleValue(function (result) {
var Name = new Array();
var Type = new Array();
var Data = new Array();
var Time = new Array();
var Ser = chart.series;
for (var i = 0; i < 6; i++) {
Type[i] = result[i].split('-')[0];
Name[i] = result[i].split('-')[1];
Data[i] = result[i].split('-')[2];
Time[i] = result[i].split('-')[3];
chart.addSeries({ name :Name[i], data : [ [Time[i], Data[i]] ] }, true, true);
/* Test Method To ensure data Fetching */
// alert(Type[i] + Name[i] + Data[i] + Time[i]);
// alert(result[i]);
}
})
//console.log(typeof PageMethods.GetSingleValue);
// PageMethods.GetSingleValue();
setInterval("PageMethods.GetSingleValue()", 5000);
}
}
},
title: {
text: 'Live random data'
},
xAxis: {
//type: 'datetime',
//tickPixelInterval: 150
},
yAxis: {
title: {
text: 'Value'
},
plotLines: [{
value: 0,
width: 1,
color: '#808080'
}]
},
tooltip: {
formatter: function () {
return '<b>' + this.series.name + '</b><br/>' +
Highcharts.dateFormat('%Y-%m-%d %H:%M:%S', this.x) + '<br/>' +
Highcharts.numberFormat(this.y, 2);
}
},
legend: {
enabled: false
},
exporting: {
enabled: false
},
series: [{
name: 'Test Data',
data: [[10, 50], [15, 55]]
}]
});
});
});
</script>
This is what I've done and works like a charm. On a side-note, since you mentioned aspx page, why don't you just buy the dot net highcharts library? It makes life a lot easier if you're a dot net fan!
I am initially creating a chart with 5 elements, and then using the "iterated" JSON serialized string to pass data to client-side. Traversing the elements gives me a dynamic live chart!
Highcharts chart = new Highcharts("livechart")
.InitChart(new Chart
{
Events = new ChartEvents { Load = "ChartEventsLoad" }
})
.SetSeries(initialSeries)
.SetXAxis(new XAxis { Categories = lsst.ToArray() })
.AddJavascripVariable("iterated", iterateData.ToString())
.AddJavascripVariable("index", "5")
.AddJavascripFunction("ChartEventsLoad",
#"// set up the updating of the chart each 5 seconds
var result = iterated;
var theseries = eval(result); // De-serializing the JSON object
var loopseries = function() {
var sseries = livechart.series[0]
,shift = sseries.data.length > 5; // shift if the series is longer than 5;
sseries.addPoint(theseries[0].data[index], true, shift);
var sseries1 = livechart.series[1]
sseries1.addPoint(theseries[1].data[index], true, shift);
index++; };
setInterval(loopseries, 5000);")
You can add as many series as you like; you can use a loop if needed and the same code I've added as a function can be used to create the chart completely in Javascript.