I have 3 graphs and I want to put one of them to another place on the local host screen. But I'm a beginner on php and I have no idea is it possible or how can I do that. Can you give me any advice for it ? How can I do that ? Thanks.
My HTML codes:
<!DOCTYPE HTML>
<html>
<head>
<script type="text/javascript">
window.onload = function () {
var chart = new CanvasJS.Chart("chartContainer",
{
title:{
text: "RR Interval Time Series"
},
data: [
{
type: "line",
dataPoints: [
<?PHP
foreach($arr as $key => $v){
$output[] = "{ x: " . $x[$key] . ", y: " . $v . " }";
}
echo implode(",\n", $output);
?>
]
}
]
});
var data = <?php echo json_encode($wshort, JSON_NUMERIC_CHECK); ?>;
data = data.map(function (row, index) {
return {
x: index,
y: row
};
});
var chart2 = new CanvasJS.Chart("chartContainer2", {
title: {
text: "FFT Results"
},
data: [{
type: "line",
dataPoints: data
}]
});
var chart3 = new CanvasJS.Chart("chartContainer3",
{
title:{
text: "Poincare Plot"
},
data: [
{
type: "scatter",
dataPoints: [
<?PHP
foreach($pointy as $key1 => $v1){
$output1[] = "{ x: " . $pointx[$key1] . ", y: " . $v1 . " }";
}
echo implode(",\n", $output1);
?>
]
}
]
});
chart.render();
chart2.render();
chart3.render();
}
</script>
<script type="text/javascript" src="https://canvasjs.com/assets/script/canvasjs.min.js"></script></head>
<body>
<div id="chartContainer" style="height: 200px; width: 70%;">
</div>
<div id="chartContainer2" style="height: 200px; width: 70%;">
</div>
<div id="chartContainer3" style="height: 300px; width: 30%;">
</div>
</body>
</html>
I need to change position of "chartContainer3". Should I do something with div style ?
Related
function timeDataToPointChart($dataPoints,$title,$xlabel,$ylabel,$chartID) {
?>
<script src="https://canvasjs.com/assets/script/canvasjs.min.js"></script>
<script>
window.onload = function () {
var NameOfChart = "<?php echo $chartID; ?>"
window[NameOfChart] = new CanvasJS.Chart("chartContainer",
{
animationEnabled: true,
title:{
text: "<?php echo $title; ?>"
},
axisX:{
title: "<?php echo $xlabel; ?>",
valueFormatString: "MM/YYYY",
crosshair: {
enabled: true
}
},
axisY: {
title: "<?php echo $ylabel; ?>"
},
data: [
{
type: "line",
xValueType: "dateTime",
dataPoints:
<?php echo json_encode($dataPoints, JSON_NUMERIC_CHECK); ?>
}
]
});
window[NameOfChart].render();
function toggleDataSeries(e){
if (typeof(e.dataSeries.visible) === "undefined" || e.dataSeries.visible) {
e.dataSeries.visible = false;
}
else{
e.dataSeries.visible = true;
}
window[NameOfChart].render();
}
}
</script>
<div id="chartContainer" style="height: 370px; width: 650px;"></div>
<?php
}
?>
I use this PHP function to generate my canvas chart. This works well, but if I call the function twice on a page, only one chart is shown.
Console shows the following error, but I don't understand what's wrong.
CanvasJS namespace already exists. If you are loading both chart and
stockchart scripts, just load stockchart alone as it includes all
chart features.
Thank you for your help.
As described from canvasJs, i've implemented the code accordingly in my Laravel App like below
#foreach($records as $record)
<div id="chartContainer{{$record->employeeRequisitionId}}" style="height: 270px; width: 100%;"></div>
#endforeach
#push('after_scripts')
<script>
window.onload = function () {
#foreach($records as $record)
const chart{{$record->employeeRequisitionId}} = new CanvasJS.Chart ( "chartContainer{{$record->employeeRequisitionId}}", {
animationEnabled: true,
theme: "light2",
title: {
text: "Requisition According Fiscal Year"
},
axisY: {
suffix: "%",
scaleBreaks: {
autoCalculate: false
}
},
data: [{
type: "column",
yValueFormatString: "#,##0\"%\"",
indexLabel: "{y}",
indexLabelPlacement: "inside",
indexLabelFontColor: "white",
dataPoints: {!! formatRequisitionAccordingFiscalYearData($record) !!}
}]
} );
#endforeach
#foreach($records as $record)
chart{{$record->employeeRequisitionId}}.render ();
#endforeach
}
</script>
#endpush
I'm working with Highcharts and Highstock from a few weeks ago. Step by step, following the documentation and help online, I have builded some charts with interesting options. But now I have a question, and my skills with mysql and php are limited.
I get temperature values from a data base, every minute. I use a php file to connect to database, and then I build the chart. Now, I want to update the chart like in this example. But I can't find a right way. I was reading in Highcharts documentation, and Stackoverflow some answers, but I can't implement into my code.
I was working in 2 ways to implement the dynamic updates. The first one is:
<?php
function conectarBD(){
$server = "localhost";
$usuario = "user";
$pass = "password";
$BD = "databasename";
$conexion = mysqli_connect($server, $usuario, $pass, $BD);
if(!$conexion){
echo 'Ha sucedido un error inexperado en la conexion de la base de datos<br>';
}
return $conexion;
}
function desconectarBD($conexion){
$close = mysqli_close($conexion);
if(!$close){
echo 'Ha sucedido un error inexperado en la desconexion de la base de datos<br>';
}
return $close;
}
function getArraySQL($sql){
$conexion = conectarBD();
if(!$result = mysqli_query($conexion, $sql)) die();
$rawdata = array();
$i=0;
while($row = mysqli_fetch_array($result))
{
$rawdata[$i] = $row;
$i++;
}
desconectarBD($conexion);
return $rawdata;
}
$sql = "SELECT Probe1,Time from table2;";
$rawdata = getArraySQL($sql);
for($i=0;$i<count($rawdata);$i++){
$time = $rawdata[$i]["Time"];
$date = new DateTime($time);
$rawdata[$i]["Time"]=$date->getTimestamp()*1000;
}
?>
<HTML>
<BODY>
<meta charset="utf-8">
<script src="https://code.jquery.com/jquery.js"></script>
<script src="http://code.highcharts.com/stock/highstock.js"></script>
<script src="http://code.highcharts.com/modules/exporting.js"></script>
<div id="container">
</div>
<script type='text/javascript'>
$(function () {
$(document).ready(function() {
Highcharts.setOptions({
global: {
useUTC: false
}
});
var chart;
$('#container').highcharts({
chart: {
type: 'spline',
animation: Highcharts.svg, // don't animate in old IE
marginRight: 10,
events: {
load: function () {
var series = this.series[0];
setInterval(function () {
<?php
for($i = 0 ;$i<count($rawdata);$i++){
?>
series.addPoint([<?php echo $rawdata[$i]["Time"];?>,<?php echo $rawdata[$i]["Probe1"];?>], true, true);
<?php } ?>
}, 90000);
}
}
},
title: {
text: 'Tunnel temperature'
},
xAxis: {
type: 'datetime',
tickPixelInterval: 150
},
yAxis: {
title: {
text: 'ºC'
},
plotLines: [{
value: 0,
width: 1,
color: '#808080'
}]
},
tooltip: {
formatter: function() {
return '<b>'+ this.series.name +'</b><br/>'+
Highcharts.dateFormat('%d-%b %H:%M', this.x) +'<br/>'+
'<b>'+ Highcharts.numberFormat(this.y, 1) +'</b>';
}
},
legend: {
enabled: true
},
exporting: {
enabled: true
},
series: [{
name: 'Probe-1',
data: (function() {
var data = [];
<?php
for($i = 0 ;$i<count($rawdata);$i++){
?>
data.push([<?php echo $rawdata[$i]["Time"];?>,<?php echo $rawdata[$i]["Probe1"];?>]);
<?php } ?>
return data;
})()
}]
});
});
});
</script>
</html>
And this other way:
Connection to datatest2.php:
<?php
//convert the date values to Unix Timestamp
//Convert from 2017-02-28 19:30:01 to Tuesday, February 28 2017 19:30:01
$con = mysql_connect("localhost","username","password");
if (!$con) { die('Could not connect: ' . mysql_error()); } mysql_select_db("databasename", $con);
$result = mysql_query("SELECT * FROM table2");
while ($row = mysql_fetch_array($result)) {
$uts=strtotime($row['Time']); //convertir a Unix Timestamp
$date=date("l, F j Y H:i:s",$uts);
//echo $valor3 . “\t” . $row[$valor2]. “\n”;
echo $date . "\t" . $row['Probe1'] . "\n";
}
mysql_close($con); ?>
And the php file for the chart:
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN"
"http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<html xmlns="http://www.w3.org/1999/xhtml">
<head>
<meta http-equiv="Content-Type" content="text/html; charset=utf-8"/>
<title>Highstock & multiple</title>
<script src="https://code.jquery.com/jquery.js"></script>
<script src="http://code.highcharts.com/stock/highstock.js"></script>
<script src="http://code.highcharts.com/modules/exporting.js"></script>
<script type="text/javascript">
var chart;
$(document).ready(function() {
var options = {
chart: {
renderTo: 'container',
defaultSeriesType: 'line',
marginRight: 130,
marginBottom: 25
},
title: {
text: 'Temperature Tunnel',
x: -20 //center
},
subtitle: {
text: '',
x: -20
},
rangeSelector: {
buttons: [
{
type: 'all',
text: 'all'
}, {
type: 'week',
count: 1,
text: '1w'
}, {
type: 'day',
count: 1,
text: '1d'
}, {
type: 'hour',
count: 18,
text: '18h'
}, {
type: 'hour',
count: 12,
text: '12h'
}, {
type: 'hour',
count: 6,
text: '6h'
}]
},
xAxis: {
type: 'datetime',
tickWidth: 0,
gridLineWidth: 1,
labels: {
align: 'center',
x: -3,
y: 20,
formatter: function() {
return Highcharts.dateFormat('%d-%b %H:%M', this.value);
}
}
},
yAxis: {
title: {
text: 'Celsius degrees'
},
plotLines: [{
value: 0,
width: 1,
color: '#808080'
}]
},
tooltip: {
formatter: function() {
return Highcharts.dateFormat('%d-%b %H:%M', this.x) +': <b>'+ this.y + '</b>';
}
},
legend: {
layout: 'vertical',
align: 'right',
verticalAlign: 'top',
x: -10,
y: 100,
borderWidth: 0
},
series: [{
name: 'Probe1'
}]
}
jQuery.get('datatest2.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 = Highcharts.stockChart (options);
setInterval(function() { tsv; }, 30000);
pollChart.series[0].setData(data);
});
});
</script>
</head>
<body>
<div id="container" style="width: 100%; height: 400px; margin: 0 auto"></div>
</body>
</html>
Can you help me to find and fix the mistake?
Thanks!
Alex.
Using a combination of your first example and the JSFiddle that you posted, I would try something like this:
chart: {
events: {
load: function () {
var series = this.series[0];
setInterval(function () {
<?php
for($i = 0 ;$i<count($rawdata);$i++){
?>
series.addPoint([<?php echo $rawdata[$i]["Time"];?>,<?php echo $rawdata[$i]["Probe1"];?>], true, true);
<?php } ?>
}, 1000);
}
}
}
Note that I have no idea whether your PHP code there is actually retrieving the data that you wanted, I have simply copied it from your example and made the assumption that that part of the code was ok.
The key here is the chart.events.load property, this takes a function that fires once the chart has finished loading. By calling setInterval here, your function will fire continuously after the chart finishes loading the first time.
By calling series.addPoint, your chart will redraw every time a new point is added, which I believe is what you want.
More information is available here about the load property.
I'll start by saying I'm completely new to Javascript. I have worked with Java and PHP more than anything.
I copied much of the code from the example and have tried tinkering with it to get it to run but have not had any luck. The original example in JSFiddle is here: http://jsfiddle.net/gh/get/jquery/1.9.1/highslide-software/highcharts.com/tree/master/samples/stock/demo/compare/
Any input is appreciated.
<?php
echo <<< 'EOT'
<html>
<head>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.3/jquery.min.js"></script>
<script src="https://code.highcharts.com/highstock.js"></script>
<script src="https://code.highcharts.com/exporting.js"></script>
</head>
<body>
EOT;
require_once('hvst.php'); // Generates the JSON file using json_encode();
echo <<< 'EOT'
function createChart() {
var fields = ['humidity', 'curtemp'];
Highcharts.stockChart('container', {
rangeSelector: {
selected: 4
},
yAxis: {
labels: {
formatter: function () {
return (this.value > 0 ? ' + ' : '') + this.value + '%';
}
},
plotLines: [{
value: 0,
width: 2,
color: 'silver'
}]
},
tooltip: {
pointFormat: '<span style="color:{series.color}">{series.name}</span>: <b>{point.y}</b> ({point.change}%)<br/>',
valueDecimals: 2,
split: true
},
series: seriesOptions
});
$.each(fields, function (timestamp, curtemp) {
$.getJSON('chart1.json', function (humidity) {
seriesOptions[timestamp] = {
name: curtemp,
data: humidity
},
seriesCounter += 1;
if (seriesCounter === fields.length) {
createChart();
}
});
});
};
</script>
<div id="container" style="height: 400px; min-width: 400px"></div>
</body>
</html>
EOT;
?>
Edit: hvst.php
<?php
ini_set('display_errors', 'On');
error_reporting(E_ALL);
//Set JSON header
header("Content-type: text/json");
include 'dbread.php';
//include 'correlate.php';
// Get last 5 days
$days=5;
$resultSet1 = readDB('SELECT timestamp,humidity,curtemp FROM public."WeatherData" WHERE timestamp > NOW()-INTERVAL \''.$days.' days\';');
$fp = fopen('chart1.json', 'w');
fwrite($fp, json_encode($resultSet1,JSON_PRETTY_PRINT|JSON_NUMERIC_CHECK));
fclose($fp);
?>
Here's a sample of the first few lines from the JSON output:
[
{
"timestamp": "2016-11-05 10:10:02.427425",
"humidity": 48,
"curtemp": 46
},
{
"timestamp": "2016-11-05 10:10:03.83401",
"humidity": 48,
"curtemp": 46
},
http://www.highcharts.com/stock/demo/basic-line
It's my code for json.php
<?php
header("content-type: application/json");
define('HOST', 'localhost');
define('USER', 'root');
define('PASSWORD', 'password');
define('NAME_BD', 'bd');
$connect = mysql_connect(HOST, USER, PASSWORD)
or die("die"
.mysql_error( ));
mysql_select_db(NAME_BD, $connect)
or die ("wtf"
.mysql_error( ));
$result = mysql_query("SELECT UNIX_TIMESTAMP(`Time`) * 1000 as datetime, `Current A` as A FROM `Table`")
or die ("die".mysql_error( ));
while ($row = mysql_fetch_array($result)) {
$data[] = $row['datetime'];
$datab[] = $row['A'];
}
echo '?(' . "\n" . '['. "\n";
$count = count($data);
for ($i=0; $i<$count; $i++)
{
echo '['. str_replace('"', "", json_encode($data[$i], JSON_HEX_APOS)) . ',' . str_replace('"', "", json_encode($datab[$i], JSON_HEX_APOS)) .']' . ',' . "\n";
}
echo ']);';
?>
I refresh my page and highstock don't draw. Please help me.
It's my stock.html
<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=utf-8">
<title>Highstock 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 () {
$.getJSON('http://192.168.1.175/json.php', function (data) {
// Create the chart
$('#container').highcharts('StockChart', {
rangeSelector : {
selected : 1
},
title : {
text : 'AAPL Stock Price'
},
series : [{
name : 'AAPL',
data : data
}]
});
});
});
</script>
</head>
<body>
<script src="https://code.highcharts.com/stock/highstock.js"></script>
<script src="https://code.highcharts.com/stock/modules/exporting.js"></script>
<div id="container" style="height: 400px; min-width: 310px"></div>
</body>
</html>
Stock.html call json.php but when a refresh stock.html i don't see draw.
Please help me
Please try below code
in Ajax code
function drawGrap()
{
$.ajax({
type: "POST",
url: 'graph.php',
data: '',
success: function(json) {
drawSalesChart(json);
}
});
}
in graph.php
<?php
if(!empty($data))
{
foreach ($data as $d)
{
$time = strtotime($d['date']);
$date = date("Y-m-d",$time);
$graphData[$date][0] = 'Date.UTC('. date("Y",$time) .','. (date("m",$time)-1) .','. date("d",$time) .')';
$graphData[$date][1] = $d['count'];
}
}
sort($graphData);
//Convert result array to json format
$jsonGraphData = json_encode($graphData);
$jsonGraphData = str_replace('"', '', $jsonGraphData);
echo $jsonGraphData;
?>
After response
function drawSalesChart( data)
{
$('#GraphID').css("height", "400px");
$('#GraphID').highcharts('StockChart', {
title: {
text: 'Daily Sales'
},
colors: ['#920000'],
navigator: {
enabled: false
},
rangeSelector: {
selected: 5,
buttons: [
{
type: 'week',
count: 1,
text: '1 Week'
},
{
type: 'month',
count: 1,
text: '1 Month'
},
{
type: 'month',
count: 3,
text: '3 Months'
},
{
type: 'month',
count: 6,
text: '6 Months'
},
{
type: 'year',
count: 1,
text: '1 Year'
},
{
type: 'all',
text: 'All'
}
],
buttonTheme: {
width: 100,
padding: 5,
style: {
color: '#000000'
}
}
},
series: [{
name: 'Kr',
type: 'area',
data: eval(data),
tooltip: {
valueDecimals: 2
},
fillColor: {
linearGradient: {
x1: 0,
y1: 0,
x2: 0,
y2: 1
},
stops: [
[0, '#FF4848'],
[1, '#ffe1e1'],
]
}
}]
});
}
I tried to use a column chart example given in Highcharts tutorial. This code should work fine. Someone please help me to figure out the problem. I attach the code below. I don't know why it only shows blank page.
<!DOCTYPE HTML>
<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=utf-8">
<title>Column chart with data from MySQL using Highcharts</title>
<script src="http://ajax.googleapis.com/ajax/libs/jquery/1.7.1/jquery.min.js" type="text/javascript"></script>
<script src="http://code.highcharts.com/highcharts.js"></script>
<script src="http://code.highcharts.com/modules/exporting.js"></script>
<script type="text/javascript">
$(document).ready(function() {
var options = {
chart: {
renderTo: 'container',
type: 'column',
marginRight: 130,
marginBottom: 25
},
title: {
text: 'Project Requests',
x: -20 //center
},
subtitle: {
text: '',
x: -20
},
xAxis: {
categories: []
},
yAxis: {
title: {
text: 'Requests'
},
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("data.php", function(json) {
options.xAxis.categories = json[0]['data'];
options.series[0] = json[1];
options.series[1] = json[2];
options.series[2] = json[3];
chart = new Highcharts.Chart(options);
});
});
</script>
</head>
<body>
<div id="container" style="min-width: 400px; height: 400px; margin: 0 auto"></div>
</body>
</html>
Here is data.php. I think there is nothing wrong about this php.
<?php
$con = mysql_connect("localhost","*****","*******");
if (!$con) {
die('Could not connect: ' . mysql_error());
}
mysql_select_db("test_youtube", $con);
$query = mysql_query("SELECT month, wordpress, codeigniter, highcharts FROM project_requests");
$category = array();
$category['name'] = 'Month';
$series1 = array();
$series1['name'] = 'Wordpress';
$series2 = array();
$series2['name'] = 'CodeIgniter';
$series3 = array();
$series3['name'] = 'Highcharts';
while($r = mysql_fetch_array($query)) {
$category['data'][] = $r['month'];
$series1['data'][] = $r['wordpress'];
$series2['data'][] = $r['codeigniter'];
$series3['data'][] = $r['highcharts'];
}
$result = array();
array_push($result,$category);
array_push($result,$series1);
array_push($result,$series2);
array_push($result,$series3);
print json_encode($result, JSON_NUMERIC_CHECK);
mysql_close($con);
?>