Highcharts Graph Blank Using JSON Data - javascript

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
});

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.

Problem creating scatter graph using chart.js

I have been trying to create a scatter graph using chart.js, and using data from a JSON object I am fetching from a public api, however my graph is not being created but I am not getting any errors on my console therefore I am unsure as to where the problem is.
This is the structure of my JSON object
0:{
first_name: "Shkodran"
form: "2.3"
points_per_game: "3.2"
now_cost: 51
second_name: "Mustafi"
web_name: "Mustafi"
minutes: 620
goals_scored: 0
assists: 2
clean_sheets: 2
goals_conceded: 9
}
Each entry is a different player and there are 628 entries.
Below is the code I am using
Fetching the public api and parsing the response
var request = new XMLHttpRequest()
var json;
request.open('GET','https://cors- anywhere.herokuapp.com/https://fantasy.premierleague.com/api/bootstrap-static/' , true)
request.onload = function() {
if (request.status >= 200 && request.status < 400) {
json = JSON.parse(this.response);
}
console.log(json);
}
request.send();
Generating the datasets for the scatter graph as I want my graph to be x:now_cost and y:points_per_game.
Creating the chart using chart.js
if (document.readyState === 'complete') {
function generateData() {
var data=[];
json.elements.forEach(elements => {
data.push({
x: elements.now_cost,
y: points_per_game
});
});
return data;
}
var ctx = document.getElementById('chart1').getContext('2d');
var scatterChart = new Chart(ctx, {
type: 'scatter',
data: {
dataset: [{
data: generateData()
}]
},
options: {
title: {
display: true,
text: 'Cost vs Points Per Game Chart'
},
scales: {
xAxes: [{
title:{
display:true,
text: 'Cost'
},
type: 'linear',
position: 'bottom'
}],
yAxes: [{
title:{
display:true,
text: 'Points Per Game'
},
type: 'linear',
position: 'bottom'
}]
}
}
});
}
Your data is not of valid JSON format, individual properties need to be separated by a comma each. There's also an error inside the generateData function with the assignment to the y property. It should be rewritten as follows:
function generateData() {
var data = [];
json.elements.forEach(element => {
data.push({
x: element.now_cost,
y: element.points_per_game
});
});
return data;
}
Or you could even get rid of this function generateData and assign data directly as follows:
dataset: [{
data: json.elements.map(e => ({ x: e.now_cost, y: e.points_per_game }))
}]

Firebase web keeps duplicating apexchart everytime data is updated

Hey all i am using javascript with ApexCharts to draw a chart and this chart gets its data from firebase but each time the data is changed in firebase instead of replacing the chart or updating it it appends new chart under it
this is the code
function dailyTracking(){
var query = firebase.database().ref('Facilities').on('value', function(snapshot) {
var options = {
chart: {
height: 380,
width: "100%",
type: "bar",
stacked: false
},
series: [
{
name: "Library",
data: snapshotToArray(snapshot.child('Library'))
},
{
name: "Canteen",
data: [5]
},
{
name: "Free Lab",
data: [42]
}
],
xaxis: {
labels: {
formatter: function (value, timestamp) {
return new Date() // The formatter function overrides format property
},
}
}
};
var chart = new ApexCharts(document.querySelector("#chart"), options);
chart.render();
query.off();
return snapshotToArray(snapshot);});}
I managed to solve it by adding this line
document.getElementById('chart').innerHTML = '';
before rendering the chart
Try not to wrap the chart.render() call in the event. Render the chart once and call the update event when you get new data by calling chart.updateSeries()

Highcharts Pyramid Chart displays no data with JSON, PHP

When using JSON with a pyramid chart in Highcharts, I don't get any errors in the console log but no data is displayed.
I have charts.php which outcome is this:
{"success":1,"data":[{"name":"John Spoon","data":300}, {"name":"Dave Jones","data":200},{"name":"Other","data":500}]}
This is what I've tried, which returns no data.
<div id="chart" style=
"height:600px;width:100%;"></div>
<script>
$(function () {
$("#chart").html("Loading Activity Log Graph...");
var options = {
chart: {
type: 'pyramid',
renderTo: 'chart',
marginRight: 100
},
title: {
text: 'Activity',
x: -50
},
plotOptions: {
series: {
dataLabels: {
enabled: true,
format: '<b>{point.name}</b> ({point.y:,.0f})',
color: (Highcharts.theme && Highcharts.theme.contrastTextColor) || 'black',
softConnector: true
}
}
},
legend: {
enabled: false
},
name: 'Activity Count',
series: [{}]
};
$.ajax({
url: "charts.php",
type:'post',
dataType: "json",
success: function(data){
options.series = data.data;
var chart = new Highcharts.Chart(options);
}
});
});
</script>
This is my desired outcome, showing without the use of JSON:
http://jsfiddle.net/0dyy44hz/
What do I need to change for it to show data?
Looking at the pyramid example, the data must be in the form of a single series with each data point as an array of [name, value]. You have two options, change your PHP to output the correct format or modify the PHP output in javascript. Since you didn't post your PHP code, I'll do the later:
var data = {"success":1,"data":[{"name":"John Spoon","data":300}, {"name":"Dave Jones","data":200},{"name":"Other","data":500}]};
options.series = [{
data: $.map(data.data, function(i){ // loop outputted data
return [[i.name, i.data]]; // coerce into an array of [name,value]
})
}];
Here's a working example.

Creating multiple series in a highcharts spline chart?

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
};

Categories