How to create Chart with 2 variables (x,,y) - php

I am looking forward chart like this https://i.stack.imgur.com/a6dAq.png with this code
php + html:
$sql = "SELECT val1 , val2 ,t
FROM DvojeHodnoty
INNER JOIN Pristroje ON DvojeHodnoty.dev_name = Pristroje.dev_name
WHERE t>'$startdate2' AND t< '$enddate2' AND Pristroje.nazev_pristroje='$pristroj' order by val1 asc;";
$result = mysqli_query($connection, $sql);
while ($row = mysqli_fetch_array($result))
{
$t = $t.'"'.date('d.m.y H:i:s', $row['t']/1000).'",';
$hodnota = $hodnota.'"'.$row['val1'].'",';
$hodnota2 = $hodnota2.'"'.$row['val2'].'",';
}
$start = date('d.m.y', $startdate2/1000);
$end = date('d.m.y', $enddate2/1000);
$t = trim($t,",");
$hodnota = trim($hodnota,",");
$hodnota2 = trim($hodnota2,",");
}
<div id="chart-container" style="background: white">
<canvas id="chart"></canvas>
<script>
var ctx =document.getElementById("chart").getContext('2d');
var myChart = new Chart(ctx, {
type:'line',
data: {
labels: [<?PHP echo $hodnota2; ?>],
datasets:
[
{
label: '<?PHP echo $start;?> - <?PHP echo $end; ?> Přístroj: <?PHP echo $pristroj;?> ',
data: [<?PHP echo $hodnota; ?>],
backgroundColor:'transparent',
borderColor:'rgba(255,99,132)',
borderWidth: 3
}]
},
options: {
scales: {
yAxes:[{
scaleLabel: {
display: true,
labelString: 'σ',
fontSize: 20
}
}],
xAxes:[{
scaleLabel: {
display: true,
labelString: 'ε',
fontSize:20
}
}]
}
}
})
</script>
</div>
but so far I got only this https://i.stack.imgur.com/Ri8Ho.png.
I don't know how to create chart with two variables, I tried scatter but so far I am stuck with no ability to create graph with x,y line as values. Is there any easy way to create chart with two variables? If so can you help me/ give me some documentation? (I've seen one scatter chart with fix values, but I am not able to do it with php echo (with values from database) since I need to have variable values since user will choose values depends on chosen date. So far I got only 1 value (y) and two values but with text (numbers counted as text not as value) so chart looks weirdly (0,1,-1 still on same line not like normal graph showned up).

The problem was that data type was VARCHAR and for sorting it I need INT. Problem solved

Related

formatting date in a morris chart with php mysql data

i am just trying to make my date appear "M d, Y" in my morris chart ... i am getting all of the data over correctly, but i can't seem to format the date how i want ... can anybody help?
here is my code:
$get_bar_scores = "SELECT * FROM user_rounds WHERE user_id = '".$row_user['user_id']."'";
$run_bar_scores = mysqli_query($con, $get_bar_scores); ?>
<script>
$(function(){
Morris.Line({
element: 'line-score',
data: [
<?php while($row_bar_scores = mysqli_fetch_array($run_bar_scores)) { ?>
{
y: '<?php echo $row_bar_scores['date_played']; ?>',
a: '<?php echo $row_bar_scores['total']; ?>',
},
<?php } ?>],
xkey: 'y',
ykeys: ['a'],
labels: ['Score'],
lineColors:['#16a085','#FF0066']
});
})
</script>
like i said, all of the info is appearing correctly, i would just like to have the date to show up cleaner ... i have tried: date("M d, Y", strtotime($row_bar_scores['date_played'])); but to no avail.
any and all help is greatly appreciated!! thanks!!
First, you should explicitly select your columns...but that's another topic.
"SELECT DATE_FORMAT(date_played,'%M %d %Y') as date_played FROM user_rounds WHERE user_id =...

Flot Chart (Array 3 values)

