Cant display data from JSON in canvasjs - javascript

hi and sorry for silly question i miss some part of code and cant figure it out, I did from this lesson https://canvasjs.com/javascript-charts/json-data-api-ajax-chart/ and when I'm editing code to put my json api and values nothing happens....(values from json are telemetry only 'timestamp' and 'cpu' value)
my code is :
window.onload = function() {
var dataPoints = [];
var cpuPoints = [];
var chart = new CanvasJS.Chart("chartContainer", {
animationEnabled: true,
theme: "light2",
title: {
text: "consume timeline"
},
axisY: {
title: "cpu use",
titleFontSize: 24,
},
data: [{
type: "column",
yValueFormatString: "#,### Units",
dataPoints: dataPoints
}]
});
function addData(data) {
for (var i = 0; i < data.length; i++) {
dataPoints.push({
x: new Date(data[i].timestamp),
y: data[i].cpu
});
}
chart.render();
}
$.getJSON("http://192.168.13.60:12345/api/metric/cpu", addData);
}
please can somebody help me figure it out. I think i miss some variable to declare

Related

how can i get percentage of each pie slice in Chart.js

I wanted to get percentage of each slice of pie . I am using chart.js for visualizing feedback results. Below is the code i am using
<script>
var xValues = ["very satisfied", "satisfied", "neutral", "dissatisifed", "very dissatified"];
var yValues = {{ faculty_feedback_data }};
var barColors = [
"#b91d47",
"#00aba9",
"#2b5797",
"#e8c3b9",
"#1e7145"
];
faculty_questionnaire = [questions are inserted here ]
faculty_chart_ids = ["faculty-chart1", "faculty-chart2", "faculty-chart3", "faculty-chart4", "faculty-chart5", "faculty-chart6", "faculty-chart7", "faculty-chart8", "faculty-chart9", "faculty-chart10", "faculty-chart11", "faculty-chart12", "faculty-chart13"]
for (let i = 0; i < faculty_chart_ids.length; i++) {
new Chart(faculty_chart_ids[i], {
type: "pie",
data: {
labels: xValues,
datasets: [{
backgroundColor: barColors,
data: yValues[i]
}]
},
options: {
title: {
display: true,
text: faculty_questionnaire[i]
},
},
});
}
</script>

Cant Generate pie chart using chartjs from JSON

I can't generate pie chart using canvas.JS. I already iterate them through loop.
JSON itself return value like below
[[{"label":"belum","x":1},{"label":"sudah","x":5}]]
I am using below code to get JSON data.
<script type="text/javascript">
$(document).ready(function () {
var abc = [];
$.getJSON("json/data_wilayah1.php", function (result) {
for( var i = 0; i < result.length; i++) {
abc.push({ label: result[i].label, y: result[i].y });
}
var chart = new CanvasJS.Chart("chartContainer", {
animationEnabled: true,
title:{
text: "Ketersediaan Perangkat Jasa Akses Internet Redesain USO"
},
toolTip:{
shared: true,
},
data: [
{
type:"pie",
name: "{label}",
legendText: "{label}",
showInLegend: true,
toolTipContent: "{label}: <strong>{x}%</strong>",
indexLabel: "{label} - {x}%",
dataPoints: abc
}
]
});
chart.render();
}
});
});
</script>
I think it's just a typo in looping.
abc.push({ label: result[i].label, y: result[i].y });
Do you have Y property in your response ?
In your Json response it's X so this result[i].y will return undefined.
I think you're supplying undefined value to co-ordinate.
This is the one which is not working
This is a working one (Updated)

Dynamically load in series HighCharts

