Related
Firstly I apologise, I am not a programmer (but I am learning - slowly). I am interested in graphs for Horticultural applications. I have a database that gets data from sensors on an hourly basis and the query grabs the last 12 to 48 readings, according to the select statement. With help from your forum, I have created 3 files that together extract the data from MySQL to plot a graph with multiple series of: Timestamp (with various options for display), temperature and humidity.
I based my work on this example in fiddle https://jsfiddle.net/gh/get/library/pure/highcharts/highcharts/tree/master/samples/highcharts/demo/line-basic which uses data provided 'in the script' but after three weeks I can't inject the data from JSON
The first of my files makes the MySQL db connection, the second file extracts and formats the data into JSON data and the third is supposed to create the graph but doesn't :-(.
this is what is produced with a series label for each row, rather than a line for each series.
Can you help me? I would like a line graphs showing temperature and humidity. Time/date along the bottom x-axis, the left y-axis temperature in degrees and a right-hand y-axis showing percentage humidity. Am I asking too much?
Finally can I please request no Ajax, or other "stuff" other than php, html, JSON, and javascripts if possible?
Any help on formatting my question would be much appreciated :-)
<?php $json_data = include ('nw_database02.php');?>
<!DOCTYPE HTML>
<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=utf-8"/>
<meta name="viewport" content="width=device-width, initial-scale=1">
<title>Line Graph</title>
</head>
<body>
<script src="https://code.highcharts.com/highcharts.js"></script>
<script src="https://code.highcharts.com/modules/exporting.js"></script>
<script src="https://code.highcharts.com/modules/export-data.js"></script>
<script src="https://code.highcharts.com/modules/accessibility.js"></script>
<script src="https://code.highcharts.com/modules/series-label.js"></script>
<div id="container"></div>
<script type="text/javascript">
Highcharts.chart('container', {
title: {
text: 'Temperature and Humidity'
},
subtitle: {
text: 'Source: Greenhouse1'
},
yAxis: {
title: {
text: 'Temperature'
}
},
legend: {
layout: 'vertical',
align: 'right',
verticalAlign: 'middle'
},
plotOptions: {
series: {
label: {
connectorAllowed: false
},
pointStart: 2010
}
},
series: <?= $json_data?> ,
responsive: {
rules: [{
condition: {
maxWidth: 500
},
chartOptions: {
legend: {
layout: 'horizontal',
align: 'center',
verticalAlign: 'bottom'
}
}
}]
}
});
</script>
</body>
</html>
...
If I echo the $json_data I get this type of result, but bear in mind it is dynamic data and changes every hour so it must be read from json_data every time the page is accessed:
[{"Timestamp":"10:04 02/01/21","temperature":"5","humidity":"66"},{"Timestamp":"10:19 02/01/21","temperature":"6","humidity":"65"},{"Timestamp":"10:35 02/01/21","temperature":"6","humidity":"64"},{"Timestamp":"10:50 02/01/21","temperature":"6","humidity":"64"},{"Timestamp":"11:06 02/01/21","temperature":"6","humidity":"64"},{"Timestamp":"11:21 02/01/21","temperature":"7","humidity":"63"},{"Timestamp":"11:34 02/01/21","temperature":"10","humidity":"66"},{"Timestamp":"04:21 02/01/21","temperature":"15","humidity":"64"},{"Timestamp":"04:36 02/01/21","temperature":"16","humidity":"61"},{"Timestamp":"04:51 02/01/21","temperature":"15","humidity":"59"},{"Timestamp":"05:07 02/01/21","temperature":"15","humidity":"60"},{"Timestamp":"05:22 02/01/21","temperature":"14","humidity":"61"}]
You need to format your data to the series structure required by Highcharts. The rest of the requirements are achievable by using chart options - please check xAxis and yAxis properties in API.
var data = <?= $json_data?>
var series = [{
name: "temperature",
data: []
},
{
name: "humidity",
data: [],
yAxis: 1
}
];
data.forEach(function(dataEl) {
series[0].data.push([
new Date(dataEl.Timestamp).getTime(),
Number(dataEl.temperature)
]);
series[1].data.push([
new Date(dataEl.Timestamp).getTime(),
Number(dataEl.humidity)
]);
});
Highcharts.chart('container', {
series: series,
yAxis: [{
title: {
text: 'temperature'
}
},
{
title: {
text: 'humidity'
},
opposite: true
}
],
xAxis: {
type: 'datetime'
}
});
Live demo: http://jsfiddle.net/BlackLabel/aw95vek6/
API Reference: https://api.highcharts.com/highcharts/series.line.data
you can achive with below code but when you choosing chart first know the purpose and create json data accroding to the series use apexcharts for free
<script type="text/javascript">
var data=[{"Timestamp":"10:04 02/01/21","temperature":"5","humidity":"66"},{"Timestamp":"10:19 02/01/21","temperature":"6","humidity":"65"},{"Timestamp":"10:35 02/01/21","temperature":"6","humidity":"64"},{"Timestamp":"10:50 02/01/21","temperature":"6","humidity":"64"},{"Timestamp":"11:06 02/01/21","temperature":"6","humidity":"64"},{"Timestamp":"11:21 02/01/21","temperature":"7","humidity":"63"},{"Timestamp":"11:34 02/01/21","temperature":"10","humidity":"66"},{"Timestamp":"04:21 02/01/21","temperature":"15","humidity":"64"},{"Timestamp":"04:36 02/01/21","temperature":"16","humidity":"61"},{"Timestamp":"04:51 02/01/21","temperature":"15","humidity":"59"},{"Timestamp":"05:07 02/01/21","temperature":"15","humidity":"60"},{"Timestamp":"05:22 02/01/21","temperature":"14","humidity":"61"}];
console.log(data);
var timestamp=[];
var temperature=[];
var humidity=[];
$.each(data, function(i, item) {
console.log(data[i]);
timestamp.push(data[i].Timestamp);
temperature.push(data[i].temperature);
humidity.push(data[i].humidity);
});
Highcharts.chart('container', {
title: {
text: 'Solar Employment Growth by Sector, 2010-2016'
},
subtitle: {
text: 'Source: thesolarfoundation.com'
},
yAxis: {
title: {
text: 'Number of Employees'
}
},
xAxis: {
categories: timestamp,
},
legend: {
layout: 'vertical',
align: 'right',
verticalAlign: 'middle'
},
plotOptions: {
series: {
label: {
connectorAllowed: false
},
pointStart: 2010
}
},
series: [{
name: 'temperature',
data: temperature
}, {
name: 'humidity',
data: humidity
}],
responsive: {
rules: [{
condition: {
maxWidth: 500
},
chartOptions: {
legend: {
layout: 'horizontal',
align: 'center',
verticalAlign: 'bottom'
}
}
}]
}
});
</script>
I am trying to draw a line graph using high-charts. I am facing a strange problem that is the contents or data fetching from database are not showing or the graph is not drawing at all.
There is no any PHP error as I already checked by error reporting on. Also there is no any error on console.
But when I am accessing my data.php file. It shows the contents like this
[{"name":"Month","data":["Mar","Mar","Mar","Mar","Mar","Mar","Mar","Mar","Mar","Mar","Mar","Mar","Mar","Mar","Mar","Mar","Mar","Apr","Apr","Apr","Apr","Apr","Apr","Apr","Apr","Apr","Apr","Apr","Apr","Apr","Apr","Apr","Apr","Apr","Apr","Apr","Apr","Apr","Apr","Apr","Apr","Apr","Apr","Apr","Apr","Apr","Apr","Apr","Apr","Apr","Apr","","Jul","Jul","Jul","Jul","Jul","Jul","Jul","Jul","Jul","Jul","Jul","Jul","Jul","Jul"]},
{"name":"Name","data":["Direct Sales","Search Engine Marketing","PPC Advertising","Website Marketing","Blog Marketing","Social Media Marketing","Email Marketing","Online PR","Multimedia Marketing","Mobile Marketing","Display Advertising","Direct Sales","Search Engine Marketing","PPC Advertising","Website Marketing","Blog Marketing","Social Media Marketing","Email Marketing","Online PR","Multimedia Marketing","Mobile Marketing","Display Advertising"]}]
Actually this is the content that I want to be shown on graph.
I did not find any solution to this.
Please help me to know that where I am going wrong.
Hope I have explained my issue well!
index.php
<?php
ini_set('display_errors', 1);
include './includes/db_connection.php';
?>
<!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">
$(function () {
var chart;
$(document).ready(function() {
$.getJSON("data.php", function(json) {
chart = new Highcharts.Chart({
chart: {
renderTo: 'container',
type: 'line',
marginRight: 130,
marginBottom: 25
},
title: {
text: 'Month Vs Names',
x: -20 //center
},
subtitle: {
text: '',
x: -20
},
xAxis: {
categories: ['Jan', 'Feb', 'Mar', 'Apr', 'May', 'Jun', 'Jul', 'Aug', 'Sep', 'Oct', 'Nov', 'Dec']
},
yAxis: {
title: {
text: 'Amount'
},
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: json
});
});
});
});
</script>
</head>
<body>
<script src="http://code.highcharts.com/highcharts.js"></script>
<script src="http://code.highcharts.com/modules/exporting.js"></script>
<div id="container" style="min-width: 400px; height: 400px; margin: 0 auto"></div>
</body>
</html>
data.php
ini_set('display_errors', 1);
include './includes/db_connection.php';
//$check = "SELECT month FROM activities";
$sth1 = mysqli_query($link,"SELECT month FROM activities");
//print_r($sth1);
//die($check."<br/><br/>".mysql_error());
$rows = array();
$rows['name'] = 'Month';
while($r = mysqli_fetch_array($sth1)) {
$rows['data'][] = $r['month'];
}
//$check1 = ;
$sth = mysqli_query($link,"SELECT name FROM web_marketing");
//print_r($sth);
//die($check."<br/><br/>".mysql_error());
$rows1 = array();
$rows1['name'] = 'Name';
while($rr = mysqli_fetch_assoc($sth)) {
$rows1['data'][] = $rr['name'];
}
$result = array();
array_push($result,$rows);
array_push($result,$rows1);
echo json_encode($result,JSON_NUMERIC_CHECK);
You need to check the format of json that set in series object.
series: json
First, data of Series object would have to be number format (etc. 0.23 or 6).
and I didn't understand where you want to set display those contents (title or tooltip on graph?),
Anyway, under the contents will be displayed in chart, if you set the name's value of Series object or categories object of xAxis.
"Direct Sales","Search Engine Marketing","PPC Advertising","Website Marketing","Blog Marketing","Social Media Marketing","Email Marketing","Online PR","Multimedia Marketing","Mobile Marketing","Display Advertising","Direct Sales","Search Engine Marketing","PPC Advertising","Website Marketing","Blog Marketing","Social Media Marketing","Email Marketing","Online PR","Multimedia Marketing","Mobile Marketing","Display Advertising"
I have wrote chart's example below. hope that it works for you.
http://jsfiddle.net/uv7cvfsb/1/
also, maybe this picture will help to understand about the structure of Highchart.
http://4.bp.blogspot.com/-8U9LxYsbp1k/UDUYsSJxN_I/AAAAAAAAAtk/SNWsEJUIGu8/s1600/highcharts.png
if you want to ask defferent things, please leave a comment.
i have to create a single chart showing different series with different type of chart (Ex: one data series with 'areaspline' and one data series with 'column'). I built a db with a lot of data, extracted by sql query into a json file
[
{ "name": "Test", "data": [2.8,2.8,2.8,2.7,2.7,] },
{ "name": "kwc", "data": [10,1,10,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0] }
]
The json file is correct, but if i try to select the series for a chart with the $.each function it doesn't work!
Here's my code
<!DOCTYPE HTML>
<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=utf-8">
<title>Highcharts Example</title>
<script src="estrazione.php"></script>
<script type="text/javascript" src="http://ajax.googleapis.com/ajax/libs/jquery/1.8.2/jquery.min.js"></script>
<script type="text/javascript">
$(function () {
$.getJSON("new3.php", function(json) {
$.each(json.data, function(index, item){
// split the data set into ohlc and volume
var temperatura = [],
misura = [],
dataLength = json.length;
for (i = 0; i < dataLength; i++) {
temperatura.push([
data[i][0]
]);
misura.push([
data[i][1]
])
}
$('#container').highcharts({
chart: {
zoomType: 'xy'
},
title: {
text: 'Analisi Temperature e Consumo Generale',
},
xAxis: [{
categories: ['00.00', '00.15', '00.30', '00.45', '01.00', '01.15', '01.30', '01.45', '02.00', '02.15', '02.30', '02.45', '03.00', '03.15', '03.30', '03.45', '04.00', '04.15', '04.30', '04.45', '05.00', '05.15', '05.30', '05.45', '06.00', '06.15', '06.30', '06.45', '07.00', '07.15', '07.30', '07.45', '08.00', '08.15', '08.30', '08.45', '09.00', '09.15', '09.30', '09.45', '10.00', '10.15', '10.30', '10.45', '11.00', '11.15', '11.30', '11.45', '12.00', '12.15', '12.30', '12.45', '13.00', '13.15', '13.30', '13.45', '14.00', '14.15', '14.30', '14.45', '15.00', '15.15', '15.30', '15.45', '16.00', '16.15', '16.30', '16.45', '17.00', '17.15', '17.30', '17.45', '18.00', '18.15', '18.30', '18.45', '19.00', '19.15', '19.30', '19.45', '20.00', '20.15', '20.30', '20.45', '21.00', '21.15', '21.30', '21.45', '22.00', '22.15', '22.30', '22.45', '23.00', '23.15', '23.30', '23.45'],
}],
yAxis: [{ // Primary yAxis
labels: {
format: '{value}°C',
style: {
color: '#89A54E'
}
},
title: {
text: 'Temperature',
style: {
color: '#89A54E'
}
}
}, { // Secondary yAxis
title: {
text: 'Consumo',
style: {
color: '#4572A7'
}
},
labels: {
format: '{value} Kw',
style: {
color: '#4572A7'
}
},
opposite: true
}],
tooltip: {
shared: true
},
legend: {
layout: 'vertical',
align: 'left',
x: 120,
verticalAlign: 'top',
y: 100,
floating: true,
backgroundColor: '#FFFFFF'
},
series: [{
name: 'Misure',
color: '#4572A7',
type: 'column',
yAxis: 1,
data: misura,
tooltip: {
valueSuffix: ' Kw'
}
}, {
name: 'Temperature',
color: '#89A54E',
type: 'spline',
data: temperatura,
tooltip: {
valueSuffix: '°C'
}
}]
});
});
</script>
</head>
<body>
<script src="js/highcharts.js"></script>
<script src="js/modules/exporting.js"></script>
<div id="container" style="min-width: 310px; height: 400px; margin: 0 auto"></div>
</body>
</html>'
this is my php code:
<?php
$data_scelta = "2013-08-08";
$misura = "kwc";
$temperatura = "Test";
$link = mysqli_connect('localhost:3306', 'root', '','telegestione');
if (!$link) {
die('Could not connect: ' . mysqli_error());}
$sth = mysqli_query($link,"SELECT $temperatura FROM temperature WHERE dataora BETWEEN '$data_scelta 00:00:00.000'
AND '$data_scelta 23:59:59.997'");
$rows = array();
$rows['name'] = $temperatura;
while($r = mysqli_fetch_assoc($sth)) {
$rows['data'][] = $r[$temperatura];}
$sth = mysqli_query($link,"SELECT $misura FROM misure WHERE dataora BETWEEN '$data_scelta 00:00:00.000'
AND '$data_scelta 23:59:59.997'");
$rows1 = array();
$rows1['name'] = $misura;
while($rr = mysqli_fetch_assoc($sth)) {
$rows1['data'][] = $rr[$misura];}
$result = array();
array_push($result,$rows);
array_push($result,$rows1);
print json_encode($result, JSON_NUMERIC_CHECK);
?>
I tryed any kind of option, but anything gone right :(
Any hope to display 1 chart, 2 or more data series and 2 or more type of charts?
Thanks in advance
It looks like your highcharts creation call is within your $.each function. So it will try to create 2 highcharts, but they both will be created in the same div, so you'll only end up with one.
Also, the way you are caculating datalength, it'll be 2. When, it appears, you'd like it to be the length of the actual data (which is different for your different series).
I can't do the getJSON in a jsfiddle, so I'm assuming your PHP code is creating the json object you listed (and it looks like it would). You can lose the each loop alltogether and set your 2 series like this:
series: [{
name: 'Misure',
color: '#4572A7',
type: 'column',
yAxis: 1,
data: json[1].data,
tooltip: {
valueSuffix: ' Kw'
}
}, {
name: 'Temperature',
color: '#89A54E',
type: 'spline',
data: json[0].data,
tooltip: {
valueSuffix: '°C'
}
}]
http://jsfiddle.net/bhlaird/dUkuY/
I am trying to get data from my mysql into Highcharts bar graph. I have the data from mysql that includes a port number and average bytes per port. Here is what I have for my php query and html page. The data (average bytes) shows up on the graph just fine. I can't get the categories (port) data to display.
<?php
$con = mysql_connect("localhost","root","kdkdkdk") or die(mysql_error());
mysql_select_db("silk", $con);
$result = mysql_query("SELECT dstPortNum,avgByte FROM statistic_avgbytesport ORDER BY avgByte DESC LIMIT 10;");
$rows = array();
while($r = mysql_fetch_array($result)) {
$row[0] = $r[0];
$row[1] = $r[1];
array_push($rows,$row);
}
print json_encode($rows, JSON_NUMERIC_CHECK);
#print json_encode($rows[0][0], JSON_NUMERIC_CHECK);
mysql_close($con);
?>
And my html page to display the graph.
<!DOCTYPE HTML>
<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=utf-8">
<title>Highcharts Pie Chart</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: 'avgbytes'
},
title: {
text: 'Average Bytes Per Port'
},
pane: {
size:'80%'
},
xAxis: {
title: {
text: 'PORTS'
},
categories: []
},
yAxis: {
min: 0,
title: {
text: 'Bytes'
}
},
series: [{
type: 'bar',
name: 'Average Bytes',
data: []
}]
}
$.getJSON("averageBytesPerPort.php", function(json) {
options.series[0].data = json;
chart = new Highcharts.Chart(options);
});
});
</script>
<script src="http://code.highcharts.com/highcharts.js"></script>
<script src="http://code.highcharts.com/highcharts-more.js"></script>
</head>
<body>
<div id="avgbytes" style="width: 300px; height: 300px; margin: 0 auto"></div>
</body>
</html>
You can use something like this:
$.getJSON("averageBytesPerPort.php", function(json) {
var options = {
chart: {
renderTo: 'avgbytes'
},
title: {
text: 'Average Bytes Per Port'
},
pane: {
size:'80%'
},
xAxis: {
title: {
text: 'PORTS'
},
categories: data.categories
},
yAxis: {
min: 0,
title: {
text: 'Bytes'
}
},
series: [{
type: 'bar',
name: 'Average Bytes',
data: data
}]
}
chart = new Highcharts.Chart(options);
});
how the hell on earth your data is shown , you have not put the $conn as the second parameter of the
mysql_query();
it should be
$result = mysql_query("SELECT dstPortNum,avgByte FROM statistic_avgbytesport ORDER BY avgByte DESC LIMIT 10;",$conn);
I'm trying to display data from MSSQL. I saw an example at http://www.blueflame-software.com/blog/using-highcharts-with-php-and-mysql.
Value of Y Axis already good, but the X axis cannot display on my chart, so the value of chart only in 0 Xaxis,
data.php
mssql_select_db("CU-CAB01", $con);
$result = mssql_query("select count(nba) sumnba, datein from tbl_anggota where tgl_masuk > '2012-06-01'group by tgl_masuk");
while($row = mssql_fetch_array($result)) {
echo $row['tgl_masuk'] . "\t" . $row['jumlah']. "\n";
index.php
<script type="text/javascript" src="js/jquery-1.7.1.min.js" ></script>
<script type="text/javascript" src="js/highcharts.js" ></script>
<script type="text/javascript" src="js/themes/dark-blue.js"></script>
<script type="text/javascript">
var chart;
$(document).ready(function() {
var options = {
chart: {
renderTo: 'container',
defaultSeriesType: 'line',
marginRight: 130,
marginBottom: 25
},
title: {
text: 'Hourly Visits',
x: -20 //center
},
subtitle: {
text: '',
x: -20
},
xAxis: {
type: 'datetime',
tickInterval: 10000 * 1000, // one hour
tickWidth: 0,
gridLineWidth: 1,
labels: {
align: 'center',
x: -3,
y: 20,
formatter: function() {
return Highcharts.dateFormat('%e', this.value);
}
}
},
yAxis: {
tickInterval: 2,
title: {
text: 'Anggota'
},
plotLines: [{
value: 0,
width: 1,
color: '#808080'
}]
},
tooltip: {
formatter: function() {
return Highcharts.dateFormat('%l%p', this.x-(1000*3600)) +'-'+ Highcharts.dateFormat('%l%p', this.x) +': <b>'+ this.y + '</b>';
}
},
legend: {
layout: 'vertical',
align: 'right',
verticalAlign: 'top',
x: -10,
y: 100,
borderWidth: 0
},
series: [{
name: 'Count'
}]
}
jQuery.get('data.php', null, function(tsv) {
var lines = [];
traffic = [];
try {
// split the data return into lines and parse them
tsv = tsv.split(/\n/g);
jQuery.each(tsv, function(i, line) {
line = line.split(/\t/);
date = Date.parse(line[0] +' UTC');
traffic.push([
date,
parseInt(line[1].replace(',', ''),10)
]);
});
} catch (e) { }
options.series[0].data = traffic;
chart = new Highcharts.Chart(options);
});
});
</script>
and my data in tbl_anggota query result like this
sumnba datein
1 2012-07-03 00:00:00.000
4 2012-07-04 00:00:00.000
5 2012-07-05 00:00:00.000
5 2012-07-06 00:00:00.000
2 2012-07-16 00:00:00.000
5 2012-07-17 00:00:00.000
1 2012-07-18 00:00:00.000
2 2012-07-19 00:00:00.000
I think my mistake in parsing data with jquery on datein field, so my Xaxis only in null value..
Can someone get my chart to display the Xaxis value?
If you output query is like above, you have your X and Ys reversed in your parsing. The date field is after the count field:
// split the data return into lines and parse them
tsv = tsv.split(/\n/g);
jQuery.each(tsv, function(i, line) {
line = line.split(/\t/);
date = Date.parse(line[1] +' UTC'); //your datin is after the '\t'
traffic.push([
date,
parseInt(line[0].replace(',', ''),10) //your count is before the '\t'
]);
});
And please, please fix the empty catch block. Ignore errors in a critical section of code is never a good idea.