Php Array to line chart in ChartJs - javascript

$days = ["Monday","Tuesday","Wednesday"];
$rates = [40,60,80];
$profit = [];
foreach($days as $day => $value){
foreach($rates as $rate){
$netprofit = $rate* 20;
$profit[$value] = [$rate=> $netprofit];
}
}
$usersChart = new UserChart;
$usersChart->labels($days);
foreach($profit as $key => $value){
$data = array();
foreach ($value as $values){
$data[] = $values;
}
$usersChart->dataset($key, 'line', collect($data));
}
I want to show this array into Chartjs Line Graph. I want the x axis to be the 40,60,80. Y axis to be 800, 1200, 1600. The Dataset or Lines should be Monday, Tuesday and Wednesday.
Right now i get Monday, Tuesday and Wednesday as x axis and Line. 600,800 etc are on y axis.
Array
(
[Monday] => Array
(
[40] => 800
[60] => 1200
[80] => 1600
)
[Tuesday] => Array
(
[40] => 800
[60] => 1200
[80] => 1600
)
[Wednesday] => Array
(
[40] => 800
[60] => 1200
[80] => 1600
)
)

keep your array as it is and convert it to JSON object and then echo it inside Javascript, javascript have to be inside php file to run, not in external javascript file.
notice that there is PHP code in this example and i have put <?php echo $json; ?> inside the javascript code.
<html>
<head>
<style>body{width: 800px;}</style>
<script src="https://cdn.jsdelivr.net/npm/chart.js#2.8.0"></script>
</head>
<body>
<div>
<canvas id="myChart" width="700px" height="300px"></canvas>
</div>
<?php
$array = array(600, 800, 1200, 1800);
$json = json_encode($array);
?>
<script>
var ctx = document.getElementById('myChart').getContext('2d');
var chart = new Chart(ctx, {
// The type of chart we want to create
type: 'line',
// The data for our dataset
data: {
labels: ["20", "40", "60", "80"],
datasets: [
{
label: 'Monday',
borderColor: "#FF9F40",
data: <?php echo $json; ?>,
},
{
label: 'Tuesday',
borderColor: "#FF6384",
data: [600, 800, 1200, 1800]
},
{
label: 'Wednesday',
borderColor: "#219151",
data: [600, 800, 1200, 1800]
}
]
},
// Configuration options go here
options: {}
});
</script>
</body>
</html>

Related

How to make a correct json to provide data to Apexcharts pie?

I'm new in Apexcharts, and I try to make a pie chart with data, getting from mysql database. This is the php-file named "get_types_chart.php"
$year = date('Y');
$month = date('m');
$graf = PDO()->prepare("SELECT COUNT(tickets.id) AS cid, types.ticket_type AS type_name FROM tickets LEFT JOIN types ON tickets.type=types.id WHERE tickets.arch=0 AND tickets.status NOT IN (2, 4) AND MONTH(tickets.date_create)=:month AND YEAR(tickets.date_create)=:year GROUP BY types.ticket_type");
$graf->execute([':year' => $year,
':month' => $month]);
$arrData = array();
while($row = $graf->fetch(PDO::FETCH_LAZY)) {
array_push($arrData, array(
"labels" => $row->type_name,
"series" => $row->cid
)
);
}
$jsonEncodedData = json_encode($arrData);
header('Content-Type: application/json');
echo $jsonEncodedData;
And this is the js-code:
var url3 = 'charts/get_types_chart.php';
var options3 = {
series: [],
chart: {
width: 380,
type: 'pie',
},
title: {
text: '<?php echo lang('MON_STAT_year'); ?>',
floating: true,
align: 'center'
},
labels: [],
responsive: [{
breakpoint: 480,
options: {
chart: {
width: 200
},
legend: {
position: 'bottom'
}
}
}]
};
var chart3 = new ApexCharts(document.querySelector("#chart3"), options3);
chart3.render();
$.getJSON(url3, function(response) {
chart3.updateSeries([{
name: '<?php echo lang('DASH_STAT_month_all'); ?>',
data: response
}])
});
Finally I get empty pie. Please hel me to make a correct json.

Expression expected Error when using php variables in ChartJS functions