I'd like to know if is possible to do that with Flot chart, because I'm not sure...
I have a table on a database with 3 rows: Date Start, Date End, Medication
Mi PHP code:
$sql = "SELECT * FROM medications ORDER BY DateStart";
$stmt = $PDO -> query($sql);
$result=$stmt -> fetchAll(PDO::FETCH_ASSOC);
foreach ($result as $row){
$dateini= $row['DateStart'];
$datend= $row['DateEnd'];
$medic= $row['Medication'];
$data1 = array(strtotime($dateini)*1000,$medic);
$data2 = array(strtotime($datend)*1000,$medic);
$data3[] = array($data1,$data2);
}
If I do:
echo json_encode($data3);
I get the array:
[[[1456531200000,"12"],[1456704000000,"12"]],[[1456531200000,"16"],[1456704000000,"16"]],[[1456617600000,"13"],[1456790400000,"13"]],[[1456704000000,"14"],[1457049600000,"14"]]]
<script>
var data3 = <?php echo json_encode($data3)?>;
$(function() {
var datasets = [
{
label: "Medication",
data: data3,
yaxis: 1,
color: "Yellow",
points: { symbol: "diamond", fillColor: "Yellow",show: true, radius: 6}
}
];
$.plot($("#flot-placeholder"), datasets ,options);
</script>
This: $.plot($("#flot-placeholder"), datasets ,options) don't plot anything, but if I do:
$.plot($("#flot-placeholder"), data3,options);
I get
It would be possible to get the graphic writing datasets (in $.plot) instead data3?
Two issues with your datasets array:
Your data3 array has multiple data series but you try to put it all into one data set object in the datasets array. Put each data series in a separate object (with its own options where neccessary).
var datasets = [{
label: "Medication",
data: data3[0],
yaxis: 1,
color: "Yellow",
points: {
symbol: diamond,
fillColor: "Yellow",
show: true,
radius: 6
}
}, {
label: "Medication",
data: data3[1],
yaxis: 1,
color: "red",
points: {
symbol: diamond,
fillColor: "red",
show: true,
radius: 6
}
}, ... ]
Flot has no build-in diamond symbol, you have to provide a function which draws a diamond.
function diamond(ctx, x, y, radius, shadow) {
var size = radius * Math.sqrt(Math.PI) / 2;
ctx.moveTo(x - size, y);
ctx.lineTo(x, y + size);
ctx.lineTo(x + size, y);
ctx.lineTo(x, y - size);
ctx.lineTo(x - size, y);
}
See this fiddle for a full working example.

Date data from MySQL to Highcharts

Really new to Highcharts and PHP. Trying to use date from my SQL database but can get the X-axis to recognise the data as dates.
My PHP request looks like this:
<?php
mysql_connect('xxxxxxxxxxxxx.ipagemysql.com', 'xxxxx', 'xxxxxxxx') or die(mysql_error());
mysql_select_db("history") or die(mysql_error());
$result = mysql_query("SELECT * FROM eur_weekly")
or die(mysql_error());
WHILE ($row = mysql_fetch_array( $result )) {
$EUR1 [] = $row ['price'];
$EUR2 [] = $row ['date'];}
?>
Where "date" is my date column organised as follow:
31.01.2014
31.12.2013
30.11.2013
31.10.2013
30.09.2013
31.08.2013
In my HTML code I use this function that works with the rest of the data but it wont recognise the "dates" as dates data for the x-axis:
<script type="text/javascript">
$(function () {
$('#container').highcharts({
chart: {
zoomType: 'x'
},
title: {
text: 'EUR/USD '
},
xAxis: [{
type: 'datetime',
categories: [<?php echo join($EUR2,',') ?> ],
}],
yAxis: [{
labels: {
format: '{value} price',
style: {
color: '#CC33FF',
lineWidth: 0.5
}
},
}],
tooltip: { },
series: [{
name: 'EUR/USD',
color: '#4572A7',
type: 'spline',
marker:{ enabled: false},
zIndex:1,
data: [ <?php echo join($EUR1, ',') ?> ],
}]
});
});
</script>
Is there a transformation I should do? Can't find a simple example of dates from MySQL imported into Highcharts..
Thank you and best regards!
You need to parse your dates, to achieve that you can transform time to unix and multiply by 1000 in the php, other solution is parse dates in javascript.
I advice to use json_encode(), which return json in php (then load it by getJSON() in javascript), instead of inject php inside javascript.

Get json data into Highcharts scatter plot

I cannot get Highcharts to graph a scatter plot of 2 series. Actually, the graph isn't even showing up. Please help me determine what I'm doing wrong. I cannot find a scatter plot example to go off of and I am very new to this. I've got json data from a php file that looks like:
[[65,44],[66,37],[67,42],[68,55],[65,50],[65,41],[65,41],[68,41],[69,42],[70,47],[69,55],[67,45],[67,49],[67,53],[67,49],[68,51],[68,55],[68,57],[70,53],[69,66],[68,54],[69,52],[68,48]][[75,36],[72,42],[75,44],[69,56],[72,40],[73,37],[77,34],[77,40],[74,50],[77,45],[77,43],[75,47],[73,52],[73,50],[75,44],[72,54],[71,57],[72,57],[74,55],[74,54],[75,47],[78,45],[75,43]]
This should be two series in an (x,y) format. I want to graph these on a scatter plot in HighCharts. My HighCharts code is:
<script type="text/javascript">
$(function () {
var chart;
$(document).ready(function() {
$.getJSON("comfortgb1b.php", function(json) {
chart = new Highcharts.Chart({
chart: {
renderTo: 'container4',
type: 'scatter',
marginRight: 175,
marginBottom: 50
},
title: {
text: 'Comfort Level',
x: -20 //center
},
subtitle: {
text: '',
x: -20
},
xAxis: {
title: {
enabled: true,
text: 'Temp (F)'
},
min: 60,
max: 85,
startOnTick: true,
endOnTick: true,
showLastLabel: true
},
yAxis: {
title: {
text: 'Humidity (%RH)'
},
min: 30,
max: 100
},
plotOptions: {
scatter: {
marker: {
radius: 5,
states: {
hover: {
enabled: true,
lineColor: 'rgb(100,100,100)'
}
}
},
states: {
hover: {
marker: {
enabled: false
}
}
},
tooltip: {
headerFormat: '<b>{series.name}</b><br>',
pointFormat: '{point.x} F, {point.y} %RH'
}
},
series: [{
name: 'Night',
data: json(1)
}, {
name: 'Night',
data: json(2)
});
});
});
});
</script>
Thanks in advance!
The php file that is creating the json data is below. How would I separate these arrays with a comma?
$result1 = mysql_query("SELECT round(AVG(d_internal_duct_return),0) AS 'avg_return', round(AVG(d_evap_pre_humidity),0) AS 'avg_hum' FROM pheom.pheom_gb WHERE timestamp between subdate(curdate(), interval 2 month) and curdate() AND HOUR(Timestamp) NOT BETWEEN 9 AND 22 GROUP BY DAY(Timestamp) ORDER BY Timestamp");
$ret1 = array();
while($item = mysql_fetch_array($result1)) {
$avg_return1 = $item['avg_return'];
$avg_hum1 = $item['avg_hum'];
$ret1[] = array($avg_return1,$avg_hum1);
}
$result2 = mysql_query("SELECT round(AVG(d_internal_duct_return),0) AS 'avg_return', round(AVG(d_evap_pre_humidity),0) AS 'avg_hum' FROM pheom.pheom_gb WHERE timestamp between subdate(curdate(), interval 2 month) and curdate() AND HOUR(Timestamp) BETWEEN 9 AND 22 GROUP BY DAY(Timestamp) ORDER BY Timestamp");
$ret2 = array();
while($item = mysql_fetch_array($result2)) {
$avg_return2 = $item['avg_return'];
$avg_hum2 = $item['avg_hum'];
$ret2[] = array($avg_return2,$avg_hum2);
}
echo json_encode($ret1, JSON_NUMERIC_CHECK);
echo json_encode($ret2, JSON_NUMERIC_CHECK);
Not sure about this, but at first glance I think the array returned from the php file requires an additional square bracket outside it in order to be parsed as proper json. Currently it is:
[[65,44],[66,37]..][[75,36],[72,42]..]
From what I know, this is just two arrays. What you want is to enclose these arrays within an array. Try changing this to:
[[[65,44],[66,37]..],[[75,36],[72,42]..]]
That is, add an extra square bracket outside and separate the two arrays using a comma.
In addition, here:
series: [{
name: 'Night',
data: json(1)
}, {
name: 'Night',
data: json(2)
});
json(1) and json(2) are interpreted as function calls. You should instead use:
series: [{
name: 'Night',
data: json[0]
}, {
name: 'Night',
data: json[1]
});
EDIT ---- Edited as per OP edits
Also as requested, in order to add the commas and proper formatting, the php file can be changed at the last two lines as follows:
echo "[".json_encode($ret1, JSON_NUMERIC_CHECK).",";
echo json_encode($ret2, JSON_NUMERIC_CHECK)."]";
You have several things giving you problems. See this fiddle: http://jsfiddle.net/nbwN9/1/
First, I don't think your json is in the proper format for a 2 series plot. You have two arrays of data just butted up to each other rather than in another array. The linked fiddle corrects that (and stuffs it into a var since the getJSON() call will fail within jsFiddle). Each point is an array of (x,y) coords. Each series.data is an array of points. Your json will need to be an array of series.data arrays. So we're looking at nested arrays 3 deep.
Second, you seem to have a malformed set of chart options. Most notable is that your series node (with name and data) is inside your plotOptions node when it should be outside of it. And that series node is not terminated properly.
Third, once you get your json data and your chart options formatted correctly, accessing the json array is done like so:
series: [{
name: 'Night',
data: json[0]
}, {
name: 'Day',
data: json[1]
}]
The array is 0-based (so the first record will be indexed with a 0, second record with a 1, etc) and is access using the brackets [] not parentheses ()
Sorry, I renamed one of your series to "Day" so I could see the difference in the chart.
As far as the PHP script... try this:
$result1 = mysql_query("SELECT round(AVG(d_internal_duct_return),0) AS 'avg_return', round(AVG(d_evap_pre_humidity),0) AS 'avg_hum' FROM pheom.pheom_gb WHERE timestamp between subdate(curdate(), interval 2 month) and curdate() AND HOUR(Timestamp) NOT BETWEEN 9 AND 22 GROUP BY DAY(Timestamp) ORDER BY Timestamp");
$ret1 = array();
while($item = mysql_fetch_array($result1)) {
$avg_return1 = $item['avg_return'];
$avg_hum1 = $item['avg_hum'];
$ret1[] = array($avg_return1,$avg_hum1);
}
$result2 = mysql_query("SELECT round(AVG(d_internal_duct_return),0) AS 'avg_return', round(AVG(d_evap_pre_humidity),0) AS 'avg_hum' FROM pheom.pheom_gb WHERE timestamp between subdate(curdate(), interval 2 month) and curdate() AND HOUR(Timestamp) BETWEEN 9 AND 22 GROUP BY DAY(Timestamp) ORDER BY Timestamp");
$ret2 = array();
while($item = mysql_fetch_array($result2)) {
$avg_return2 = $item['avg_return'];
$avg_hum2 = $item['avg_hum'];
$ret2[] = array($avg_return2,$avg_hum2);
}
echo json_encode(array($ret1,$ret2), JSON_NUMERIC_CHECK);

Get value with php and mysql in var name[value1,value2,value2]

How I can insert array value in php and mysql from variable Var s1, s2, s3:
$(function () {
var s1 = [100, 200, 300]; //How to Get Value from mysql database
var s2 = [30, 80, 90]; //How to Get Value from mysql database
var s3 = [120, 90, 80]; //How to Get Value from mysql database
// Can specify a custom tick Array.
// Ticks should match up one for each y value (category) in the series.
var ticks = ['2010', '2011', '2012'];
var plot1 = $.jqplot('chart3', [s1, s2, s3], {
// The "seriesDefaults" option is an options object that will
// be applied to all series in the chart.
seriesDefaults: {
shadow: true, // show shadow or not.
renderer: $.jqplot.BarRenderer,
rendererOptions: {
fillToZero: true
}
},
// Custom labels for the series are specified with the "label"
// option on the series option. Here a series option object
// is specified for each series.
series: [
{label: 'Hotel'},
{label: 'Event Regristration'},
{label: 'Airfare'}
],
// Show the legend and put it outside the grid, but inside the
// plot container, shrinking the grid to accomodate the legend.
// A value of "outside" would not shrink the grid and allow
// the legend to overflow the container.
legend: {
show: true,
placement: 'outsideGrid'
},
axes: {
// Use a category axis on the x axis and use our custom ticks.
xaxis: {
renderer: $.jqplot.CategoryAxisRenderer,
ticks: ticks
},
// Pad the y axis just a little so bars can get close to, but
// not touch, the grid boundaries. 1.2 is the default padding.
yaxis: {
pad: 1.05,
tickOptions: {
formatString: '$%d'
}
}
},
grid: {
borderColor: '#000', // CSS color spec for border around grid.
borderWidth: 2.0, // pixel width of border around grid.
shadow: true // draw a shadow for grid.
}
});
// Bind a listener to the "jqplotDataClick" event. Here, simply change
// the text of the info3 element to show what series and ponit were
// clicked along with the data for that point.
$('#chart3').bind('jqplotDataClick',
function (ev, seriesIndex, pointIndex, data) {
$('#info3').html('series: ' + seriesIndex + ', point: ' + pointIndex + ', data: ' + data);
});
});
2 ways:
Ajax
Use: $.getJSON ( http://api.jquery.com/jQuery.getJSON/ )
var ses = {};
$.getJSON('page_adress.php', {variable_you_want_to_pass1: 'its value', variable_you_want_to_pass2: 'var 2 value'}, function(data) {
ses = data;
});
In your PHP:
<?php
$passed_var_1 = $_REQUEST['variable_you_want_to_pass1'];
//.... etc
//Here you get your data from mysql, cast it into array
header('Content-type: application/json');
echo json_encode($dbdata);
?>
So basically after request finishes you will have exact array you had in PHP transferred in JavaScript. Have in mind that this technique uses AJAX. If you want to avoid that, you will have to use second technique.
Dynamically Creating JS
Make PHP generate your javascript. In this case you would have in your main page
<script src="js_data.js.php" type="text/javascript"></script>
In your js_data.js.php file:
<?php
header("content-type: application/x-javascript");
$s1 = array(100,200,300);
//....
var s1 = [<?=implode(', ', $s1)?>],
s2 = [<?=implode(', ', $s2)?>],
s3 = [<?=implode(', ', $s3)?>];
?>
First method (w/o ajax & json)(untidy-way)
First fetch the value from database and have it in PHP variable.
Then put html element in page and assign the value to it.
Then use it in javascript using document.getElement method.
// assume that you have got value from database in $valueFrmDB.
$valueFrmDB;
Now, take html element(you might have to take more than one)
<input type="hidden" id="something" name="something" value="echo value of $valueFrmDB here" />;
Then, in javascript
var vfd = document.getElementById('something').value;
convert string to array
Second method(with ajax and json)(simple & correct but must know ajax and json)
Use ajax to fetch the values from database
Then use json to pass that values to javascript
simply you can do this by:
<?php
$query = mysql_query("SELECT * FROM attendence");
$results = array(array());
while($line = mysql_fetch_array($query)){
$results[] = $line;
}
?>
Javascript
<script type="text/javascript">
$(document).ready(function(){
var data = <?php echo json_encode($results); ?>; //array uses here
var plot1 = jQuery.jqplot ('chart1', [data],
{
seriesDefaults: {
renderer: jQuery.jqplot.PieRenderer,
rendererOptions: {
showDataLabels: true}
},
legend: { show:true, location: 'e' }
});
});
</script>

Categories