I have recently started working on Highchart. I dont have indepth knowledge. But I am still trying my level best. I have tried few codes, but I didn't get any results. The browser console is not loading anything and it is showing blank. Can you please help me in pointing out what to do next. I tried my level best. Please me out.
Here is my code:
Database Coding: php.data
<?php
//open connection to mysql db
$connection = mysqli_connect("localhost","root","root","demo") or die("Error " . mysqli_error($connection));
//fetch table rows from mysql db
$sql = "select * from project_requests";
$result = mysqli_query($connection, $sql) or die("Error in Selecting " . mysqli_error($connection));
//close the db connection
mysqli_close($connection);
?>
index.php
<!DOCTYPE HTML>
<?php
include_once 'data.php';
?>
<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=utf-8">
<title>Highcharts Example</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 () {
$('#container').highcharts({
chart: {
plotBackgroundColor: null,
plotBorderWidth: null,
plotShadow: false,
type: 'pie'
},
title: {
text: 'Browser market shares January, 2015 to May, 2015'
},
tooltip: {
pointFormat: '{series.name}: <b>{point.percentage:.1f}%</b>'
},
plotOptions: {
pie: {
allowPointSelect: true,
cursor: 'pointer',
dataLabels: {
enabled: true,
format: '<b>{point.name}</b>: {point.percentage:.1f} %',
style: {
color: (Highcharts.theme && Highcharts.theme.contrastTextColor) || 'black'
}
}
}
},
series: [{
type: 'pie',
name: 'Brands',
colorByPoint: true,
data: [
<?php
//$sql = mysqli_query("select * from project_requests")
while($res=mysql_fetch_array($sql)){
?>
['<?php echo $res['month']; ?>', 45.0],
<?php
}
?>
]
}]
});
});
</script>
</head>
<body>
<script src=
"https://code.highcharts.com/highcharts.js"></script>
<script src="https://code.highcharts.com/modules/exporting.js"></script>
<div id="container" style="min-width: 310px; height: 400px; max-width: 600px; margin: 0 auto"></div>
</body>
</html>
MY sql: Database Snapshot
Schema:: Demo Table:: project_requests
Related
I have had a look at my chart issue and I think the problem lies in the Highstock code. I have 2 other charts running the same php code and I have only changed from highchart to highstock.
I am trying to add a range selector in my chart. The code for that works in terms of showing the zoom and selector buttons but the date is now showing incorrectly.
I am drawing the data from an online MySQL data base so I its hard to run a demo for you.The timestamp format has worked in my other charts as mentioned.
This first code shows the date correctly
<?php
// 1-test.php
$servername = "localhost";
$dbname = "";
$username = "";
$password = "";
$conn = new mysqli($servername, $username, $password, $dbname);
if ($conn->connect_error) {
die("Connection failed: " . $conn->connect_error);
}
$sql = "SELECT id, value1, reading_time FROM Sensor order by reading_time desc limit 40";
$result = $conn->query($sql);
while ($data = $result->fetch_assoc()){
$sensor_data[] = $data;
}
$readings_time = array_column($sensor_data, 'reading_time');
$i = 0;
foreach ($readings_time as $reading){
$readings_time[$i] = date("d-M H:i", strtotime("$reading + 16 hours"));
$i += 1;
}
$value1 = json_encode(array_reverse(array_column($sensor_data, 'value1')), JSON_NUMERIC_CHECK);
$reading_time = json_encode(array_reverse($readings_time), JSON_NUMERIC_CHECK);
/*echo $value1;
echo $reading_time;*/
$result->free();
$conn->close();
?>
<!DOCTYPE html>
<html>
<meta name="viewport" content="width=device-width, initial-scale=1">
<meta http-equiv="refresh" content="30">
<link rel="icon" type="image/png" href="favicon.png">
<script src="https://code.highcharts.com/highcharts.js"></script>
<style>
body {
min-width: 310px;
max-width: 1500px;
height: 500px;
margin: 0 auto;
}
h2 {
font-family: Arial;
font-size: 2.5rem;
text-align: center;
}
</style>
<body>
<h2>Test page 2</h2>
<div id="chart-temperature" class="container"></div>
</div>
<script>
var value1 = <?php echo $value1; ?>;
var reading_time = <?php echo $reading_time; ?>;
var chartT = new Highcharts.Chart({
chart: { renderTo : 'chart-temperature',
type: 'spline'
},
title: { text: 'Roof Temperature' },
series: [{
showInLegend: false,
data: value1
}],
plotOptions: {
spline: { animation: false,
dataLabels: { enabled: true }
},
series: { color: '#059e8a' }
},
xAxis: {
type: 'datetime',
categories: reading_time
},
yAxis: {
title: { text: 'Temp (C)' }
},
credits: { enabled: false }
});
</script>
</body>
</html>
Then this code shows the date as Thursday,Jan 1, 00:00:00:001
<?php
$servername = "localhost";
$dbname = "";
$username = "";
$password = "";
$conn = new mysqli($servername, $username, $password, $dbname);
if ($conn->connect_error) {
die("Connection failed: " . $conn->connect_error);
}
$sql = "SELECT id, value1, reading_time FROM Sensor order by reading_time desc limit 40";
$result = $conn->query($sql);
while ($data = $result->fetch_assoc()){
$sensor_data[] = $data;
}
$readings_time = array_column($sensor_data, 'reading_time');
$i = 0;
foreach ($readings_time as $reading){
$readings_time[$i] = date("d-M H:i", strtotime("$reading + 16 hours"));
$i += 1;
}
$value1 = json_encode(array_reverse(array_column($sensor_data, 'value1')), JSON_NUMERIC_CHECK);
$reading_time = json_encode(array_reverse($readings_time), JSON_NUMERIC_CHECK);
/*echo $value1;
echo $reading_time;*/
$result->free();
$conn->close();
?>
<!DOCTYPE html>
<html>
<meta name="viewport" content="width=device-width, initial-scale=1">
<meta http-equiv="refresh" content="30">
<link rel="icon" type="image/png" href="favicon.png">
<script src="https://code.highcharts.com/stock/highstock.js"></script>
<script src="https://code.highcharts.com/stock/modules/data.js"></script>
<script src="https://code.highcharts.com/stock/modules/exporting.js"></script>
<style>
body {
min-width: 310px;
max-width: 1500px;
height: 500px;
margin: 0 auto;
}
h2 {
font-family: Arial;
font-size: 2.5rem;
text-align: center;
}
</style>
<body>
<h2>Test Page</h2>
<div id="chart-temperature" class="container"></div>
<script>
var value1 = <?php echo $value1; ?>;
var reading_time = <?php echo $reading_time; ?>;
var chartH = new Highcharts.stockChart({
chart: { renderTo : 'chart-temperature',
type: 'spline'
},
title: { text: 'Roof Temperature' },
series: [{
showInLegend: false,
data: value1
}],
plotOptions: {
spline: { animation: false,
dataLabels: { enabled: true }
},
series: { color: '#059e8a' }
},
rangeSelector: {
buttons: [{
type: 'day',
count: 3,
text: '3d'
}, {
type: 'week',
count: 1,
text: '1w'
}, {
type: 'month',
count: 1,
text: '1m'
}, {
type: 'month',
count: 6,
text: '6m'
}, {
type: 'year',
count: 1,
text: '1y'
}, {
type: 'all',
text: 'All'
}],
selected: 3
},
xAxis: {
type: 'datetime',
dateTimeLabelFormats: { second: '%H:%M:%S' },
categories: reading_time
},
yAxis: {
title: { text: 'Temp (C)' }
},
credits: { enabled: false }
});
</script>
</body>
</html>
the first screen shot is working. The second is the wrong date,
Any thoughts on how to change the date
The difference between the charts results from the fact that the second chart is a stock chart, which doesn't support categories on a x-axis. You need to use data in the [x, y] format.
var value1 = [18.10, 14.5];
var reading_time = ['2021-08-22 15:00:53', '2021-08-23 15:00:53'];
var seriesData = value1.map(function(val, index) {
return [new Date(reading_time[index]).getTime(), val];
});
Live demo: http://jsfiddle.net/BlackLabel/xLh7y8d6/
API Reference: https://api.highcharts.com/highcharts/xAxis.type
I am using HighCharts and im showing temperature on the graph. I was thinking that is it possible to show data for a single day only or 1 week or over a month using highchart graph. Right now I get all the data which is from the 1st record to the latest one from MySQL DB . Here is the code .
this is data.php -
<?php
$con = mysql_connect("192.168.100.107:3306","root","hannan786");
if (!$con) {
die('Could not connect: ' . mysql_error());
}
mysql_select_db("pi", $con);
$sth = mysql_query("SELECT * FROM temperature ");
$rows = array();
$rows['Temperature'] = 'temperature';
while($r = mysql_fetch_array($sth)) {
$rows['data'][] = $r['temperature'];
}
$result = array();
array_push($result,$rows);
print json_encode($result, JSON_NUMERIC_CHECK);
mysql_close($con);
?>
And this is the code for the main Page where the graph data is displayed -
<!DOCTYPE HTML>
<html>
<head>
<meta http-equiv="Refresh" Content="5">
<meta http-equiv="Content-Type" content="text/html; charset=utf-8">
<title>Temperature</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: 'Temperature',
x: -20 //center
},
subtitle: {
text: '',
x: -20
},
xAxis: {
categories: ['Temperature']
},
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>
Right Now I get this as output -
You can use the method setExtremes() of the Highcharts Api. You only have to provide min and max value, that in your case consists of the same Date Object, I think.
This is a fiddle as an example on how to use it.
chart.xAxis[0].setExtremes(
Date.UTC(2007, 0, 1),
Date.UTC(2007, 11, 31)
);
Docs are here: http://api.highcharts.com/highstock#Axis.setExtremes
I want to use my database data in series
my table “mob” is something like this :
![my table named "mob"][1]
Icost data in not real
And my code is like this :
<?php
include '../../class/jdf.php';
require_once "../../db.php";
$db = new db();
$query_time = "SELECT DISTINCT iDate FROM mob WHERE 1 ";
$datashow = $db->get_arr($query_time);
$time = array();
foreach ($datashow as $key => $row) {
$format = ' Y/m/d ';
$time[] = jdate($format, $row['iDate']);
}
$query_cost = "SELECT * FROM mob WHERE 1 ";
$data = $db->get_arr($query_cost);
$datamin = $db->get_field('mob','MIN(iCost)','1');
$datamin = $datamin -100;
$datamax = $db->get_field('mob','MAX(iCost)','1');
<!DOCTYPE HTML>
<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=utf-8">
<title>Highcharts Example</title>
<script src="../../js/jquery-1.9.1.min.js"></script>
<script src="../../js/highcharts.js"></script>
<style type="text/css">
</style>
<script type="text/javascript">
Highcharts.setOptions({
lang: {
numericSymbols: null
},
});
$(function() {
$('#container').highcharts({
chart:
{
type: 'column'
},
title: {
text: 'my chart '
},
subtitle: {
text: 'mob'
},
xAxis: {
categories: [
<?php
foreach ($time as $value) {
echo "'" . $value . "',";
}
?>
]
},
yAxis: {
min :<?php echo $datamin ?>,
max :<?php echo $datamax ?>,
title: {
text: 'cost'
}
},
tooltip: {
headerFormat: '<span style="font-size:10px">{point.key}</span><table>',
pointFormat: '<tr><td style="color:{series.color};padding:0">{series.name}: </td>' +
'<td style="padding:0"><b>{point.y:.1f} mm</b></td></tr>',
footerFormat: '</table>',
shared: true,
useHTML: true
},
plotOptions: {
column: {
pointPadding: 0.2,
borderWidth: 0
}
},
series: []
});
});
</script>
</head>
<body>
<script src="../../js/modules/exporting.js"></script>
<div id="container" style="min-width: 310px; height: 400px; margin: 0 auto"></div>
</body>
</html>
What should I write in series to have a chart like this
![my chart sample is like this][2]
// [1]: http://i.stack.imgur.com/WBJm5.jpg
// [2]: http://i.stack.imgur.com/DYZjm.jpg
Help me please .
Thank you
In your php, prepare correct array (according to avascript structure) and use json_encode(). In javasctrip call $.getJSON(), get data and use in the highcharts.
More information about preprocessing data, here
im trying to style my flot charts similar to this:
this is my current chart:
here is my chart code,
<?php
include('Includes/connect.php');
?>
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Strict//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-strict.dtd">
<html xmlns="http://www.w3.org/1999/xhtml" xml:lang="cs" lang="cs">
<head>
<meta http-equiv="Content-Type" content="text/html;charset=utf8"/>
<title>Index</title>
<script src="Includes/jquery-1.8.3.js"></script>
<script src="Includes/jquery.flot.js"></script>
<script src="Includes/jquery.flot.time.js"></script>
</head>
<?php
// Main query to pull data from 'tests' table
$sql = "SELECT UNIX_TIMESTAMP(`date`)*1000 AS unixDate,`date`, `test1`, `test2`, `test3`, `test4`, `test5`, `test6`, `test7`, `test8`, `test9`, `test10`, `test11`, `test12`, `test13`, `test14` FROM `tests` WHERE member_id = '1' ORDER by `date` ASC";
$result = mysql_query($sql) or die ("no query");
// Dataset1
while($row = mysql_fetch_assoc( $result )) {
$dataset1[] = array( $row['unixDate'], sprintf( "%.3f", $row['test1'] ));}
?>
<div id="chart1" style="width:700px;height:300px;"></div>
<script type="text/javascript">
//Chart1
var chart1Options = {
xaxis: {mode: "time", timeformat: "%Y-%m-%d"},
lines: { show: true, color: "#fff" },
points: { show: true },
grid: {
backgroundColor: { colors: ["#4ca8fa", "#2887da"] },
bordercolor: "#fff",
borderwidth: "60",
hoverable: true }
};
var dataset1 = { data: <?php echo json_encode($dataset1); ?>,};
$.plot($("#chart1"), [ dataset1 ], chart1Options);
</script>
</body>
</html>
can anyone help me out please? similar colours and also i cant seem to get hover data showing up either
thanks.
This should get you close to the appearance you want.
HTML:
<div id="placeholder" style="width:400px;height:300px;background-color: #6EB5F0"></div>
JS:
$(function () {
var plot = $.plot($("#placeholder"),[
{ data: [[0,0],[1,1],[2,4],[3,3],[4,5],[5,7],[6,9],[7,10],[8,8],[9,12]], color: 'white'}
], {
series: {
lines: { show: true, fill: true, fillColor: 'rgba(143, 198, 242, 0.7)' },
points: { show: true}
},
grid: { color: 'transparent' },
xaxis: {
color: 'white',
font: { color: 'white', family: 'sans-serif', size: 11}
},
yaxis: {
color: 'white',
font: { color: 'white', family: 'sans-serif', size: 11}
}
});
});
Result:
Fiddle here.
As far as your hover tooltips not working, there's a great example here. Follow that and if you still can't get it working, update your question with specifics and a minimal code sample that demonstrates the problem.
I'm having a table in MySQL with the following data
Buy_client Amount
ABC 6597
XYZ 4479
PQR 2075
qqq 1706
ttt 1030
Other 450
I want to show the following data in a Pie Chart in High Charts. Someone please help me with this. I'm new to both PHP and HighCharts
Question 1: I need to Create a Pie chart from this data
Question 2: I'm using HighCharts for this. Someone please help me to do this in HighCharts
I have used the following code to do this but it doesn't show the info in a pie chart but just display the data in the web browser
<!DOCTYPE HTML>
<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=utf-8">
<title>Highcharts Example</title>
<?php
$con = mysql_connect("localhost","root","");
if (!$con) {
die('Could not connect: ' . mysql_error());
}
mysql_select_db("offlinesurv", $con);
$my_data = mysql_query("SELECT * FROM top_buy_clients");
while($row = mysql_fetch_array($my_data)) {
echo $row['buy_client'] . "\t" . $row['qty']. "\n";
}
?>
<script type="text/javascript" src="js/jquery.js"></script>
<script type="text/javascript">
$(function () {
var chart;
$(document).ready(function() {
chart = new Highcharts.Chart({
chart: {
renderTo: 'container',
plotBackgroundColor: null,
plotBorderWidth: null,
plotShadow: false
},
title: {
text: 'Browser market shares at a specific website, 2010'
},
tooltip: {
pointFormat: '{series.name}: <b>{point.percentage}%</b>',
percentageDecimals: 1
},
plotOptions: {
pie: {
allowPointSelect: true,
cursor: 'pointer',
dataLabels: {
enabled: true,
color: '#000000',
connectorColor: 'green',
formatter: function() {
return '<b>'+ this.point.name +'</b>: '+ this.percentage +' %';
}
}
}
},
series: [{
type: 'pie',
name: 'Browser share',
data: [ <?php echo $row; ?>]
}]
});
});
});
</script>
</head>
<body>
<script src="js/highcharts.js"></script>
<script src="js/exporting.js"></script>
<div id="container" style="min-width: 400px; height: 400px; margin: 0 auto"></div>
</body>
</html>
In your php...where you make the query to the database....in the while loop, you need to construct and string and in the end of the loop the string should looks like:
$my_data = "['ABC', 6597],
['XYZ', 4479],
['PQR', 2075],
['qqq', 1706],
['ttt', 1030],
['Others', 450] ";
Then in your javascript file, you should have a line like this
series: [{
type: 'pie',
name: 'Pie Data',
data: [
<?php echo $my_data; ?>
]
}]
It's very simple.
Saludos.