Related
I am Trying to make a HighChart's Line Chart Based on the data from the Database.
I Fetched the Data from The Database as I can see that data in the console .
The php Code I Used is :
<?php
$query = "
SELECT YEAR(created_at) AS year,
MONTHNAME(created_at) AS month,
COUNT(*) AS count
FROM users
GROUP BY month ASC ORDER BY created_at ASC
" ;
$result = mysqli_query($conn, $query) ;
while ($row = mysqli_fetch_assoc($result)) {
$data1[] = $row['month'];
$data2[] = $row['count'];
}
?>
Now I Fetched the Data in Highchart's script as Follows :
<script type="text/javascript">
$(function () {
$('#container').highcharts({
chart: {
type: 'line',
},
title: {
text: 'Download Trends'
},
credits: {
enabled: false
},
xAxis: {
categories: ['<?php echo join($data1, "','"); ?>'],
},
yAxis: {
min: 0,
title: {
text: 'No. of Downloads'
}
},
plotOptions: {
column: {
pointPadding: 0.2,
borderWidth: 0
}
},
series: [{
name: 'Qty',
data: ['<?php echo join($data2, "','"); ?>'],
}]
});
});
</script>
I using the container div with id container as follows :
<div id="container"></div>
The Problem is that the data is not showing in correct Manner . its been showing only half of the data as you can see below :
its not showing the Line.
Please Help
Your data serie is made of strings, and Highcharts works with numbers for this kind of graph.
Remove the simple quotes in the data section and it should works :
data: [<?php echo join($data2, ","); ?>]
I have a database with timestamp for three different parameters but for educational purposes only I am trying to do just one graph on one parameter in real time.
Here is my php code:
if ($result->num_rows > 0) {
$count =0;
echo '[';
while($row = $result->fetch_assoc()) {
echo '['.$row["time"].','.$row["temperature"].']';
$count++;
if ($count<"100") {
echo ',';
}
}
echo ']';
}
else {
echo "[[],[]]";
}
$link->close();
?>
The following php code displays:
[[1511533905000,34],[1511534125000,34],[1511534201000,34],[1511535161000,34],[1511535221000,34],[1511535281000,34],[1511535306000,34],[1511535606000,34],[1511535907000,34],[1511536207000,34],[1511536507000,34],[1511536807000,34],[1511537108000,34],[1511537408000,34],[1511537708000,34],[1511538070000,85],[1511538370000,31],[1511538670000,31],[1511538971000,30],[1511539271000,30],[1511539571000,30],[1511539872000,30],[1511540172000,30],[1511540472000,30],[1511540773000,30],[1511936414000,25],[1511936714000,24],[1511937014000,85],[1511937315000,24],[1511937616000,24],[1511937916000,24],[1511938216000,24],[1511938517000,24],[1511938817000,24],[1511939117000,24],[1511939417000,24],[1511939718000,24],[1511940018000,24],[1511950908000,85],[1511951208000,23],[1511951509000,23],[1511951809000,23],[1511952109000,23],[1511952410000,23],[1511952710000,22],[1511953010000,22],[1511953310000,22],[1511953611000,22],[1511953911000,22],[1511954211000,22],[1511954512000,22],[1511954812000,22],[1511955112000,22],[1511955412000,22],[1511955713000,22],[1512056186000,31],[1512056486000,85],[1512056787000,30],[1512057087000,31],[1512057387000,30],[1512057688000,30],[1512057988000,30],[1512058289000,30],[1512058589000,30],[1512058889000,30],[1512059189000,30],]
now here is the html code:
$(document).ready(function() {
Highcharts.setOptions({
global: {
useUTC: false
}
});
chart = new Highcharts.Chart({
chart: {
renderTo: 'container',
//defaultSeriesType: 'spline',
},
title: {
text: 'Live random data'
},
events:{
load: refreshChart()
},
xAxis: {
type: 'datetime',
},
tooltip: {
valueSuffix: ' C'
},
yAxis: {
type: 'linear',
title: {
text: 'Temperature ( C)'
},
},
series: [{}]
});
$.getJSON("index.php", function(json) { /*Get the array data in data.php using jquery getJSON function*/
options.series[0].data = json; /*assign the array variable to chart data object*/
chart = new Highcharts.Chart(options); /*create a new chart*/
});
function refreshChart(){ /*function is called every set interval to refresh(recreate the chart) with the new data from data.php*/
setInterval(function(){
$.getJSON("index.php", function(json) {
options.series[0].data = json;
chart = new Highcharts.Chart(options);
});
},6000);
}
});
But the graph doesnt display anything? Anyhelp pls?
SOLVED!! I just converted the output of my array in the index.php.
$output[] = array(((float)($row["time"])),((int)($row["temperature"])));
in this way both the timestamp and the value of the temperature are both valid json.
I'm trying to create a highchart with irregular x axis, a bit like this: http://jsfiddle.net/gh/get/jquery/1.9.1/highslide-software/highcharts.com/tree/master/samples/highcharts/demo/spline-irregular-time/
I'm pulling my data from mySQL via PHP and processing in JSON format.
I can't get highcharts/JS to read the dates in date format - it seems to be pulling them as strings.
Here's my script:
$(document).ready(function() {
var options = {
chart: {
type: 'spline',
marginRight: 130,
marginBottom: 25
},
title: {
text: 'some title',
x: -20 //center
},
subtitle: {
text: '',
x: -20
},
xAxis: {
type: 'datetime',
dateTimeLabelFormats: { // don't display the dummy year
month: '%e. %b',
year: '%b'
},
categories: []
},
yAxis: {
title: {
text: 'L/min'
},
plotLines: [{
value: 0,
width: 1,
color: '#808080'
}]
},
plotOptions: {
spline: {
marker: {
enabled: true
}
}
},
tooltip: {
formatter: function() {
return '<b>'+ this.series.name +': '+
this.y +'</b><br>'+ this.x;
}
},
legend: {
layout: 'vertical',
align: 'right',
verticalAlign: 'top',
x: -10,
y: 100,
borderWidth: 0
},
series: []
}
$.getJSON("allreports/report.php", function(json) {
options.xAxis.categories = json[0]['data'];
options.series[0] = json[1];
options.chart.renderTo = 'container';
chart = new Highcharts.Chart(options);
});
and here's my PHP page:
<?php
$con = mysql_connect("localhost","db-user","db-pw");
if (!$con) {
die('Could not connect: ' . mysql_error());
}
mysql_select_db("db", $con);
$sth = mysql_query("SELECT v1,v2 FROM table");
$rows = array();
$rows['name'] = 'v1';
while($r = mysql_fetch_array($sth)) {
$rows['data'][] = $r['v1'];
}
$result = array();
array_push($result,$rows1);
array_push($result,$rows);
print json_encode($result, JSON_NUMERIC_CHECK);
mysql_close($con);
?>
This outputs the following:
[{"name":"medicinetime","data":["01,01,1970,01,00,00","01,01,1970,01,33,36","01,01,1970,01,33,36","01,01,1970,01,33,36"]},{"name":"units","data":[1,3,2,2]}]
But my chart is as follows:
Any thoughts on what I'm doing wrong please? What do I need to do to get PHP/JS to pick up on this array as a series of datetimes rather than strings?
Thank you!
You have two issues. First, you need to convert your date-component values into an actual Javascript date object. The format you're looking for for your series data is an array of X/Y pairs. It'll look like this, using your data:
[
[Date.UTC(1970,1,1,1,0,0),1],
[Date.UTC(1970,1,1,1,33,36),3],
[Date.UTC(1970,1,1,1,33,36),2],
[Date.UTC(1970,1,1,1,33,26),2]
]
Try something like this:
var xVals= json[0].data.map( item => {
var dateArr = point[0].join(',');
return Date.UTC(dateArr[2],dateArr[1],dateArr[0],dateArr[3],dateArr[4],dateArr[5]);
});
var yVals = json[1].data;
options.series[0] = {
name: json[1].name,
data: xVals.map( (x,i) => [x,yVals[i]])
}
Some documentation on valid formats for the series data is here: http://www.highcharts.com/docs/chart-concepts/series
Second, you have some duplicate X values there, and that's going to be confusing...you're going to want your timestamps to be unique, or it's going to be hard to make a line chart out of them.
I'm trying to plot data from a mysql table on document load with highcharts:
the html looks like that:
function FetchData(){
//alert("Fetching");
$.ajax({
url: 'php/reports/fetch_data.php',
success: function(data) {
dataTemp = [];
for(i=0;i<data.length;i++){
dataTemp.push(data[i][0]); // '1' index for getting that temp value. '0' for date.
}
c_temperature.series[0].data = dataTemp;
for(i=0;i<data.length;i++){
dataTemp.push(data[i][1]); // '1' index for getting that temp value. '0' for date.
}
c_temperature.series[1].data = dataTemp;
}
});
function DrawCharts(){
c_temperature = new Highcharts.Chart({
chart: {
renderTo: 'dashboard',
defaultSeriesType: 'spline',
},
title: {
text: 'Temperatur'
},
xAxis: {
type: 'datetime',
tickPixelInterval: 150,
maxZoom: 20 * 1000
},
yAxis: {
minPadding: 0.2,
maxPadding: 0.2,
title: {
text: 'Value',
margin: 10
}
},
legend:{
enabled: false
},
credits:{
enabled: false
},
series: [{
name: 'Temperatur',
data: []
}]
});
$(document).ready(function() {
DrawCharts();
FetchDevices();
FetchData();
});
<body>
<div id="dashboard">
</div>
<div class="clear"></div>
</body>
And the php I call looks like that:
try {
$con = new PDO("mysql:host=$servername; dbname=$dbname", $username, $password);#
echo 'Connected</br>';
$sql = "select ZEIT,FEUCHTE,TEMPERATUR,LUX,PITCH from ".$mac.
" order by ID";
foreach($con - > query($sql) as $row) {
$x = $row['ZEIT'];
/*$x = mktime()*1000;*/
$y_h = (float) $row['FEUCHTE'];
/*$y_t=(float)$row['TEMPERATUR'];
$y_l=(float)$row['LUX'];
$y_a=(float)$row['PITCH'];*/
$ret = array($x, $y_h, /*$y_t,$y_l,$y_a,$mac*/ );
echo json_encode($ret);
}
$con = null;
}
The php code successfully returns data.
But I dont see a graph and debugging with the browser console does not give a clue either. Any suggestions what I'm doing wrong?
Beste Regards
You want to use c_temperature.series[0].setData(dataTemp, true); and c_temperature.series[1].setData(dataTemp, true);. By setting the data, you're not actually telling highcharts to redraw the chart, so nothing is happening when you update the data.
I think it has to do with the order in wich you do your operations: firstly you create the chart and then you make the ajax call to fetch the data, but you are not updating the chart.
Try to move the chart creation inside the ajax success callback: first populate the series array with the data received from PHP, then construct the chart passing the serie array as a option; like this:
success: function(data) {
var data_series = [];
/* here populate the data_series array from your PHP results */
new Highcharts.Chart({
/* here other options... */
series: data_series
});
So this is what I'm doing now:
function FetchData(){
$.ajax({
type: "POST",
url: 'php/reports/fetch_data.php',
data: "",
dataType: 'json',
success: function(data) {
var points = data;
c_temperature = new Highcharts.Chart({
chart: {
renderTo: 'dashboard',
defaultSeriesType: 'spline',
},
title: {
text: 'Temperatur'
},
xAxis: {
type: 'datetime',
tickPixelInterval: 150,
maxZoom: 20 * 1000
},
yAxis: {
minPadding: 0.2,
maxPadding: 0.2,
title: {
text: '°C',
margin: 10
}
},
legend:{
enabled: false
},
credits:{
enabled: false
},
series: points
});
/*dataTemp = [];
for(i=0;i<data.length;i++){
dataTemp.push(data[0][i]);
}
c_temperature.series[0].setData(dataTemp, true);
for(i=0;i<data.length;i++){
dataTemp.push(data[1][i]);
}
c_temperature.series[1].setData(dataTemp, true);*/
}
});
}
Result: it is showing the graph but still no plot.
The php return has been changed to this:
try {
$con = new PDO("mysql:host=$servername; dbname=$dbname" ,$username, $password);
$sql = "select ZEIT,FEUCHTE,TEMPERATUR,LUX,PITCH from ".$mac." where ID>'60080' order by ID";
$x = array();
$y_h = array();
foreach ($con->query($sql) as $row)
{
$x[]=$row['ZEIT'];
$y_h[]=(float)$row['FEUCHTE'];
$ret = array($x,$y_h);
}
echo json_encode($ret);
$con = null;
}
I have successfully created a chart using High Chart to compare the expected time & arrival time of a patient.
However, I am now having an issue with the label of the columns; which is displaying time in milliseconds.
The screen shot below shows the issue:
How do I change the label to display time in format (H:M:S)
CODE:
<script type="text/javascript">
function drawChart(){
var chart = new Highcharts.Chart({
chart: {
renderTo: 'divforchart',
type:'column',
},
xAxis: {
name:'patients',
categories: [<?php
echo "'".$names[0]."'";
for($i = 1; $i < sizeof($names); $i++){
echo ",'".$names[$i]."'";
}
?>]
},
yAxis: {
type: 'datetime',
dateTimeLabelFormats: {
//force all formats to be hour:minute:second
second: '%H:%M:%S',
minute: '%H:%M:%S',
hour: '%H:%M:%S',
day: '%H:%M:%S',
week: '%H:%M:%S',
month: '%H:%M:%S',
year: '%H:%M:%S'
},
min: <?php echo "Date.UTC(".gmdate("Y,m,d,H",strtotime($minDate)).")";?>
},
series: [
{
name: 'Arrival time',
data: [<?php
echo "['".$names[0]."',Date.UTC(".gmdate("Y,m,d,H,i,s",strtotime($Arrival_time[0])).")]";
for($i = 1; $i < sizeof($names); $i++){
echo "
,['".$names[$i]."',Date.UTC(".gmdate("Y,m,d,H,i,s",strtotime($Arrival_time[$i])).")]";
}
?>]
},
{
name: 'Expected time',
data: [<?php
echo "['".$names[0]."',Date.UTC(".gmdate("Y,m,d,H,i,s",strtotime($Expected_time[0])).")]";
for($i = 1; $i < sizeof($names); $i++){
echo "
,['".$names[$i]."',Date.UTC(".gmdate("Y,m,d,H,i,s",strtotime($Expected_time[$i])).")]";
}
?>]
}
]
});
}
</script>
</head>
<body onLoad="drawChart()">
<div id="divforchart" style="height: 400px"></div>
</body>
Try with:
Highcharts.dateFormat(values)
See here: http://api.highcharts.com/highcharts#Highcharts.dateFormat%28%29
This if you want it in the serie, or you can change the tooltip.
series: [{
dataLabels: {
enabled: true,
formatter:function() {
return Highcharts.dateFormat('%H:%M:%S',this.y);
},
style:{color:"black"}
},
data: [data]
}]
Tooltip:
tooltip:{
formatter:function() {
return Highcharts.dateFormat('%H:%M:%S',this.y);
}
}
Your code must look like:
chart: {
renderTo: 'divforchart',
type:'column',
},
tooltip: { ...
By the look of it, you are referring to the tooltip, not the dataLabel.
You can use the formatter function to format the date properly:
http://api.highcharts.com/highcharts#tooltip.formatter
(if you are in fact talking about the dataLabel, you can do the same thing still: http://api.highcharts.com/highcharts#plotOptions.series.dataLabels.formatter )
I think the default is to numberFormat the y axis value, but you will want to instead use the dateFormat function in your formatter:
http://api.highcharts.com/highcharts#Highcharts.dateFormat%28%29
If you need help implementing, create a jsfiddle ( http://jsfiddle.net/ ) and post back