I'm looking for a help with loading data from dbase into Higtcharts.
The Highcharts data loading entrance looks like:
<script type="text/javascript">
jQuery(function() {
// Create the chart
window.chart = new Highcharts.StockChart({
chart: {
renderTo: 'container'
},
rangeSelector: {
selected: 1
},
title: {
text: 'USD to EUR exchange rate'
},
xAxis: {
maxZoom: 14 * 24 * 3600000 // fourteen days
},
yAxis: {
title: {
text: 'Exchange rate'
}
},
series: [{
name: 'USD to EUR',
data: usdeur
}]
});
});
</script>
and usdeur is loading as in scheme (example from external csv file):
var usdeur = [
[Date.UTC(2011,1,3),0.7488],
[Date.UTC(2011,2,6),0.6983],
[Date.UTC(2011,3,8),0.6961],
[Date.UTC(2011,4,9),0.6945]
];
from dbase SELECT I have:
$data_date = array();
$data_data = array();
foreach($STH as $row)
{
$date1 = $row['date'];
$date2 = explode("-", $date1);
$date3 = $date2[0].",".$date2[1].",".$date2[2];
$data_date[] = $date3; // date in scheme 2011,1,3
$data_data[] = $row['index_p_actual']; // data like 0.7488
}
info about date - $date_date[]
info about corelated data - $data_data[]
I want to load data online, not via any external file like csv.
And my question is - how to join $data_date and $data_data into one data pocket to receive completly virtual list like
[Date.UTC(2011,1,3),0.7488],
[Date.UTC(2011,2,6),0.6983],
[Date.UTC(2011,3,8),0.6961],
[Date.UTC(2011,4,9),0.6945]
The suggestion from highcharts is to use:
series: [{
data: [<?php echo join($data, ',') ?>]
}]
but I have $data & $date - how to join it? With php join I can use only one variable[] ...
Hmmm, or maybe another better way?
If I understood you well, I think you want to do this:
$data_date = array();
$data_data = array();
foreach($STH as $row)
{
$date1 = $row['date'];
$date2 = explode("-", $date1);
$date3 = $date2[0].",".$date2[1].",".$date2[2];
$data_date[] = $date3; // date in scheme 2011,1,3
$data_data[] = $row['index_p_actual']; // data like 0.7488
$data_highcharts[] = [$date3,$row['index_p_actual']]
}
And then you send the $data_highcharts[] to your JavaScript which will have the format:
[[date1,data1],[date2,data2],...]
Related
Trying to group tow columns and and populate it as a particular series on highcharts. my code not grouping columns, And showing all data as a single series.
$query = $db->Prepare("SELECT class, SUM(marks), DATE(date_column) as
dates FROM classes GROUP BY class,DATE(date_column)");
$query->execute();
while ( $row = $query->fetch(PDO:: FETCH_ASSOC)) {
$date = $row['dates'];
$dates[] = $row['dates'];
$class[] = $row['class'];
$marks[] = $row['SUM(marks)'];
$output[] = array($date,(int)$marks);
}
echo json_encode(array('date'=>$dates,'marks'=>$marks, 'name' => $class));
JS
<script>
$(document).ready(function () {
$(function() {
$.getJSON('data.php', function(data) {
// Create the chart
Highcharts.chart('container', {
title: {
text: 'class Marks'
},
xAxis: {
categories: data.dates
},
series : [{
"name" : data.name,
"data": data.marks
}],
});
});
});
});
</script>
Table
Expected output in JSFiddle
data response
date: ["2019-02-07", "2019-02-09", "2019-02-12", "2019-02-08", "2019-02-12",
"2019-02-13", "2019-03-13",…]
marks: ["45", "166", "78", "64", "64", "627", "87", "352"]
name: ["claas 1", "claas 1", "claas 1", "class 2", "class 2", "class 2", "class 3", "class 3"]
By seeing your fiddle the expected output you want for HighCharts is as follow:
1: Category Data:
It should be an array of dates.
Make sure you remove duplicates and order them in ascending/descending order whichever you want, to see a continuous graph.
"categories":["2019-02-07", "2019-02-08", "2019-02-09", "2019-02-12", "2019-02-13", "2019-02-14"]
2: Series Data:
It would be an array of object, where each object contains two properties name and data.
Data should have n no of values if your categories array has n values and each corresponds to same index.
As we don't have data for each date for each class, we would add 0 there.
So data would look like
"series":[
{
"name":"class 1",
"data":[45,0,166,78,0,0]
},
{
"name":"class 2",
"data":[0,64,0,64,627,0]
},
{
"name":"class 3",
"data":[0,0,0,0,87,352]
}
]
Final Fiddle which can be achieved by PHP using below code:
$arrDates = [];
$arrClass = [];
$arrData = [];
while ( $row = $query->fetch(PDO:: FETCH_ASSOC)) {
$arrDates[] = $row['dates'];
$arrClass[] = $row['class'];
$arrData[$row['class'] . ':' . $row['dates']] = $row['marks']; // to identify for which date & class this marks belong to, we can directly search for index.
}
$arrDates = array_unique($arrDates);
sort($arrDates);
$arrClass = array_unique($arrClass);
// Create series data
$arrSeriesData = [];
foreach($arrClass as $strClass){
$tempArr = ['name' => $strClass];
foreach($arrDates as $strDate){
$tempArr['data'][] = isset($arrData[$strClass . ':' . $strDate]) ? intval($arrData[$strClass . ':' . $strDate]) : 0;
}
$arrSeriesData[] = $tempArr;
}
$response = ['categories' => $arrDates, 'series' => $arrSeriesData];
echo json_encode($response);
Output:
{"categories":["2019-02-07","2019-02-08","2019-02-09","2019-02-12","2019-02-13","2019-02-14"],"series":[{"name":"class 1","data":[45,0,166,78,0,0]},{"name":"class 2","data":[0,64,0,64,627,0]},{"name":"class 3","data":[0,0,0,0,87,352]}]}
Update your javascript code to reflect the above
$(document).ready(function() {
$(function() {
$.getJSON('data.php', function(data) {
// Create the chart
Highcharts.chart('container', {
title: {
text: 'class Marks'
},
xAxis: {
categories: data.categories
},
series: data.series,
});
});
});
});
My head is going to blow.
livedata.php loads json when page open.
live.php add point to graph.
From livedata.php i got output like this:
[["Date.UTC(2016, 07-1, 28, 15, 08)",37],["Date.UTC(2016, 07-1, 28, 15, 08)",37],["Date.UTC(2016, 07-1, 28, 15, 08)",37],["Date.UTC(2016, 07-1, 28, 15, 08)",37],["Date.UTC(2016, 07-1, 28, 15, 08)",37],["Date.UTC(2016, 07-1, 28, 15, 08)",37]]
live.php output - only last row, looks like
["Date.UTC('.2016, 07-1, 29, 15, 40.')", 44]
I've got chart, live addPoint working, but no date on x-axis. What i do wrong?
JS
var chart;
function requestData() {
$.ajax({
url: 'live.php',
success: function(point) {
var series = chart.series[0],
shift = series.data.length > 120; // shift if the series is
chart.series[0].addPoint(eval(point));
setTimeout(requestData, 10000);
},
cache: false
});
}
$(function () {
$.ajax({
url: 'livedata.php',
success: function(point) {
chart = new Highcharts.Chart({
chart: {
renderTo: 'container',
type: 'areaspline',
events: {
load: requestData
}
},
title: {
text: 'Revenue vs. Overhead',
},
subtitle: {
text: '',
},
xAxis: {
type: 'datetime'
},
yAxis: {
title: {
text: 'Amount'
},
plotLines: [{
value: 0,
width: 1,
color: '#808080'
}]
},
series: [{
name: 'Random data',
data: eval(point )
}]
});
},
});
});
live.php
global $dbConnection;
$stmt = $dbConnection->query('SELECT DATE_FORMAT(data,"%Y-%m-%d %H:%i") as dataa, humidity FROM sensorsdata order by id desc limit 1');
$row = $stmt->fetch(PDO::FETCH_ASSOC);
$date_raw = strftime('%Y, %m-1, %d, %H, %M', strtotime($row[dataa]));
$date_complete = "Date.UTC('.$date_raw.')";
$ar = array($date_complete, $row[humidity]);
echo json_encode($ar, JSON_NUMERIC_CHECK);
livedata.php
global $dbConnection;
$stmt = $dbConnection->query('SELECT DATE_FORMAT(data,"%Y-%m-%d %H:%i") as dataa, humidity FROM sensorsdata');
$result = $stmt->fetchAll();
foreach ($result as $row) {
$date_raw = strftime('%Y, %m-1, %d, %H, %M', strtotime($row[dataa]));
$date_complete = 'Date.UTC('.$date_raw.')';
$hum_for_chart[] = [$date_complete, $row[humidity]];
}
echo json_encode($hum_for_chart, JSON_NUMERIC_CHECK);
Chart:
Chart
I think its problem of your data try to make string like,
live.php
....
$date_complete = "Date.UTC('.$date_raw.')";
$ar = "[".$date_complete.",". $row[humidity]."]";
echo json_encode($ar);
livedata.php
....
foreach ($result as $row) {
$date_raw = strftime('%Y, %m-1, %d, %H, %M', strtotime($row[dataa]));
$date_complete = 'Date.UTC('.$date_raw.')';
$hum_for_chart[] = "[".$date_complete.",". $row[humidity]."]";
}
....
You can refer highcharts-data-series-issue-with-ajax-json-and-php
i've got it! 2 days of mind blowing ))))
Thanks to Rohan Kumar for link.
I made changes from date.utc to unix timestamp.
$datetimeUTC = ((strtotime($row[dataa])+ 10800) * 1000);
$data[] = [$datetimeUTC, $row[humidity]];
echo json_encode($data);
10800 - that is +3 hours (Moscow timezone)
The output is
[[1469718529000,37],[1469718529000,37],[1469718530000,37],[1469718531000,37]]
And that's it, date axis started working!
Im using this to draw column highcharts jsfiddle
i use this to gt JSON:
<?php
$query = mysql_query("SELECT
sales_raport_all.from_date,
sales_raport_all.to_date,
sales_raport_all.konto,
SUM(sales_raport_all.saldo_sprzedazy),
SUM(sales_raport_all.wartosc_kosztowa),
SUM(sales_raport_all.marza),
klienci_ax_all.sales_group,
klienci_ax_all.nazwa
FROM
sales_raport_all
INNER JOIN
klienci_ax_all
ON
sales_raport_all.konto=klienci_ax_all.konto_odbiorcy
WHERE
YEAR(from_date) = YEAR(CURDATE())
GROUP BY
sales_raport_all.from_date,
klienci_ax_all.sales_group
ORDER BY
sales_raport_all.from_date,
klienci_ax_all.sales_group");
$raw = array();
$dates = array();
while ($r = mysql_fetch_array($query)) {
$date = $r['from_date'];
if (!in_array($date, $dates)) $dates[] = $date;
$sales_group = $r['sales_group'];
$raw[$sales_group][$date] = intval($r['SUM(sales_raport_all.saldo_sprzedazy)']);
}
$data = array();
$data[0] = array('name' => "Date", 'data' => $dates);
foreach ($raw as $name => $d) {
$new_data = array('name' => $name, 'data' => array());
foreach ($dates as $date) {
$new_data['data'][] = isset($d[$date]) ? $d[$date] : 0;
}
$data[] = $new_data;
}
print json_encode($data);
in fiddle i use
chart3Options.series[0] = json[1];
...
is there a simple way to define all data in json? this data is variable and if i declare 11 variables and there will be only 7 then charts will not draw
JSON output for one date:
[{"name":"Date","data":["2014-01-01"]},{"name":"IN","data":[2580]},{"name":"KD","data":[5030]},{"name":"\u0141S","data":[12628]},{"name":"NN","data":[400]},{"name":"SG","data":[12979]},{"name":"TD","data":[15096]}]
// EDIT
i create new file:
<!DOCTYPE HTML>
<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=utf-8">
<title>Highcharts Example</title>
<script type="text/javascript" src="http://ajax.googleapis.com/ajax/libs/jquery/1.7.1/jquery.min.js"></script>
<script type="text/javascript">
$(document).ready(function() {
var options = {
chart: {
renderTo: 'container',
type: 'column',
marginRight: 130,
marginBottom: 25
},
title: {
text: 'test',
x: -20 //center
},
subtitle: {
text: '',
x: -20
},
xAxis: {
categories: []
},
yAxis: {
title: {
text: 'test'
},
plotLines: [{
value: 0,
width: 1,
color: '#808080'
}]
},
tooltip: {
formatter: function() {
return '<b>'+ this.series.name +'</b><br/>'+
this.x +': '+ this.y;
}
},
legend: {
layout: 'vertical',
align: 'right',
verticalAlign: 'top',
x: -10,
y: 100,
borderWidth: 0
},
series: []
}
$.getJSON("test2.php", function(json) {
options.xAxis.categories = json[0]['category'];
options.series[0] = {};
options.series[0].name = json[0]['name'];
options.series[0].data = json[0]['data'];
chart = new Highcharts.Chart(options);
});
});
</script>
<script src="http://code.highcharts.com/highcharts.js"></script>
<script src="http://code.highcharts.com/modules/exporting.js"></script>
</head>
<body>
<div id="container" style="min-width: 400px; height: 400px; margin: 0 auto"></div>
</body>
</html>
and test2.php
<?php
$db_host = '******';
$db_user = '******';
$db_pass = '******';
$db_database = '******';
$link = mysql_connect($db_host,$db_user,$db_pass) or die('Nawiązanie połączenia z bazą danych nie było możliwe');
mysql_select_db($db_database,$link);
mysql_query("SET names UTF8");
$query = mysql_query("SELECT
sales_raport_all.from_date,
sales_raport_all.to_date,
sales_raport_all.konto,
SUM(sales_raport_all.saldo_sprzedazy),
SUM(sales_raport_all.wartosc_kosztowa),
SUM(sales_raport_all.marza),
klienci_ax_all.sales_group,
klienci_ax_all.nazwa
FROM
sales_raport_all
INNER JOIN
klienci_ax_all
ON
sales_raport_all.konto=klienci_ax_all.konto_odbiorcy
WHERE
YEAR(from_date) = YEAR(CURDATE())
GROUP BY
sales_raport_all.from_date,
klienci_ax_all.sales_group
ORDER BY
sales_raport_all.from_date,
klienci_ax_all.sales_group");
$result = array();
while($r = mysql_fetch_array($query)) {
$grupa = $r['sales_group'];
$datetime = $r['from_date'];
$result['name'][] = $datetime;
$result['category'][] = $grupa;
$result['data'][] = intval($r['SUM(sales_raport_all.saldo_sprzedazy)']);
}
$json = array();
array_push($json,$result);
print json_encode($json);
?>
JSON give me:
[{"name":["2014-01-01","2014-01-01","2014-01-01","2014-01-01","2014-01-01","2014-01-01"],"category":["IN","KD","\u0141S","NN","SG","TD"],"data":[2580,5030,12628,400,12979,15096]}]
Series looks greate but i dont know how to change category as in example http://jsfiddle.net/rubJS/
You can handle it in javascript. In other words, instead of defining variable for each <x,y> pair, return the data and let javascript construct the series.
For example, given your current output you can prepare X and Y values (in javascript) in separate arrays and write a function pushing these values into series. It can be done like this (using jQuery as an example):
function build_chart(x_values, y_values, options)
{
jQuery.each(x_values, function(item) {
options.xAxis.categories.push(x_values[item]);
});
var series = {
data: []
};
jQuery.each(y_values, function(item) {
series.data.push(parseInt(y_values[item]));
});
options.series.push(series);
chart = new Highcharts.Chart(options);
return chart;
}
Where variable options defines a chart template without series member (which is added by the above function)
EDIT
Following the edit in the question, here is the jsFiddle supporting it.
Note that the data in JSON is represented as array of arrays. First element in each array corresponds to the first category, second element in each array corresponds to the second category etc.
Apart from incorrect json format (which was mentioed) you need to push your dates as categorries in highcharts or use datetime type of axis, and then parse your date to timestamp.
I am trying to pull financial stock data of multiple companies from CSVs and display the data as separate series in a Highcharts/Highstocks line chart. I have the sources setup and I am able to pull data + convert to JSON, but I am having trouble passing the data off to Highcharts. I believe I am not using the most efficient method of preparing the data for Highcharts use, and I am hoping someone can give me direction on what I've done incorrectly. Please take a look at my code and make me aware of any inefficiencies or glaring errors you see.
PHP code:
date_default_timezone_set('America/Los_Angeles');
$stocks = array('MSFT' => 'http://ichart.finance.yahoo.com/table.csv?s=MSFT', 'AAPL' => 'http://ichart.finance.yahoo.com/table.csv?s=AAPL', 'FB' => 'http://ichart.finance.yahoo.com/table.csv?s=FB');
$stocks_data = array();
foreach ($stocks as $key=>$stock) {
$fh = fopen($stock, 'r');
$header = fgetcsv($fh);
$varname = $key . '_data';
$$varname = array();
while ($line = fgetcsv($fh)) {
${$varname}[count($$varname)] = array_combine($header, $line);
}
fclose($fh);
}
foreach($MSFT_data as $val){
$MSFT[] = strtotime($val['Date']) * 1000 . ', ' . (float)$val['Close']; //sets the date as a javascript timestamp
}
$MSFT = json_encode($MSFT);
foreach($AAPL_data as $val){
$AAPL[] = strtotime($val['Date']) * 1000 . ', ' . (float)$val['Close']; //sets the date as a javascript timestamp
}
$AAPL = json_encode($AAPL);
foreach($FB_data as $val){
$FB[] = strtotime($val['Date']) * 1000 . ', ' . (float)$val['Close']; //sets the date as a javascript timestamp
}
$FB = json_encode($FB);
JS code:
$(function () {
var seriesOptions = [],
yAxisOptions = [],
colors = Highcharts.getOptions().colors;
seriesOptions[0] = {
name: 'MSFT',
data: <? php echo $MSFT; ?>
};
seriesOptions[1] = {
name: 'AAPL',
data: <? php echo $AAPL; ?>
};
seriesOptions[2] = {
name: 'FB',
data: <? php echo $FB; ?>
};
function createChart() {
chart = new Highcharts.StockChart({
chart: {
renderTo: 'container'
},
rangeSelector: {
selected: 4
},
yAxis: {
labels: {
formatter: function () {
return (this.value > 0 ? '+' : '') + this.value + '%';
}
},
plotLines: [{
value: 0,
width: 2,
color: 'silver'
}]
},
plotOptions: {
series: {
compare: 'percent'
}
},
tooltip: {
pointFormat: '<span style="color:{series.color}">{series.name}</span>: <b>{point.y}</b> ({point.change}%)<br/>',
valueDecimals: 2
},
series: seriesOptions
});
}
});
If you have any questions or need further information, please let me know with a comment.
Thanks
BTW: I have all necessary assets included for Highcharts to work; when I replace my JS + PHP with example code from the Highcharts site, it works beautifully. So the problem clearly lies in my JS + PHP code.
Alright, I believe I found the problem, it lies in the way that you are storing each individual point in the array.
Instead of this (which is passing a string x,y separated by a comma):
strtotime($val['Date']) * 1000 . ', ' . (float)$val['Close'];
You are going to want to use something like this (Highcharts accepts arrays or associative arrays):
array((strtotime($val['Date']) * 1000), ((float)$val['Close']));
That will store the X and Y variables as an array instead of comma separated string for the javascript to pass as data.
I have a Highstock graph and I've got the data from a MySQL database like is shown in this example.
The date field is a MySQL timestamp. When I situate the cursor over a value, only the year is shown instead of (Day, month day, year).
Any idea about why only the year is shown?
I'm using Codeigniter framework and the server side code looks like:
$sql = "SELECT UNIX_TIMESTAMP(sop_date)*1000 AS sop_date, sop_price
FROM share
INNER JOIN share_operation
ON share_operation.sop_idsha = share.sha_id
INNER JOIN share_operation_type
ON share_operation_type.sot_id = share_operation.sop_idsot";
$params = array($sha_idcon, $sha_idwal);
$query = $this->db->query($sql, $params);
if ($query->num_rows() > 0) {
$data = array();
foreach ($query->result() as $i => $row) {
$data[] = "[$row->sop_date, $row->sop_price]";
}
return ($data);
}
Client side:
$(document).ready(function() {
Highcharts.setOptions({
lang: {
months: ['Gener', 'Febrer', 'Març', 'Abril', 'Maig', 'Juny',
'Juliol', 'Agost', 'Setembre', 'Octubre', 'Novembre', 'Desembre'],
weekdays: ['Dilluns', 'Dimarts', 'Dimecres', 'Dijous', 'Divendres', 'Dissabte', 'Diumenge'],
rangeSelectorFrom: 'Des de',
rangeSelectorTo: 'Fins'
}
});
window.chart = new Highcharts.StockChart({
chart : {
renderTo : 'graphic'
},
rangeSelector : {
selected : 1
},
title : {
text : 'Xisco'
},
xAxis : {
maxZoom : 14 * 24 * 3600000 // fourteen days
},
series : [{
name : 'Xisco',
data : [<?php echo join($data, ',') ?>],
tooltip: {
yDecimals: 2
}
}]
});
});
Enforcing a formatting might solve this issue.
tooltip: {
formatter: function() {
return Highcharts.dateFormat('%e. %b %Y', this.x);
}
}
More information is in the documentation.
Hope this helps.