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
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 this code for the Highchart column:
$(function () {
$('#container').highcharts({
chart: {
type: 'column'
},
xAxis: {
type: 'category',
},
yAxis: {
min: 0,
},
...
series: [{
data: [
['Shanghai', 23.7],
['Lagos', 16.1],
['Istanbul', 14.2],
['Karachi', 14.0],
],
}]
});
});
and this file query.php:
<?php
include 'bd_cnx.php';
$sql = "SELECT
...";
$result = $conn->query($sql);
if ($result->num_rows > 0){
while($row = $result->fetch_assoc()){
$ret[] =[$row['NUME_J'], floatval($row['TOTAL'])];
}
}
echo json_encode($ret);
?>
How can I insert the returned values from query.php in the function javascript to series.data?
Thank you!
var data ;
$.ajax({
method:"POST",
url:"query.php",
data:{},
success:
function(response){
data=response;
$('#container').highcharts({
chart: {
type: 'column'
},
xAxis: {
type: 'category',
},
yAxis: {
min: 0,
},
...
series: [{
data: data,
}]
});
},
});
It's covered in the documentation, with examples. Check out their web site: - you may find even more useful ideas. BTW, remember to send the correct JSON Content-Type, or some browsers may balk.
This is one way:
$(function () {
// Get the CSV and create the chart
$.getJSON('https://www.highcharts.com/samples/data/jsonp.php?filename=analytics.csv&callback=?', function (csv) {...
You can also get live data.
Finally, you can assign the series variable in several ways, and redraw the chart.
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 have some problem with this.
i want to make a barchart with xAxis = day from 1-31 ( for this month)
this is my table: http://prntscr.com/4xaljv
case : i have average price Execpt the promo price : 1.000.000
how can i use that data to make a barchart like this one :
http://prntscr.com/4xal4p
anyone can help or make some sugestion about this case?
im trying using high chart and make some problem with value of each date.
this is my code:
<script type="text/javascript">
var chart1; // globally available
$(document).ready(function() {
chart1 = new Highcharts.Chart({
chart: {
renderTo: 'container',
type: 'column'
},
title: {
enabled: false
},
xAxis: {
categories: ['1']
},
legend: {
enabled: false
},
yAxis: {
title: {
text: 'Jumlah Penduduk'
}
},
series:
[
<?php
for ($day=1; $day <= $num ; $day++) {
while($k<count($tglevent)){
if($day==$tglevent[$k]){
$promo = $hargapromo[$k];
break;
}
$k++;
}
if ($hargapromo[$k] != NULL || $hargapromo[$k] > 0) {
$harga_promo = ($promo+$data_rata2->average)/2;
}else{
$harga_promo = $data_rata2->average;
}
?>
{
name: [<?= $day ?>],
data: [<?= $data_rata2->average ?>]
},
<?php
}
?>
]
});
});
</script>
Your SQL should be something like this:
SELECT date, avg(price) FROM myTable GROUP BY 1
This will give you the average prive per day, no need (more speed) to calculate it in your program.
Note that you can use MySQLs data-Functions as well:
SELECT year(date), month(date), day(date), avg(price) FROM myTable GROUP BY 1,2,3
I have been able to produce results from mysql using:
$myArray=array();
$tempArray = array();
// Get all records
while ( $row = $results->fetch_assoc())
{
$tempArray = $row;
array_push($myArray, $tempArray);
}
echo json_encode($myArray);
$mysqli->close();
?>
And I then included this to produce a chart on my page index.php by using the following Javascript.
what concepts/code am I not understanding/missing to produce a chart based upon my ajax json?
EDITED - SOLUTION:
Final PHP code to produce the json:
while ( $row = $results->fetch_assoc())
{
$tempArray[0] = $row['unix_timestamp(auct.end_date)'];
$tempArray[0] *= 1000;
$tempArray[1] = $row['winning_bid'];
array_push($myArray, $tempArray);
}
echo json_encode ($myArray, JSON_NUMERIC_CHECK);
$mysqli->close();
?>
Final javascript code:
$('#btn_search').click(function(){
txt_search = $('#txt_search').val();
$.ajax({
url: './php/search.php',
type: 'GET',
data: {search: txt_search},
dataType: 'json',
success: function(rows)
{
chart = new Highcharts.Chart({
chart: {
renderTo: 'chartdiv',
type: 'line',
marginRight: 100,
marginBottom: 50
},
title: {
text: 'Whisky Tracking',
x: -20 //center
},
xAxis: {
text: 'EndDate',
type: 'datetime'
},
yAxis: {
title: {
text: 'Price',
color: '#CC680E'
},
plotLines: [{
value: 0,
width: 20,
color: '#CC680E'
}]
},
series: [{
name: txt_search,
xAxis:0,
data: rows,
dataLabels: {
enabled: true,
formatter: function() {
return '£'+ Highcharts.numberFormat(this.y, 0);
}
}
}],
});
}
});
goToByScroll('tracker');
return false;
});
Sample Data from the JSON:
[1306732000000,160],[1306745000000,45],[1306788000000,65],[1306788000000,50],[1306712000000,130],[1306733000000,240],[1306744000000,60],[1306788000000,250],[1306710000000,145]
The problem is that values are strings, for example, your data:
["2011-05-30 00:00:00","130"]
Should be instead:
[1306706400000, 130]
To it's timestamp in ms and true value.
You can read about JSON_NUMERIC_CHECK option for json_encode(string, JSON_NUMERIC_CHECK) to change strings to numbers. But dates to timestamps you need to change on your own.
Edit:
Also the problem was with setting data in doubled array, changed from:
data: [rows]
to:
data: rows