It doesn't work on all three browsers - IE, Chrome and Firefox.
Here's the source code for my HTML:
<html>
<head>
<script type ="text/javascript" src ="jquery-1.10.2.js" ></script>
<script type ="text/javascript" src ="highcharts.js" ></script>
<script type ="text/javascript" src ="exporting.js" ></script>
<script type ="text/javascript" src ="fruits.js" ></script>
</head>
<body>
<div id="container" style="min-width: 310px; height: 400px; margin: 0 auto"></div>
</body>
</html>
Here's the source code for what I have in the fruits.js script:
$(document).ready(function () {
var options = {
chart: {
renderTo: 'container',
type: 'column'
},
title: {
text: 'Fruit Consumption'
},
xAxis: {
categories: []
},
yAxis: {
title: {
text: 'Units'
}
},
series: []
};
$.get('data.csv', function (data) {
// Split the lines
var lines = data.split('\n');
// Iterate over the lines and add categories or series
$.each(lines, function (lineNo, line) {
var items = line.split(',');
// header line containes categories
if (lineNo == 0) {
$.each(items, function (itemNo, item) {
if (itemNo > 0) options.xAxis.categories.push(item);
});
}
// the rest of the lines contain data with their name in the first
// position
else {
var series = {
data: []
};
$.each(items, function (itemNo, item) {
if (itemNo == 0) {
series.name = item;
} else {
series.data.push(parseFloat(item));
}
});
options.series.push(series);
}
});
// Create the chart
var chart = new Highcharts.Chart(options);
});
});
So any idea why isn't the chart displays anything at all? It does works without the CSV data file though
This is what I have in my csv file:
Categories,Apples,Pears,Oranges,Bananas
John,8,4,6,5
Jane,3,4,2,3
Joe,86,76,79,77
Janet,3,16,13,15
Related
I am trying to plot a multi series line graph with two y-Axis using highcharts. The data is being plotted from a CSV on a server. The problem i have is when it comes to plotting more than one series. I can succesfully load all the csv data into arrays. When i try plot the second axis nothing shows up. Am i missing something here?
Here is the html code
<script type="text/javascript">
$.get('employeeData.csv', function(data) {
var lines = data.split('\n');
console.log(lines);
var timeData=[];
$.each(lines, function(lineNo, lineContent){
if(lineNo > 0)
{
timeData[lineNo-1] = lineContent.split(',')[0];
}
});
var weightData=[];
$.each(lines, function(lineNo, lineContent){
if(lineNo > 0)
{
weightData[lineNo-1] = lineContent.split(',')[1];
}
});
var valueData=[];
$.each(lines, function(lineNo, lineContent){
if(lineNo > 0)
{
valueData[lineNo-1] = parseFloat(lineContent.substring(lineContent.lastIndexOf(",")+1) );
}
});
console.log(timeData);
console.log(weightData);
console.log(valueData);
Highcharts.chart('container', {
chart: {
type: 'spline'
},
title: {
text: 'employee Data'
},
subtitle: {
text: 'firmA'
},
xAxis: {
categories: timeData,
crosshair: false
},
yAxis: [{ // Primary yAxis
labels: {
format: '{value}(g)',
style: {
color: Highcharts.getOptions().colors[1]
}
},
title: {
text: 'Weight',
style: {
color: Highcharts.getOptions().colors[1]
}
}
}, { // Secondary yAxis
title: {
text: 'secondary axis',
style: {
color: Highcharts.getOptions().colors[0]
}
},
labels: {
format: '{value} zCount',
style: {
color: Highcharts.getOptions().colors[0]
}
},
////////Notice: importance option
opposite: true //This option will set position of this axis to the right sie
}],
tooltip: {
headerFormat: '<b>Time:</b> {point.x}<br/>',
pointFormat: '<b>{series.name}:</b> {point.y}<br/>'
},
plotOptions: {
column: {
pointPadding: 0.01,
borderWidth: 0
}
},
series: [{
name: 'Weight',
data: weightData
}, {
name: 'value',
data: valueData,
yAxis: 1
}]
});
});
</script>
<html>
<head>
<script src="https://code.highcharts.com/highcharts.js"></script>
<script src="https://code.highcharts.com/modules/exporting.js"></script>
<script type="text/javascript" src="http://ajax.googleapis.com/ajax/libs/jquery/1.9.1/jquery.min.js"></script>
</head>
<body>
<div id="container" style="min-width: 310px; height: 600px; margin: 0 auto"></div>
</body>
</html>
here is the csv
Time,Weight,value
2020/08/18 18h25,29719,59
2020/08/18 18h26,29720,62
2020/08/18 18h27,29759,62
2020/08/18 18h28,29790,63
2020/08/18 18h29,29720,64
2020/08/18 18h30,29721,65
2020/08/18 18h31,29760,70
2020/08/18 18h32,29791,89
So for anyone who has had a similar issue, my problem was that i was not parsing the value read from the CSV file to a float. the values were being read as text so to fix this i edited this and added parseFloat();
var weightData=[];
$.each(lines, function(lineNo, lineContent){
if(lineNo > 0)
{
weightData[lineNo-1] = parseFloat(lineContent.split(',')[1]);
}
});
I have a page that dynamically updates a HighCharts graph from a multiselect dropdown.
<!DOCTYPE html>
<html>
<head>
<script src="https://code.jquery.com/jquery-3.1.1.min.js"></script>
<script src="https://code.highcharts.com/highcharts.js"></script>
<script src="https://code.highcharts.com/modules/series-label.js"></script>
<script src="https://code.highcharts.com/modules/exporting.js"></script>
<script src="https://code.highcharts.com/modules/export-data.js"></script>
</head>
<body>
<!-- FIELDS -->
<div id="fields">
<form method="post" action="">
<select id="f" name="f[]" multiple>
<option value="rss1" select>1RSS(dB)</option>
<option value="rss2">2RSS(dB)</option>
<option value="rqly">RQly(%)</option>
<option value="rsnr">RSNR(dB)</option>
</select>
</form>
</div>
<!-- GRAPH -->
<div id="graph">No selection</div>
<script>
var updateChart = function(json) {
// console.log(json)
var options = {
chart: {
renderTo: 'graph',
type: 'line',
zoomType: 'x'
},
title: { text: null },
plotOptions: {
series: {
label: {
connectorAllowed: false
},
pointStart: 0
}
},
series: []
}
options.series = json;
var chart = new Highcharts.Chart(options);
// update yaxis
for (i=0; i<json.length; i++) {
if(i==0) {
// it seems that a yAxis already exist when graph is initialized. Did not find a smarter way to destroy it...
chart.yAxis[0].update({ title: { text: json[i].name }});
} else {
chart.addAxis({ title: { text: json[i].name } });
}
}
}
$(document).ready(function() {
$('#f').change(function() {
var requestParams = { f: $('#f').val() };
$.post('analysisajax.php', requestParams, updateChart);
});
});
</script>
</body>
</html>
Now, my analysisajax.php file looks like this:
<?php
header("Content-type: text/json");
// Initialize the session
session_start();
// Include config file
require_once "config.php";
$jsonObject = array();
$yaxis = 0;
foreach($_POST["f"] as $v) {
$data = array();
$sql = "SELECT $v FROM log WHERE id_user = " . $_SESSION["id_user"];
$result = $link->query($sql);
while($row = $result->fetch_row()) {
$data[] = $row[0];
}
$jsonObject[] = array(
"name" => $v,
"data" => $data,
"yAxis"=>$yaxis
);
$yaxis++;
}
$myJSON = json_encode($jsonObject, JSON_NUMERIC_CHECK);
echo $myJSON;
// Close connection
mysqli_close($link);
?>
When I'm selecting 1 value from the form, the graph loads without problem, but as soon as more than 1 value is selected from the dropdown, the graph fails with the following trace:
highcharts.src.js:498 Uncaught Error: Highcharts error #18: www.highcharts.com/errors/18
at Object.a.error (highcharts.src.js:498)
at highcharts.src.js:32669
at Array.forEach (<anonymous>)
at r.<anonymous> (highcharts.src.js:32621)
at a.fireEvent (highcharts.src.js:2635)
at r.bindAxes (highcharts.src.js:32618)
at r.init (highcharts.src.js:32482)
at a.Chart.initSeries (highcharts.src.js:26913)
at highcharts.src.js:28765
at Array.forEach (<anonymous>)
I feel that the issue is coming from my dynamic construction of yAxis but can't find a way to make it work. Any idea? Thanks a lot.
I eventually made it work with the following solution:
In the analysisajax.php script, I no longer generate the yaxis. I only send name and data.
The code to generate the graph now looks like this:
var updateChart = function(json) {
//console.log(json)
var options = {
chart: {
renderTo: 'graph',
type: 'line',
zoomType: 'x'
},
title: { text: null },
yAxis:[],
legend: {
layout: 'vertical',
align: 'right',
verticalAlign: 'bottom'
},
plotOptions: {
series: {
label: {
connectorAllowed: false
},
pointStart: 0
}
},
series: [],
tooltip: { shared: true }
}
var chart = new Highcharts.Chart(options);
// update axis and series
for (i=0; i<json.length; i++) {
// add axis
chart.addAxis({ title: { text: json[i].name } });
// add serie
var a = chart.series.length;
var seriesOptions = {
name: json[i].name,
data: json[i].data,
yAxis: a
}
chart.addSeries(seriesOptions,true);
chart.options.series.push(seriesOptions);
}
}
$(document).ready(function() {
$('#f').change(function() {
var requestParams = { f: $('#f').val() };
$.post('analysisajax.php', requestParams, updateChart);
//return false;
});
});
Ok hello everyone. I have designed my HighStock works from
CSV-file. I can get time and 1 line to my serie. I want to
get 2 lines from data. Any ideas? In future I want to get 2 decimals for example 25,01. have you got ideas for that?
In CSV there's seconds,data,data. And it's prints it 1minutes.
And yes, I'm from Finland Student and my code sucks... :)
http://imgur.com/L2VSRGj
Data:
Time in Seconds,Value,Value
0,25,23
60,25,23
120,25,23
....
14220,24,22
14280,24,22
14340,24,22
Javascript in my HC.htm: (it's index)
<!DOCTYPE HTML>
<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=utf-8">
<title>Hannun virtamittaus</title>
<script type="text/javascript" src="https://ajax.googleapis.com/ajax/libs/jquery/1.8.2/jquery.min.js"></script>
<style type="text/css">
${demo.css}
</style>
<script type="text/javascript">
function getDataFilename(str){
point = str.lastIndexOf("file=")+4;
tempString = str.substring(point+1,str.length)
if (tempString.indexOf("&") == -1){
return(tempString);
}
else{
return tempString.substring(0,tempString.indexOf("&"));
}
}
query = window.location.search;
var dataFilePath = "/data/"+getDataFilename(query);
$(function () {
var chart;
$(document).ready(function() {
// define the options
var options = {
chart: {
renderTo: 'container',
zoomType: 'x',
spacingRight: 5
},
title: {
text: 'Arduinolla mitatut virran arvot'
},
subtitle: {
text: 'Zoomaa haluttu luenta alue'
},
xAxis: {
type: 'datetime',
maxZoom: 2 * 4000000
},
yAxis: {
title: {
text: 'Virran arvot 0-250A'
},
min: 0,
startOnTick: false,
showFirstLabel: false
},
legend: {
enabled: false
},
tooltip: {
formatter: function() {
return '<b>'+ this.series.name +'</b><br/>'+
Highcharts.dateFormat('%H:%M - %b %e, %Y', this.x) +': '+ this.y;
}
},
plotOptions: {
series: {
cursor: 'pointer',
lineWidth: 1.0,
point: {
events: {
click: function() {
hs.htmlExpand(null, {
pageOrigin: {
x: this.pageX,
y: this.pageY
},
headingText: this.series.name,
maincontentText: Highcharts.dateFormat('%H:%M - %b %e, %Y', this.x) +':<br/> '+
this.y,
width: 100
});
}
}
},
}
},
series: [{
name: 'Op1',
marker: {
radius: 2
}
}]
};
// Load data asynchronously using jQuery. On success, add the data
// to the options and initiate the chart.
// http://api.jquery.com/jQuery.get/
jQuery.get(dataFilePath, null, function(csv, state, xhr) {
var lines = [],
date,
// set up the two data series
lightLevels = [];
// inconsistency
if (typeof csv !== 'string') {
csv = xhr.responseText;
}
// split the data return into lines and parse them
csv = csv.split(/\n/g);
jQuery.each(csv, function(i, line) {
// all data lines start with a double quote
line = line.split(',');
date = parseInt(line[0], 10)*1400;
lightLevels.push([
date,
parseInt(line[1], 10)
]);
});
options.series[0].data = lightLevels;
chart = new Highcharts.Chart(options);
});
});
});
</script>
</head>
<body>
<script src="https://code.highcharts.com/stock/4.2.4/highstock.js"></script>
<script src="https://code.highcharts.com/stock/4.2.4/modules/exporting.js"></script>
<div id="container" style="height: 400px; min-width: 155px"></div>
</body>
</html>
You need to set an array of series objects.
Series:
series: [{
name: 'Op1',
marker: {
radius: 2
}
},{
name: 'Op2'
}]
Parser
jQuery.get(dataFilePath, null, function(csv, state, xhr) {
var lines = [],
date,
// set up the two data series
lightLevels = [];
topLevels = [];
// inconsistency
if (typeof csv !== 'string') {
csv = xhr.responseText;
}
// split the data return into lines and parse them
csv = csv.split(/\n/g);
jQuery.each(csv, function(i, line) {
// all data lines start with a double quote
line = line.split(',');
date = parseInt(line[0], 10)*1400;
lightLevels.push([
date,
parseInt(line[1], 10)
]);
topLevels.push([
date,
parseInt(line[2], 10)
]);
});
options.series[0].data = lightLevels;
options.series[1].data = topLevels;
chart = new Highcharts.Chart(options);
});
I used following file to display a highchart. but it doesnt display anything at all. Can anyone point me the mistake here. I just used code from here
Is the ordering of javascript import correct.? could anyone please help me to correct this html to display highchart.
<html>
<head>
<script src="http://ajax.googleapis.com/ajax/libs/jquery/1.7.1/jquery.min.js" type="text/javascript"></script>
<script src="http://code.highcharts.com/highcharts.js"></script>
<script src="http://code.highcharts.com/modules/exporting.js"></script>
<script src="http://code.highcharts.com/stock/highstock.js"></script>
<script>
$(function() {
$(document).ready(function() {
Highcharts.setOptions({
global: {
useUTC: false
}
});
var chart;
chart = new Highcharts.Chart({
chart: {
renderTo: 'container',
type: 'ohlc',
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();
series.addPoint([
x,
Math.random()*100,
Math.random()*100,
Math.random()*100,
Math.random()*100
], true, true);
}, 1000);
}
}
},
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: 'Random data',
type: 'ohlc',
data: (function() {
// generate an array of random data
var data = [],
time = (new Date()).getTime(),
i;
for (i = -19; i <= 0; i++) {
data.push([
time + i * 1000,
Math.random()*100,
Math.random()*100,
Math.random()*100,
Math.random()*100
]);
}
return data;
})()}]
});
});
});
</script>
</head>
<body>
<div id="container" style="min-width: 400px; height: 400px; margin: 0 auto"></div>
</body>
</html>
The JavaScript console is saying undefined function. When I put the highstock script above the exporting script, as in the jsfiddle you linked, it works fine.
The problem is that you refer to serie OHLC which is supported only in Highstock. So you need to attach highstock.js
I'm struggling to output a line chart from my CSV file, I get the graph but not data in the graph, could someone please tell me what is wrong with the code below?
The data in the CSV is formatted like so:
26-04-2012 09:10,0
26-04-2012 09:20,0
26-04-2012 09:30,0
26-04-2012 09:40,0
26-04-2012 09:50,0
26-04-2012 10:00,1
26-04-2012 10:10,1
HTML code:
<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01//EN" "http://www.w3.org/TR/html4/strict.dtd">
<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=utf-8">
<title>Test</title>
<script src="http://ajax.googleapis.com/ajax/libs/jquery/1.7.1/jquery.min.js" type="text/javascript"></script>
<script src="../../js/highcharts.js" type="text/javascript"></script>
<script type="text/javascript">
$(document).ready(function() {
var c = [];
var d = [];
$.get('test.csv', function(data) {
var lines = data.split('\n');
$.each(lines, function(lineNo, line) {
var items = line.split(',');
c.push(items[0]);
d.push(parseInt(items[1]));
});
});
var options = {
chart: {
renderTo: 'chart',
defaultSeriesType: 'line'
},
title: {
text: 'reading'
},
xAxis: {
title: {
text: 'Date Measurement'
},
categories: c
},
yAxis: {
title: {
text: 'reading'
}
},
series: [{
data: d
}]
};
var chart = new Highcharts.Chart(options);
});
</script>
</head>
<body>
<div id="chart" style="width: 800px; height: 400px; margin: 0 auto"></div>
</body>
</html>
The problem is that the $.get call will return immediately and as a result you will create the chart before the test.csv is downloaded (containing no data at all).
The callback function that you pass to $.get will run when the file is downloaded so placing the creation of the chart there would solve the problem.
The chart is loaded with no data because the csv file is loaded after the chart, because the get request takes time to receive a response. The following will load the data from your file and display the chart after the file loads.
<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01//EN" "http://www.w3.org/TR/html4/strict.dtd">
<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=utf-8">
<title>Test</title>
<script src="http://ajax.googleapis.com/ajax/libs/jquery/1.7.1/jquery.min.js" type="text/javascript"></script>
<script src="../../js/highcharts.js" type="text/javascript"></script>
<script type="text/javascript">
$(document).ready(function() {
var c = [];
var d = [];
var options = {
chart: {
renderTo: 'chart',
defaultSeriesType: 'line'
},
title: {
text: 'reading'
},
xAxis: {
title: {
text: 'Date Measurement'
},
categories: c
},
yAxis: {
title: {
text: 'reading'
}
},
series: [{
data: d
}]
};
var jqxhr = $.get('test.csv', function(data) {
var lines = data.split('\n');
$.each(lines, function(lineNo, line) {
var items = line.split(',');
c.push(items[0]);
d.push(parseInt(items[1]));
})
var chart = new Highcharts.Chart(options);
});
});
</script>
</head>
<body>
<div id="chart" style="width: 800px; height: 400px; margin: 0 auto"></div>
</body>
</html>