I am trying to dynamically load in a number of series, depending on projects chosen by the user. I am using Laravel 5.2, PHP 5.6 and HighCharts.
I have managed to load in one JSON file, which is generated when the user selects projects. But I would like it if the JavaScript could parse the different series from the JSON file and dynamically load this into the series.
This is the code which I am using:
$(function () {
// Set up the chart
var processed_json = new Array();
$.getJSON('/uploads/test.json', function(data) {
for (i = 0; i < data.length; i++) {
processed_json.push([data[i].key, data[i].value]);
}
var chart = new Highcharts.Chart({
chart: {
renderTo: 'container',
type: 'column',
options3d: {
enabled: true,
alpha: 0,
beta: 0,
depth: 0,
viewDistance: 25
}
},
title: {
text: 'Grades'
},
subtitle: {
text: 'Dataset'
},
plotOptions: {
column: {
depth: 0
}
},
series: [{
name: 'Grades',
data: processed_json
}],
credits: {
enabled: false
}
});
function showValues() {
$('#alpha-value').html(chart.options.chart.options3d.alpha);
$('#beta-value').html(chart.options.chart.options3d.beta);
$('#depth-value').html(chart.options.chart.options3d.depth);
}
// Activate the sliders
$('#sliders input').on('input change', function () {
chart.options.chart.options3d[this.id] = this.value;
showValues();
chart.redraw(false);
});
showValues();
});
});
My JSON is formatted like:
[{"key":"Math","value":6},{"key":"Biology","value":"8"},{"key":"English","value":"7"},{"key":"Gym","value":"4"}]
So I would like to have more JSONs like so, in one file to be parsed in the Javascript and be loaded in into the series.
Thank you!
EDIT
thanks for your reply. I have edited my code:
$(function () {
var processed_json = new Array();
var options = {
chart: {
renderTo: 'container',
type: 'column',
options3d: {
enabled: true,
alpha: 0,
beta: 0,
depth: 0,
viewDistance: 25
}
},
title: {
text: 'Grades'
},
subtitle: {
text: 'Dataset'
},
plotOptions: {
column: {
depth: 0
}
},
series: [{
}],
credits: {
enabled: false
}
};
$.getJSON('/uploads/test.json', function(data) {
for (i = 0; i < data.length; i++) {
processed_json.push([data[i].key, data[i].value]);
}
});
options.series[0].remove();
options.series[0].setData = {
name: 'Grades',
data: processed_json
}
var chart = new Highcharts.Chart(options);
chart.redraw(true);
function showValues() {
$('#alpha-value').html(chart.options.chart.options3d.alpha);
$('#beta-value').html(chart.options.chart.options3d.beta);
$('#depth-value').html(chart.options.chart.options3d.depth);
}
// Activate the sliders
$('#sliders input').on('input change', function () {
chart.options.chart.options3d[this.id] = this.value;
showValues();
chart.redraw(false);
});
showValues();
});
But nothing is displayed anymore and the following error is given
TypeError: options.series[0].remove is not a function
I have also tried
var chart = new Highcharts.Chart(options);
chart.series[0].remove();
chart.series[0].setData = {
name: 'Grades',
data: processed_json
}
chart.redraw(true);
But this gives:
TypeError: Cannot set property 'setData' of undefined
I think highcharts has a method chart.addSeries for adding a new series. If you want to replace the current series with a new series, you can try removing first the current series using chart.series[0].remove( ) then add the new series with chart.addSeries. The parameter for the chart.addSeries can be an object like your
{
name: 'Grades',
data: processed_json
}
Then, define method with load data.. example:
function(chart) {
$.each(chart.series, function(i, v){
chart.series[i].remove(true);
});
chart.addSeries({your_data}, true);
}
check http://api.highcharts.com/highcharts/Chart.addSeries/Chart.addSeries
In my webapp, i use 10 of 15 types of graphs highchart and all dynamically load and work fine :) Highcharts is awesome.

File loading a Csv file into highcharts

