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
Related
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 ?
Im trying to display 2 different pie chart which takes value from php database. but problem is when I do the second pie chart, the first pie chart would not show but will show the second pie chart, means it works 1 at the time.
Where is the error?
1st code for pie chart
?php
$dataPoints = array();
//Best practice is to create a separate file for handling connection to database
try{
// Creating a new connection.
// Replace your-hostname, your-db, your-username, your-password according to your database
$link = new \PDO( 'mysql:host=localhost;dbname=OISC;charset=utf8mb4', //'mysql:host=localhost;dbname=canvasjs_db;charset=utf8mb4',
'root', //'root',
'', //'',
array(
\PDO::ATTR_ERRMODE => PDO::ERRMODE_EXCEPTION,
\PDO::ATTR_PERSISTENT => false
)
);
$handle = $link->prepare("SELECT Gender, COUNT(Gender) AS totalUser FROM register GROUP By Gender");
$handle->execute();
$result = $handle->fetchAll(\PDO::FETCH_OBJ);
foreach($result as $row){
array_push($dataPoints, array("x"=> $row->Gender, "y"=> $row->totalUser));
}
$link = null;
}
catch(\PDOException $ex){
print($ex->getMessage());
}
?>
1 JavaScript for pie chart
<script>
window.onload = function () {
var chart = new CanvasJS.Chart("chartContainer", {
animationEnabled: true,
exportEnabled: true,
theme: "light1", // "light1", "light2", "dark1", "dark2"
title:{
text: "Gender Pie Chart"
},
data: [{
type: "pie", //change type to bar, line, area, pie, etc
dataPoints: <?php echo json_encode($dataPoints, JSON_NUMERIC_CHECK); ?>
}]
});
chart.render();
}
</script>
HTML
<div id="chartContainer" style="height: 370px; width: 100%;"></div>
<script src="https://canvasjs.com/assets/script/canvasjs.min.js"></script>
2nd php code for pie chart
<?php
$dataPoints = array();
//Best practice is to create a separate file for handling connection to database
try{
// Creating a new connection.
// Replace your-hostname, your-db, your-username, your-password according to your database
$link = new \PDO( 'mysql:host=localhost;dbname=OISC;charset=utf8mb4', //'mysql:host=localhost;dbname=canvasjs_db;charset=utf8mb4',
'root', //'root',
'', //'',
array(
\PDO::ATTR_ERRMODE => PDO::ERRMODE_EXCEPTION,
\PDO::ATTR_PERSISTENT => false
)
);
$handle = $link->prepare("SELECT BasedAt, COUNT(BasedAT) as TotalImmigrant FROM register GROUP By BasedAt");
$handle->execute();
$result1 = $handle->fetchAll(\PDO::FETCH_OBJ);
foreach($result1 as $row){
array_push($dataPoints, array("x"=> $row->BasedAt, "y"=> $row->TotalImmigrant));
}
$link = null;
}
catch(\PDOException $ex){
print($ex->getMessage());
}
?>
2nd JS for pie chart
<script>
window.onload = function () {
var chart = new CanvasJS.Chart("chartContainer1", {
animationEnabled: true,
exportEnabled: true,
theme: "light1", // "light1", "light2", "dark1", "dark2"
title:{
text: "Location Pie Chart"
},
data: [{
type: "pie", //change type to bar, line, area, pie, etc
dataPoints: <?php echo json_encode($dataPoints, JSON_NUMERIC_CHECK); ?>
}]
});
chart.render();
}
</script>
HTML
<div id="chartContainer1" style="height: 370px; width: 100%;"></div> <!--Location Chart-->
<script src="https://canvasjs.com/assets/script/canvasjs.min.js"></script>
Keep first chart as it is and try use this for second chart
window.onload = function () {
var chart_sec = new CanvasJS.Chart("chartContainer1", {
animationEnabled: true,
exportEnabled: true,
theme: "light1", // "light1", "light2", "dark1", "dark2"
title:{
text: "Location Pie Chart"
},
data: [{
type: "pie", //change type to bar, line, area, pie, etc
dataPoints: <?php echo json_encode($dataPoints, JSON_NUMERIC_CHECK); ?>
}]
});
chart_sec.render();
}
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.
Good day guys. So I've got some kind of problem of my highcharts pie, where I've got only two items/legends where 1995 and 1996. I've got a data in 1995 where there are 2 and 1996 is 0.
It displays the pie chart, but the problem is that it's wrong in percentage. As you can see in the image below it show both the 1995 and 1996.
The 1995 should be in 100% and not in 10% because i've got only two items, the 1996 is correct however because i've got no data.
Here is my php code
<?php
require '/db/database_configuration.php';
$_1995 = mysqli_query($conn, "SELECT COUNT(*) AS Total FROM `tblalumni` WHERE yeargrad LIKE '1995' and alum_status LIKE 2");
$_1996 = mysqli_query($conn, "SELECT COUNT(*) AS Total FROM `tblalumni` WHERE yeargrad LIKE '1996' and alum_status LIKE 2");
$_1995 = mysqli_fetch_array($_1995);
$_1996 = mysqli_fetch_array($_1996);
// displays zero if none
if (empty($_1995['Total'])) { $_1995 = '0'; } else { $_1995 = $_1995['Total'];}
if (empty($_1996['Total'])) { $_1996 = '0'; } else { $_1996 = $_1996['Total'];}
$ans_1995 = '1995';
$ans_1996 = '1996';
$Data95 = $_1995;
$Data96 = $_1996;
?>
Here is my javascript
<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: [{
name: 'Brands',
colorByPoint: true,
data: [{
name: <?php echo json_encode($ans_1995); ?>,
y: [<?php echo $Data95; ?>]
}, {
name: <?php echo json_encode($ans_1996); ?>,
y: [<?php echo $Data96; ?>]
}]
}]
});
});
</script>
Can anyone help me?
change
series: [{
name: 'Brands',
colorByPoint: true,
data: [{
name: <?php echo json_encode($ans_1995); ?>,
y: [<?php echo $Data95; ?>]
}, {
name: <?php echo json_encode($ans_1996); ?>,
y: [<?php echo $Data96; ?>]
}]
}]
to
series: [{
name: 'Brands',
colorByPoint: true,
data: [{
name: <?php echo json_encode($ans_1995); ?>,
y: <?php echo $Data95; ?>
}, {
name: <?php echo json_encode($ans_1996); ?>,
y: <?php echo $Data96; ?>
}]
}]
Just remove brackets.. HAHAHAH
i wannna make a line graph using highchart JS with data from my SQL, but unfortunately the graph just shown like this :
the graph just shown a Xline and Yline but not a data
and this is my sql code
$sqlX=mysql_query("SELECT DISTINCT DAY(tgl_daftar) as value FROM pasien WHERE MONTH(tgl_daftar) = '06' AND YEAR(tgl_daftar)='2016'")or die(mysql_error()) ;
and this my php and JS code :
<script src="js/jquery.min.js"></script>
<script src="js/highcharts.js"></script>
<script src="js/exporting.js"></script>
<script type="text/javascript">
var chart1 ;
$(document).ready(function() {
chart1 = new Highcharts.Chart({
chart: {
renderTo: 'grafik',
type: 'column'
},
title: {
text: 'Data Pendaftaran Pasien Baru Per Bulan',
x: -20 //center
},
subtitle: {
text: '',
x: -20
},
xAxis: {
categories: [<?php while($r=mysql_fetch_array($sqlX)){ echo "'".$r['value']."',";} ?>]
},
yAxis: {
title: {
text: 'Jumlah'
},
plotLines: [{
value: 0,
width: 1,
color: '#808080'
}]
},
tooltip: {
valueSuffix: ''
},
legend: {
layout: 'vertical',
align: 'right',
verticalAlign: 'middle',
borderWidth: 0
},
series: [{
name: <?php echo "'".$namabulan."'" ; ?>
<?php
while($date=mysql_fetch_array($sqlX)){
$date=$date['value'];
$sql_jumlah = "SELECT tgl_daftar, COUNT(*) as jumlah_pasien
FROM pasien
WHERE
DAY(tgl_daftar) = '$date'
AND MONTH(tgl_daftar)='$bulan' AND YEAR(tgl_daftar) = '$namatahun'";
$query_jumlah = mysql_query( $sql_jumlah ) or die(mysql_error());
while( $data = mysql_fetch_array( $query_jumlah ) ){
$jumlah = $data['jumlah_pasien']; }
?>
data: [<?php echo $jumlah ; ?>]
<?php
} ?>
}]
});
});
</script>
thanks, Any help would be really appreciated