I am trying to input my Controller variable in ChartJS Javascript file to Dynamically create charts in ChartJS
Expression Expected at "<?"
Controller.php
public function index(Request $request)
{
#$result= DB::select("SELECT * FROM table WHERE user_id =?", [$user_id]);
$result_arr = json_decode(json_encode($result), true);
$label_array = array();
foreach($result_arr as $d)
{
$label_array[]=$d['label_element'];
}
$data_array = array();
foreach($result_arr as $d)
{
$data_array[]=$d['data_element'];
}
return view('home', ['labels'=>$label_array, 'data'=>$data_array]);
}
chart-pie-demo.js:
// Pie Chart Example
var ctx = document.getElementById("myPieChart");
var myPieChart = new Chart(ctx, {
type: 'doughnut',
data: {
labels: <?php echo json_encode($labels); ?>, // Error Line
datasets: [{
data: <?php echo json_encode($data); ?>, // Error Line
backgroundColor: ['#4e73df', '#1cc88a', '#36b9cc'],
hoverBackgroundColor: ['#2e59d9', '#17a673', '#2c9faf'],
hoverBorderColor: "rgba(234, 236, 244, 1)",
}],
},

Dynamically create chart with Chart.js and PHP

We're currently using customerthermometers to survey our customers after completed support-tickets. Unfortunately customerthermometers widget's look disgusting. So I'm currently trying to create a chart with Chart.js and dynamically getting data from customerthermometers' API with PHP.
All parts in the PHP-array ($dataPoints) is taken into account in the chart, except the "data", and I really don't know how to proceed further.
<?php
$gold = file_get_contents( 'https://app.customerthermometer.com/api.php?apiKey=<api_key>&getMethod=getNumResponsesValue&temperatureID=1' );
$green = file_get_contents( 'https://app.customerthermometer.com/api.php?apiKey=<api_key>&getMethod=getNumResponsesValue&temperatureID=2' );
$yellow = file_get_contents( 'https://app.customerthermometer.com/api.php?apiKey=<api_key>&getMethod=getNumResponsesValue&temperatureID=3' );
$red = file_get_contents( 'https://app.customerthermometer.com/api.php?apiKey=<api_key>&getMethod=getNumResponsesValue&temperatureID=4' );
$dataPoints = array(
array( "label" => "Gold Star" , "data" => $gold , "backgroundColor" => "rgba(255,215,0,1)"),
array( "label" => "Green Light" , "data" => $green , "backgroundColor" => "rgba(0,128,0,1)"),
array( "label" => "Yellow Light" , "data" => $yellow , "backgroundColor" => "rgba(255,255,0,1)"),
array( "label" => "Red Light" , "data" => $red , "backgroundColor" => "rgba(255,0,0,1)" )
);
?>
<html>
<head>
<meta charset="utf-8">
<title>Chart Test</title>
</head>
<body>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.7.1/jquery.min.js"></script>
<script src="../assets/chart28/dist/Chart.js"></script>
<canvas id="myChart" width="100" height="20"></canvas>
<script>
var ctx = document.getElementById('myChart');
var myChart = new Chart(ctx, {
type: 'bar',
data: {
labels: ['Gold Star', 'Green Light', 'Yellow Light', 'Red Light'],
datasets: <?php echo json_encode($dataPoints, JSON_NUMERIC_CHECK); ?>
},
options: {
scales: {
yAxes: [{
ticks: {
beginAtZero: true
}
}]
}
}
});
</script>
<?php echo json_encode($dataPoints, JSON_NUMERIC_CHECK); ?>
</body>
</html>
Edit:
$dataPoints
[{"label":"Gold Star","data":4,"backgroundColor":"rgba(255,215,0,1)"},{"label":"Green Light","data":2,"backgroundColor":"rgba(0,128,0,1)"},{"label":"Yellow Light","data":0,"backgroundColor":"rgba(255,255,0,1)"},{"label":"Red Light","data":0,"backgroundColor":"rgba(255,0,0,1)"}]
I've also tried to statically set the following values within datasets, and this works and gives me the desired result:
datasets: [{
data: [ 4 , 2 , 0 , 0 ],
backgroundColor: [
"rgba(255,215,0,1)",
"rgba(0,128,0,1)",
"rgba(255,255,0,1)",
"rgba(255,0,0,1)"
]
}]
Working code (Thanks to #Camille):
<?php
$gold = file_get_contents( 'https://app.customerthermometer.com/api.php?apiKey=<api_key>&getMethod=getNumResponsesValue&temperatureID=1' );
$green = file_get_contents( 'https://app.customerthermometer.com/api.php?apiKey=<api_key>&getMethod=getNumResponsesValue&temperatureID=2' );
$yellow = file_get_contents( 'https://app.customerthermometer.com/api.php?apiKey=<api_key>&getMethod=getNumResponsesValue&temperatureID=3' );
$red = file_get_contents( 'https://app.customerthermometer.com/api.php?apiKey=<api_key>&getMethod=getNumResponsesValue&temperatureID=4' );
$dataPoints = array(
array( "data" => array($gold) , "label" => "Gold Star" , "backgroundColor" => "rgba(255,215,0,1)"),
array( "data" => array($green) , "label" => "Green Light" , "backgroundColor" => "rgba(0,128,0,1)"),
array( "data" => array($yellow) , "label" => "Yellow Light" , "backgroundColor" => "rgba(255,255,0,1)"),
array( "data" => array($red) , "label" => "Red Light" , "backgroundColor" => "rgba(255,0,0,1)" )
);
?>
<html>
<head>
<meta charset="utf-8">
<title>Untitled Document</title>
</head>
<body>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.7.1/jquery.min.js"></script>
<script src="../assets/chart28/dist/Chart.js"></script>
<canvas id="myChart" width="100" height="20"></canvas>
<script>
var ctx = document.getElementById('myChart');
var myChart = new Chart(ctx, {
type: 'bar',
data: {
labels: ['Customer Thermometer'],
datasets: <?php echo json_encode($dataPoints, JSON_NUMERIC_CHECK); ?>
},
options: {
scales: {
yAxes: [{
ticks: {
beginAtZero: true,
}
}]
}
}
});
</script>
</body>
</html>
Data attribute of $dataPoints should be an array. You have to convert it if you get a single value
...
$dataPoints = array(
array( "label" => "Gold Star" , "data" => array($gold) , "backgroundColor" => "rgba(255,215,0,1)"),
array( "label" => "Green Light" , "data" => array($green) , "backgroundColor" => "rgba(0,128,0,1)"),
array( "label" => "Yellow Light" , "data" => array($yellow) , "backgroundColor" => "rgba(255,255,0,1)"),
array( "label" => "Red Light" , "data" => array($red) , "backgroundColor" => "rgba(255,0,0,1)" )
);
...

Wrong date in highstock Chart

How can I incorporate the correct date into my high stock chart? I keep getting the months January to February (correct range should be from July to August) in my slider, which is incorrect. In my PHP I convert the date/time from my database into a JavaScript timestamp, but still doesn't work. Any help would be great, thanks!
Output Array: data.txt
Current high stocks Chart:
PHP & JS and HTML:
<?php
$stmt = mysqli_prepare($con, "SELECT date, IFNULL(AT,'null') FROM test");
$result = array('date' => array(), 'AT' => array());
if ($stmt) {
mysqli_stmt_execute($stmt);
mysqli_stmt_bind_result($stmt, $date, $at);
while (mysqli_stmt_fetch($stmt)) {
$result['date'][] = $date;
$result['AT'][] = (int)$at;
$stamp = strtotime($date); // get unix timestamp
$time = $stamp*1000;
}
mysqli_stmt_close($stmt);
}
?>
<!DOCTYPE html>
<html >
<!--<![endif]-->
<head>
<meta charset="utf-8">
<meta http-equiv="X-UA-Compatible" content="IE=edge,chrome=1">
<script type="text/javascript" src="http://code.jquery.com/jquery-1.9.1.min.js"></script>
<script src="https://code.highcharts.com/stock/highstock.js"></script>
<script src="https://code.highcharts.com/highcharts-more.js"></script>
<script src="https://code.highcharts.com/modules/data.js"></script>
<script>
$(function(data) {
$('#chart2').highcharts('StockChart', { //Stock chart - might need zones to match gauges
rangeSelector : {
buttons : [{
type : 'hour',
count : 3,
text : '3h'
}, {
type : 'day',
count : 2,
text : '2D'
}, {
type : 'week',
count : 1,
text : '1W'
}, {
type : 'month',
count : 1,
text : '1M'
}, {
type : 'all',
count : 1,
text : 'All'
}],
selected : 2,
},
title: {
text: 'Power'
},
yAxis: [{
title: {
text: 'Bat V'
},
height: 400,
lineWidth: 2,
oposite: true
}, {
title: { // yAxis 1 ie secondary y-axis
text: 'Solar V'
},
//top: 200,
height: 400,
offset: 25,
lineWidth: 2,
oposite: false
}],
xAxis:{
type: <?php echo json_encode($time) ?>,
},
series: [{
pointInterval: 24 * 3600 * 1000,
type: 'line',
data: <?php echo json_encode($result['AT']) ?>
},],
}); //end of stockchart graphic
// end of get function
}); // end of graphing function
</script>
</head>
<body>
<?php echo $time; ?>
<br><br /><br /><br />
<div id="chart2" style="width:100%; height:600px;"></div>
</body>
</html>
Based on your Output Array: data.txt which is [["2017-07-25 16:44",12],["2017-07-25 17:00",12],...] it should be [[1500981240000,12],[1500982200000,12],...] so fix is $result['date'][] = strtotime($date)*1000 get unix timestamp in milliseconds
<?php
$stmt = mysqli_prepare($con, "SELECT date, IFNULL(AT,'null') FROM test");
$result = array('date' => array(), 'AT' => array());
if ($stmt) {
mysqli_stmt_execute($stmt);
mysqli_stmt_bind_result($stmt, $date, $at);
while (mysqli_stmt_fetch($stmt)) {
$result['date'][] = strtotime($date)*1000; // get unix timestamp in milliseconds
$result['AT'][] = (int)$at;
$stamp = strtotime($date); // get unix timestamp
$time = $stamp*1000;
}
mysqli_stmt_close($stmt);
}
?>

Two google bar charts not working in one page

I am not able to show two bar charts in one page. I have tried both ways, implementing these in two different <script> sections in and in one <script> section also. If one is shown if I make changes to <div> id, another is not shown and vice versa but both of them not shows at one time. I have also tried with visualization version change. When I see page source, there I see all the data for both graphs, but only graph is not created. What might be the problem. I have tried a lot, but not able to debug, in last I am here. Below is my code.
<script type="text/javascript">
// Load the Visualization API and the piechart package.
google.load('visualization', '1.0', {'packages':['bar']});
// Set a callback to run when the Google Visualization API is loaded.
google.setOnLoadCallback(drawChart);
// Callback that creates and populates a data table,
// instantiates the pie chart, passes in the data and
// draws it.
function drawChart() {
// Create the data table.
var data1 = google.visualization.arrayToDataTable([
['Metric Tonnes', 'HSFO', 'LSFO', 'MGO'],
<?php
foreach ($log_book_discrepancy as $log_book)
{
?>
["<?php echo trim($log_book->type_of_vessel); ?>", <?php echo trim($log_book->fuel_hsfo); ?>, <?php echo trim($log_book->fuel_lsfo); ?>, <?php echo trim($log_book->fuel_mgo); ?> ],
<?php
}
?>
]);
// Create the data table.
var data2 = google.visualization.arrayToDataTable([
['Metric Tonnes', 'HSFO', 'LSFO', 'MGO'],
<?php
foreach ($bunker_found as $bunker)
{
?>
["<?php echo trim($bunker->type_of_vessel); ?>", <?php echo trim($bunker->fuel_hsfo); ?>, <?php echo trim($bunker->fuel_lsfo); ?>, <?php echo trim($bunker->fuel_mgo); ?> ],
<?php
}
?>
]);
// Set chart options
var options1 = {
chart: {
title: 'Log Book Discrepancy',
subtitle: 'HSFO, LSFO, and MGO',
}
};
// Set chart options
var options2 = {
chart: {
title: 'Bunkers Found',
subtitle: 'HSFO, LSFO, and MGO',
}
};
// Instantiate and draw our chart, passing in some options.
var chart1 = new
google.charts.Bar(document.getElementById('log_book_discrepancy'));
chart1.draw(data1, options1);
var chart2 = new
google.charts.Bar(document.getElementById('bunkers_found'));
chart2.draw(data2, options2);
}
</script>
<div id="log_book_discrepancy" style="width:100%; height:340px;"></div>
<div id="bunkers_found" style="width:100%; height:340px;"></div>
And my both arrays become like:
$log_book_discrepancy is like:
Array
(
[0] => stdClass Object
(
[type_of_vessel] => BULK CARRIER
[fuel_hsfo] => 30
[fuel_lsfo] => 40
[fuel_mgo] => 40
)
[1] => stdClass Object
(
[type_of_vessel] => OIL TANKER
[fuel_hsfo] => 60
[fuel_lsfo] => 40
[fuel_mgo] => 45
)
)
And $bunker_found array is like:
Array
(
[0] => stdClass Object
(
[type_of_vessel] => BULK CARRIER
[fuel_hsfo] => 10
[fuel_lsfo] => 40
[fuel_mgo] => 40
)
[1] => stdClass Object
(
[type_of_vessel] => CHEMICAL TANKER
[fuel_hsfo] => 50
[fuel_lsfo] => 40
[fuel_mgo] => 55
)
)
This is solution without PHP with the given data, first chart with option: "isStacked: true":
google.load('visualization', '1', {packages: ['corechart', 'bar']});
google.setOnLoadCallback(drawChart);
function drawChart() {
var data1 = google.visualization.arrayToDataTable([
['Metric Tonnes', 'HSFO', 'LSFO', 'MGO'],
['BULK CARRIER', 30, 40, 40],
['OIL TANKER', 60, 40, 45]
]);
var data2 = google.visualization.arrayToDataTable([
['Metric Tonnes', 'HSFO', 'LSFO', 'MGO'],
['BULK CARRIER', 10, 40, 40],
['CHEMICAL TANKER', 50, 40, 55]
]);
var options1 = {
title: 'Log Book Discrepancy',
chartArea: {width: '50%'},
isStacked: true,
hAxis: {
title: 'HSFO, LSFO, and MGO',
minValue: 0,
},
};
var options2 = {
title: 'Bunkers Found',
chartArea: {width: '50%'},
hAxis: {
title: 'HSFO, LSFO, and MGO',
minValue: 0,
},
};
var chart1 = new google.visualization.BarChart(document.getElementById('log_book_discrepancy'));
chart1.draw(data1, options1);
var chart2 = new google.visualization.BarChart(document.getElementById('bunkers_found'));
chart2.draw(data2, options2);
}
https://jsfiddle.net/mblenton/pmeh4hr9/2/
or with MaterialChart:
https://jsfiddle.net/mblenton/gp12p37w/2/
Try this:
<script type="text/javascript" src="https://www.google.com/jsapi"></script>
<script type="text/javascript">
// Load the Visualization API and the piechart package.
google.load('visualization', '1', {packages: ['corechart', 'bar']});
// Set a callback to run when the Google Visualization API is loaded.
google.setOnLoadCallback(drawChart);
// Callback that creates and populates a data table,
// instantiates the pie chart, passes in the data and
// draws it.
function drawChart() {
// Create the data table.
var data1 = google.visualization.arrayToDataTable([
['Metric Tonnes', 'HSFO', 'LSFO', 'MGO'],
<?php
foreach ($log_book_discrepancy as $log_book)
{
?>
["<?php echo trim($log_book->type_of_vessel); ?>", <?php echo trim($log_book->fuel_hsfo); ?>, <?php echo trim($log_book->fuel_lsfo); ?>, <?php echo trim($log_book->fuel_mgo); ?> ],
<?php
}
?>
]);
// Create the data table.
var data2 = google.visualization.arrayToDataTable([
['Metric Tonnes', 'HSFO', 'LSFO', 'MGO'],
<?php
foreach ($bunker_found as $bunker)
{
?>
["<?php echo trim($bunker->type_of_vessel); ?>", <?php echo trim($bunker->fuel_hsfo); ?>, <?php echo trim($bunker->fuel_lsfo); ?>, <?php echo trim($bunker->fuel_mgo); ?> ],
<?php
}
?>
]);
// Set chart options
var options1 = {
chart: {
title: 'Log Book Discrepancy',
subtitle: 'HSFO, LSFO, and MGO',
}
};
// Set chart options
var options2 = {
chart: {
title: 'Bunkers Found',
subtitle: 'HSFO, LSFO, and MGO',
}
};
// Instantiate and draw our chart, passing in some options.
var chart1 = new google.visualization.BarChart(document.getElementById('log_book_discrepancy'));
chart1.draw(data1, options1);
var chart2 = new google.visualization.BarChart(document.getElementById('bunkers_found'));
chart2.draw(data2, options2);
}
</script>
<div id="log_book_discrepancy" style="width:100%; height:340px;"></div>
<div id="bunkers_found" style="width:100%; height:340px;"></div>

Categories

Resources