The following code displays a blank chart (axes and title are displayed OK but no data), and I cannot understand why. It doesn't seem to be a data format problem, as I followed the documentation. Logging the options to Firebug shows that "series" is null.
var chart1;
var data;
options = {
chart: {
renderTo: 'container',
animation: Highcharts.svg,
},
rangeSelector: {
enabled: true
},
navigator: {
enabled: true
},
xAxis: {
type: 'datetime'
},
yAxis: { //--- Primary yAxis
title: {
text: 'Volume'
}
},
series: [{
name: 'name',
step: true,
data: data
}]
};
console.log(options); //series is null here !
function readData() {
//using foo data here, actually getting it via AJAX, and that works OK
data = [[0,1],[1,2],[2,3]];
alert("data created");
//this checks that the data loaded OK
document.getElementById("result").innerHTML = "";
for (var i = 0; i < data.length; i++) {
document.getElementById("result").innerHTML += 'Key: ' + data[i][0] + '; Value: ' + data[i][1] + "<br />";
}
chart1 = new Highcharts.StockChart(options);
}
Here's what I include :
<head>
<title>Title</title>
<meta charset="UTF-8">
<script type="text/javascript" src="XHR.js"></script><!-- unrelated (for ajax) -->
<script src="http://ajax.googleapis.com/ajax/libs/jquery/1.10.1/jquery.min.js" type="text/javascript"></script>
<script src="http://code.highcharts.com/stock/highstock.js" type="text/javascript"></script>
<script src="http://code.highcharts.com/stock/modules/exporting.js" type="text/javascript"></script>
<script type="text/javascript"> ... </script>
</head>
Of course data is null because you aren't asigning it to options, add this line:
options.series[0].data = data;
AFTER data from AJAX comes. For example before you are creating chart (chart1 = ...).
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.
I am new on highchart. I have gone through the help portal of this and I am unable to fulfill my requirement so need you help/guide to complete this task .
My task is to read the data from a csv/TXT file which contains TPS details as per below format and show it on a dynamic running chart ( it's ok if the chart will refresh in one minute ) .
DATA format:
16:08:02,3
16:08:04,5
16:08:05,1
16:09:01,10
The above file is appending on every second , will read the last one minute data from file and plot this on chart .
I have tried this using below code. Don't know what I am missing.
<!DOCTYPE HTML>
<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=utf-8">
<title>TPS Example</title>
<script type="text/javascript" src="C:/Backup/SUNIL/Software/library/jquery-2.2.0.js"></script>
<style type="text/css">
${demo.css}
</style>
<script type="text/javascript">
$(function () {
$(document).ready(function () {
Highcharts.setOptions({
global: {
useUTC: false
}
});
$('#container').highcharts({
chart: {
renderTo: 'container',
type: 'spline',
animation: Highcharts.svg, // don't animate in old IE
marginRight: 10,
events: {
load: function () {
// set up the updating of the chart each second
var series = this.series[0];
setInterval(function () {
var x = (new Date()).getTime(), // current time
y = Math.random();
series.addPoint([x, y], true, true);
}, 1000);
}
}
},
title: {
text: 'TPS Data'
},
xAxis: {
type: 'datetime',
tickPixelInterval: 150
},
yAxis: {
title: {
text: 'Value'
},
plotLines: [{
value: 3,
width: 1,
color: '#808080'
}]
},
tooltip: {
formatter: function () {
return '<b>' + this.series.name + '</b><br/>' +
Highcharts.dateFormat('%H:%M:%S', this.x) + '<br/>' +
Highcharts.numberFormat(this.y, 2);
}
},
legend: {
enabled: false
},
exporting: {
enabled: false
},
series: [{
name: 'Random data',
data: (function () {
// generate an array of random data
var data = [],
time = (new Date()).getTime(),
i;
for (i = -19; i <= 0; i += 1) {
data.push({
x: time + i * 1000,
y: Math.random()
});
}
return data;
}())
}]
});
});
});
</script>
</head>
<body>
<script src="C:\Backup\SUNIL\Software\library\Highcharts-4.2.1\js\highcharts.js"></script>
<script src="C:\Backup\SUNIL\Software\library\Highcharts-4.2.1\js\highcharts.js"></script>
<div id="container" style="min-width: 50px; height: 200px; margin: 0 auto"></div>
</body>
</html>
You probably have incorrect paths to your script files.
<script src="C:\Backup\SUNIL\Software\library\Highcharts-4.2.1\js\highcharts.js"></script>
<script src="C:\Backup\SUNIL\Software\library\Highcharts-4.2.1\js\highcharts.js"></script>
The code works fine: http://jsfiddle.net/tmp3pty2/
I have set up a simple column chart in Highcharts 4 with jQuery 1.9.1 where I parse a CSV file. I get the normal page showing with the column chart, but when I click on a bar nothing happens. I actually do see the arrays being created in the console (IE11) and they appear to be just what I need, they are in the correct syntax and the IDs match.
The JS fiddle [was...://jsfiddle.net/tjxwty3y/ ... I have changed this in the edit at the bottom ] . I put an example of the CSV that I use, but do not know how to link an external one into the JS Fiddle. I have tried the examples with CSV/TSVs embedded in the code and they have worked, so I think it has to do with how I am pushing the data, hence the external reference.
The CSV is very simple. I have the 3 categories in the first column, their values for the front chart, followed by the IDs in the 3rd and finally the drilldown values in the 4th and 5th.
CSV looks like this
AREA,VALUE,TYPE,SHIFT1,SHIFT2
Blog1,50000,Blog1_Shift,5,6
Blog2,60000,Blog2_Shift,2,3
Blog3,40000,Blog3_Shift,7,8
I have looked at multiple posts (and some videos) where the CSV or TSV is within the JS Fiddle and on Highcharts website, but I completely am not seeing where I have gone wrong (and I know that I have).
Just in case, here is the raw data from js fiddle which has the libraries (I typically use Higcharts 4 and JQuery 1.11 but here I've modified some older code that used JQuery 1.9.1):
<!DOCTYPE html>
<html>
<head>
<meta http-equiv="content-type" content="text/html; charset=UTF-8">
<title> - jsFiddle demo</title>
<script type='text/javascript' src='//code.jquery.com/jquery-1.9.1.js'></script>
<link rel="stylesheet" type="text/css" href="/css/result-light.css">
<script type='text/javascript' src="http://ajax.googleapis.com/ajax/libs/jquery/1.9.1/jquery.min.js"></script>
<script type='text/javascript' src="http://code.highcharts.com/highcharts.js"></script>
<script type='text/javascript' src="http://code.highcharts.com/modules/data.js"></script>
<script type='text/javascript' src="http://code.highcharts.com/modules/drilldown.js"></script>
<style type='text/css'></style>
<script type='text/javascript'>
//<![CDATA[
$(window).load(function () {
$(document).ready(function () {
var options = {
chart: {
renderTo: 'container',
type: 'column'
},
title: {
text: 'My Title Here'
},
xAxis: {
categories: [],
name: []
},
yAxis: {
title: {
text: 'Value Here'
}
},
legend: {
layout: 'vertical',
align: 'right',
verticalAlign: 'top',
y: 15,
borderWidth: 0,
itemStyle: {
color: '#333',
fontSize: '15px',
},
navigation: {
activeColor: '#3E576F',
animation: true,
arrowSize: 12,
inactiveColor: '#CCC',
style: {
fontWeight: 'bold',
color: '#333',
fontSize: '15px',
}
}
},
tooltip: {
shared: true,
crosshairs: true
},
plotOptions: {
series: {
marker: {
lineWidth: 1
}
}
},
series: [],
drilldown: []
};
$.get("http://my/csv/notvalid/dev_drilldown4.csv", function (csvData) {
var lines = csvData.split('\n');
var series = {
data: [],
visible: true,
type: 'column',
colorByPoint: true,
drilldown: true
};
var drilldown = {
series: []
};
$.each(lines, function (lineNo, line) {
if (lineNo > 0 && lineNo < 4) {
var items = line.split(',');
var seriesname = String(items[0]); // this is the area
var area_cost = parseFloat(items[1]); // this is the data for the rollup
var drill_id = String(items[2]); // this will be the id of the drilldown
var shift_one_value = parseFloat(items[3]); // shift1 value
var shift_two_value = parseFloat(items[4]); // shift2 value
series.data.push({
name: seriesname,
y: area_cost,
drilldown: drill_id
});
drilldown.series.push({
id: drill_id,
data: [["shift1", shift_one_value],["shift2", shift_two_value]]
});
}
});
console.log(series.data);
console.log(drilldown.series);
options.series.push({ data: series.data });
options.drilldown.push({ series: drilldown.series });
var chart = new Highcharts.Chart(options);
});
});
});
</script>
</head>
<body>
<div id="container" style="width: 800px; height: 400px; margin: 0 auto"></div>
</body>
</html>
I appreciate any for help/advice.
Thanks
EDIT:
Now that I have added in Salman's and Pawell's edits, including adding in the CSV to the jsFiddle (see Pawell's jsFiddle for what it now looks like) I encountered an additional issue, but it is/was working now!
I realized I forgot the "name" of the series and added that in, adjusting the 'var series' and changing the 'series.data.push' to 'series.push' and watched the log as mentioned by Salman. Now nothing appears, but the console log appears to show the data with the names, ids and data, but no chart (and no error).
The js fiddle is: http://jsfiddle.net/5jzb8hzb/1/. Would you know why changing the 'series.data.push' caused the initial chart to not render?
As noticed by #Salman, there is a couple of issues:
first load Highcahrts then drilldown.js (issue only in jsFiddle)
you shouldn't push to the drilldown array, but assign created series
you have drilldown: [], while should be drilldown: {}
for series you have options.series.push({ data: series.data }), while simply use options.series.push(series) or options.series = [series]
Extra note: I suggest to check values if those are not NaN's - sometimes editors create extra empty new line at the end of the file.
After all fixes, here is fully working code: http://jsfiddle.net/tjxwty3y/7/
Minimized example:
var options = {
chart: {
renderTo: 'container'
},
series: [],
drilldown: {}
};
var csvData = document.getElementById("data").innerHTML; // like $.get()
var lines = csvData.split('\n');
var series = {
data: [],
visible: true,
type: 'column',
colorByPoint: true,
drilldown: true
};
var drilldown = {
series: []
};
// I know with the below I get an extra line so can deal with that when I get the rest of the data sorted
$.each(lines, function (lineNo, line) {
if (lineNo > 0 && lineNo < 4) {
var items = line.split(',');
var seriesname = String(items[0]); // this is the area name
var area_cost = parseFloat(items[1]); // this is the data for the area rollup
var drill_id = String(items[2]); // this will be the id of the drilldown
var shift_one_value = parseFloat(items[3]); // drilldown shift1 value
var shift_two_value = parseFloat(items[4]); // drilldown shift2 value
if(!isNaN(area_cost) && !isNaN(shift_one_value) && !isNaN(shift_two_value)) {
series.data.push({
name: seriesname,
y: area_cost,
drilldown: drill_id
});
drilldown.series.push({
id: drill_id,
data: [
["shift1", shift_one_value],
["shift2", shift_two_value]
]
});
}
}
});
options.series = [series];
options.drilldown = drilldown;
var chart = new Highcharts.Chart(options);
There is a bug in the code; if you log options you will detect it. drilldown configuration is supposed to have a series key. But in your case the key is inside drilldown[0]; probably because of using push function.
The code worked after I changed
options.drilldown.push({ series: drilldown.series });
to
options.drilldown.series = drilldown.series;
There was also another bug- drilldown library should be loaded after highcharts.
Edit: Updated fiddle: http://jsfiddle.net/dxann41x/1/
I have spent many hours learning JavaScript and HighCharts today. I am trying to get this chart to display. I managed to get the JSON to work but I would prefer to get the CSV to work as all of my files are in CSV. I have gone through the JavaScript debugger a lot and see that my data is saving correctly but yet the data does not draw. The axis and title do display. Attached is my code. Thanks in advance for help. For whatever reason, the JSFiddle doesn't work so feel free to look at what I mean at: www.teratuple.com/data/dataVolume.html
<!DOCTYPE html>
<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=utf-8"/>
<script src="http://ajax.googleapis.com/ajax/libs/jquery/1.8.2/jquery.min.js"></script>
<script src="http://code.highcharts.com/stock/highstock.js"></script>
<script src="http://code.highcharts.com/stock/modules/exporting.js"></script>
</head>
<body>
<div id = "container" style = "width:100%; height:400px;"></div>
<script>
var seriesData = [];
var chart;
$(document).ready(function () {
var options = {
chart: {
renderTo: 'container'
},
rangeSelector: {
buttons: [{
type: 'hour',
count: 1,
text: '1h'
}, {
type: 'day',
count: 1,
text: '1d'
}, {
type: 'month',
count: 1,
text: '1m'
}, {
type: 'year',
count: 1,
text: '1y'
}, {
type: 'all',
text: 'All'
}],
selected: 1 // all
},
xAxis: {
title: {
text: 'Date'
}
},
yAxis: {
title: {
text: 'Volume (mm3)'
}
},
title: {
text: 'Volume Differential'
},
series: [{
data: [],
tooltip: {
pointFormat: '{series.name}: <b>{point.y}</b><br/>',
valueDecimals: 2
}
}]
};
$.get('www.teratuple.com/data/volumeData.csv', function (data) {
var lines = data.split('\n');
$.each(lines, function (lineNo, line) {
var items = line.split(',');
if (lineNo > 0) {
seriesData.push([parseInt(items[0]), parseFloat(items[1])]);
}
});
options.series.data = seriesData;
chart = new Highcharts.StockChart(options);
});
});
</script>
</body>
</html>
The series property is meant to be an array so set your series data via
options.series[0].data = seriesData;
I've tried similar examples through stackoverflow as well as Highcharts Support, however still cannot get a graph to display properly. Trying to display a spline graph with data from a csv file with format hour,temperature as shown below in an example:
22,84
23,83
00,82
01,81
02,79
03,77
04,75
Here is the currently html/javascript I have:
<!DOCTYPE HTML>
<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=utf-8">
<script type="text/javascript" src="http://ajax.googleapis.com/ajax/libs/jquery/1.7.1/jquery.min.js"></script>
<script src="../../js/highcharts.js"></script>
<script src="../../js/modules/exporting.js"></script>
<script type="text/javascript">
$(document).ready(function() {
var time = [];
var temp = [];
$.get('forecast.csv', function(data) {
var lines = data.split('\n');
$.each(lines, function(lineNo, line) {
var items = line.split(',');
time.push(parseInt(items[0]));
temp.push(parseInt(items[1]));
});
});
var options = {
chart: {
renderTo: 'container',
type: 'spline'
},
title: {
text: 'Temperature Forecast'
},
xAxis: {
title: {
text: 'Hour'
},
categories: time
},
yAxis: {
title: {
text: 'Temperature'
}
},
series: [{
data: temp
}]
};
var chart = new Highcharts.Chart(options);
});
</script>
</head>
<body>
<div id="container" style="width: 100%; height: 400px"></div>
</body>
My graph displays, however there is no data. Any ideas?
Thanks..
You need to add a two dimensional array as data. You can declare a global variable and add the data to that varible.
var chartData=[]
var dataTemp = new Array(parseInt(items[0]), parseInt(items[1]));
chartData.push(dataTemp);
and
series: [{
data: chartData
}]