I'm plotting Csv column data in highcharts. Instead of the:
$.get('5.csv', function(data)
I want input a local desktop Csv file using:
function handleFileSelect(evt) {
var files = evt.target.files; // FileList object
My current Javascript code is below :
var options = {
chart: {
renderTo: 'container',
defaultSeriesType: 'line'
},
title: {
text: 'Test'
},
xAxis: {
categories: []
},
yAxis: {
title: {
text: 'Units',
}
},
series: []
};
// $.get('5.csv', function(data) {
var file = event.target.file;
var reader = new FileReader();
var txt=reader.readAsText(file);
var lines = txt.split('\n');
var c = [], d = [];
$.each(lines, function(lineNo, line) {
if(lineNo > 0 ){
var items = line.split(',');
var strTemp = items[0];
c = [parseFloat(items[0]), parseFloat(items[1])];
d.push(c);
console.log(c);
}
});
options.xAxis.categories = c;
options.series = [{
data: d
}];
chart = new Highcharts.Chart(options);
});
How would I go about doing this ? I want to upload a Csv file from a local desktop machine. How do I link the File Reader upload of the file to highcharts to plot, instead of using the $.get(5.csv', function(data) { ? Or am I better using jquery-csv (https://github.com/evanplaice/jquery-csv). I know there are browser security issues. My file is a 3 column Csv with a one line header, column 1 is the x-axis, 2 is the y-axis, 3 will be the error bar, which I haven't yet implemented:
Q,I,E
0.009,2.40E-01,5.67E-02
0.011,2.13E-01,3.83E-02
0.013,2.82E-01,2.28E-02
etc ....
This works now upload by File API
function processFiles(files) {
var chart;
options = {
chart: {
zoomType: 'x',
renderTo: 'container',
type: 'line',
zoomType: 'x'
},
title: {
text: ''
},
subtitle: {
text: ''
},
xAxis: {
type: 'linear',
minorTickInterval: 0.1,
title: {
text: 'Q'}
},
yAxis: {
type: 'linear',
minorTickInterval: 0.1,
title: {
text: 'I(ntensity)'
},
},
tooltip: {
shared: true
},
legend: {
enabled: true
},
plotOptions: {
area: {
fillColor: {
linearGradient: [0, 0, 0, 300],
stops: [
[0, Highcharts.getOptions().colors[0]],
[0, 'rgba(2,0,0,0)']
]
},
lineWidth: 1,
marker: {
enabled: false,
states: {
hover: {
enabled: true,
radius: 5
}
}
},
shadow: false,
states: {
hover: {
lineWidth: 1
}
}
}
},
series: [{
name: 'Series'}]
};
var file = files[0]
var reader = new FileReader();
reader.onload = function (e) {
str = e.target.result;
var lines = str.split("\n");
var c = [], d = [], er = [];
$.each(lines, function(lineNo, line) {
if(lineNo > 0 ){
var items = line.split(',');
var strTemp = items[0];
er = parseFloat(items[2])
a = parseFloat(items[0])
b = parseFloat(items[1])
min = (b - (er/2))
max = b + ((er/2))
c = [a , b];
var q = [], e = [];
q = [min, max]
e.push(q);
d.push(c);
console.log(c);
console.log(q);
}
});
options.xAxis.categories = c.name;
lineWidth: 1
options.series = [{
data: d,
type: 'scatter'
}, {
name: 'standard deviation',
type: 'errorbar',
color: 'black',
data : e }
];
$("#Linear").click(function(){
$('#container').highcharts().yAxis[0].update({ type: 'linear'});
});
$("#Log").click(function(){
$('#container').highcharts().yAxis[0].update({ type: 'logarithmic'});
});
$("#Guinier").click(function(){
$('#container').highcharts().yAxis[0].update({ data: Math.log(d)});
options.xAxis.categories = c.name;
lineWidth: 1
options.series = [{
data: d
}]
});
chart = new Highcharts.Chart(options);
}
reader.readAsText(file)
var output = document.getElementById("fileOutput")
};
Due to security reasons you can't load a file directly on the client-side
To do this you need to use the HTML5 File API which will give the user a file dialog to select the file.
If you plan to use jquery-csv here's an example that demonstrates how to do that.
File Handling Demo
I'm biased but I say use jquery-csv to parse the data, trying to write a CSV parser comes with a lot of nasty edge cases.
Source: I'm the author of jquery-csv
As an alternative, if jquery-csv doesn't meet your needs, PapaParse is very good too.

Highcharts reloading issue with Backbone.js

I'm struggling to solve a problem I have with getting a chart to be redrawn after navigating to another view and then return back to the same chart view.
I'm using Backbone.js and Underscore as a MVC and templating solution for my application.
When I navigate to the charting page initially it works great, but if I move away and then come back I get a `TypeError: chart.series[0] is undefined in the console log.
I have highlighted line where the error occurs in the code below, close to the end.
My thought is that I may need to destroy() the chart at some point, but I'm unsure where I would do this and if it would solve my problem.
I recently changed the script to now use HighStock 'Highstock JS v1.3.6 (2013-10-04)' from earlier HighCharts ver 2.3.5, where it appeared that I did not have this issue.
The app is live online if anyone really needs or wants to see it in action, let me know.
The following code section is the function thatis called by the Backbone router.
If there is a need for other sections of code, please let me know.
I'll be grateful for any advice.
EDIT:
I have managed to get this in JSFiddle for anyone to view the problem.
Clickty clack your fury tailless one here http://jsfiddle.net/rockwallaby/pqKWj
When you first run it up, you will get a trend being displayed.
Then hit the 'Go to a different page' link, you will get a fairly blank page.
On that page there is a link to bring you back to the trend page.
Hitting that link brings you back but the trend does not get rendered correctly due to the above mentioned error.
//=================================================================================
// trendsBattery
// A simple trend view showing Battery Volts and Solar Charge
//
window.trendsBattery = Backbone.View.extend({
trendModel: new TrendsModel(),
template: _.template(trendsTemplate),
chart: null,
chartoptions:{
chart: {
renderTo: 'chart-container',
},
rangeSelector: {
enabled: false,
},
title:{
text:'Battery Volts & Solar Amps'
},
xAxis: {
type:'datetime',
dateTimeLabelFormats: {month:'%e. %b',year:'%b'}
},
yAxis: [{
title :{text: 'Battery Volts'},
min: 22,
max: 32,
minorGridLineColor: '#E0E0E0',
},
{
title :{text: 'Solar Charge Amps'},
min: 0,
max: 16,
opposite: true,
},
],
series:[
{yAxis: 0, data: [], type: 'line', step: true, name: 'Battery Vdc'},
{yAxis: 1, data: [], type: 'line', step: true, name: 'Solar Amps'},
],
},
render:function() {
that = this;
$(this.el).html(this.template());
this.chartoptions.chart.width = (windowWidth);
this.chartoptions.chart.height = (windowHeight - 150);
setTimeout(function() {
chart = new Highcharts.StockChart(that.chartoptions);
chart.events ={load: that.requestData(this.chart) };
},20);
return this;
},
requestData: function(chart){
var querystring = '//myHostServer.com/myFolder/myPHP.php';
jQuery.get(querystring, null, function(csv, state, xhr) {
if (typeof csv !== 'string') {
csv = xhr.responseText;
};
csv = csv.split(/\n/g);
var vB_array = [];
var iS_array = [];
jQuery.each(csv, function (i, line) {
if (line.length > 1) {
line_array = line.split(',');
var date = parseInt(line_array[0]) * 1000;
var vBpoint = {};
var iSpoint = {};
vBpoint.x = date;
iSpoint.x = date;
vBpoint.y = parseFloat(line_array[1]);
iSpoint.y = parseFloat(line_array[4]);
vB_array.unshift(vBpoint);
iS_array.unshift(iSpoint);
};
});
chart.series[0].setData(vB_array, false); // <<<<< Problem Area
chart.series[1].setData(iS_array, false);
chart.redraw();
});
chart.xAxis[0].setExtremes(); // expand out the scrollbar when moving through time:
},
});
I just updated jsfiddle with the suggestion I provided in comment, it's working.
window.trendView = Backbone.View.extend({
trendModel: new TrendsModel(),
template: _.template(trendTemplate),
chart: null,
getChartOptions: function () {
return {
chart: {
animation: true,
renderTo: 'chart-container',
backgroundColor: '#fff'
},
rangeSelector: {
enabled: false
},
title: {
text: 'Battery Volts & Solar Amps'
},
xAxis: {
type: 'datetime',
dateTimeLabelFormats: {
month: '%e. %b',
year: '%b'
} // don't display the dummy year:
},
yAxis: [{
title: {
text: 'Battery Volts'
},
min: 22,
max: 32,
minorGridLineColor: '#E0E0E0'
}, {
title: {
text: 'Solar Charge Amps'
},
min: 0,
max: 16,
opposite: true
}],
series: [{
yAxis: 0,
data: [],
type: 'line',
step: true,
name: 'Battery Vdc'
}, {
yAxis: 1,
data: [],
type: 'line',
step: true,
name: 'Solar Amps'
}]
}
},
render: function () {
that = this;
$(this.el).html(this.template());
var chartOptions = that.getChartOptions();
chartOptions.chart.width = (windowWidth - 50);
chartOptions.chart.height = (windowHeight - 50);
setTimeout(function () {
chart = new Highcharts.StockChart(chartOptions);
chart.events = {
load: that.requestData(this.chart)
};
}, 20);
return this;
},
requestData: function (chart) {
var querystring = '//paulalting.com/hydrosolar/clientGET.php?id=trendVolts&start=6400&size=200';
console.log(querystring);
jQuery.get(querystring, null, function (csv, state, xhr) {
if (typeof csv !== 'string') {
csv = xhr.responseText;
}
csv = csv.split(/\n/g);
var vB_array = [];
var iS_array = [];
jQuery.each(csv, function (i, line) {
if (line.length > 1) {
line_array = line.split(',');
var date = parseInt(line_array[0], 10) * 1000;
var vBpoint = {};
var iSpoint = {};
vBpoint.x = date;
iSpoint.x = date;
vBpoint.y = parseFloat(line_array[1]);
iSpoint.y = parseFloat(line_array[4]);
vB_array.unshift(vBpoint);
iS_array.unshift(iSpoint);
}
});
chart.series[0].setData(vB_array, false); // <<<<< Problem Area
chart.series[1].setData(iS_array, false);
chart.redraw();
});
chart.xAxis[0].setExtremes(); // expand out the scrollbar when moving through time:
}
});
here is the link
http://jsfiddle.net/pqKWj/14/
If you are interested let me know I see some more similar problems in the code, which I think fine for now, but will create issues, when you have 2 charts in the same page etc. we can talk

Categories

Resources