flot doesn't draw bars chart - javascript

I tried with my other two scripts(line chart and pie chart) but the flot doesn't draw the bars chart... can you help me with this...I think the error is in the javascript..
The library:
<script src="js/jquery.flot.min.js"></script>
<script src="js/jquery.flot.pie.min.js"></script>
<script src="js/jquery.flot.stack.js"></script>
<script src="js/jquery.flot.resize.min.js"></script>
Here is the printdata db call:
[["junio",390],["julio",125],["agosto",50]]
Here is the script in graficayear.php:
<?php
include 'includes/configs.php';
$sql = $conn->prepare("SELECT DATE_FORMAT(start, '%M') AS mdate, SUM(honorario) AS total_mes
FROM CITAS WHERE YEAR(current_date) GROUP BY mdate DESC");
$sql->execute();
while($row = $sql->fetch(PDO::FETCH_ASSOC)) {
$datayear[] = array($row['mdate'],(int) $row['total_mes']);
}
?>
Here is the code in chartyear.php:
<?php include 'graficayear.php'; ?>
<script type='text/javascript' charset='utf-8'>
$(function () {
$.plot(
$("#baryear"),
[{
data : <?php echo json_encode($datayear);?>,
color: '#012D4C',
bars: { show: true, fillColor: '#4682b4', barWidth: (15*24*60*60*1000), align: 'center' }
}],
{
grid: { color: '#012D4C' },
xaxis: {
mode: 'time',
tickDecimals: 0,
tickSize: [1,'month'],
autoscaleMargin: 0.001
}
}
);
});
</script>
And the DIV with the ID:
<?php include 'chartyear.php'; ?>
<div id="baryear" style="width: 320px; height: 300px;"></div>
here is how my chart look like until now:
And this is the data I need to show inside of the bars chart:

You need to read the documentation on the expected data formats more carefully. Here you've specified an xAxis of type time but then have given it categories. You have to pick one way or the other.
So, given the format of you json data, here the shortest path to do what you want:
// given your data
var datayear = [["junio",390],["julio",125],["agosto",50]];
// split it into a data array and a ticks array
var data = [], ticks = [];
for (var i = 0; i < datayear.length; i++) {
data.push([i,datayear[i][1]]); // note that the x value is numeric
ticks.push([i,datayear[i][0]]); // and that the x value is matched to a "category"
}
$.plot(
$("#baryear"),
[{
data : data,
color: '#012D4C',
bars: { show: true, fillColor: '#4682b4', align: 'center' }
}],
{
grid: { color: '#012D4C' },
xaxis: {
ticks: ticks
}
});
Fiddle here.
Produces:

Related

Queried Data as Datapoints on Chart.js

I am trying to plot chart using Chart.JS based on my data from database. Here number of Labels and their values will come directly from the query result. Here is my code:
<script type="text/javascript">
window.onload = function () {
<?php
function getValsOfCategoryLabels(){
$yValsWithLabels = "";
......
// some codes to make query on db and get result in $queryResult variable
......
......
foreach($queryResult as $data){
$x0 = $data0['name'];
$total = $data0['total'];
$yValsWithLabels = $yValsWithLabels. "{y: ".$total.", label: \"".$x0."\"}, ";
}
return $yValsWithLabels;
}
?>
var categoryLabelsNdVals = [<?php echo getValsOfCategoryLabels() ?>];
var hourlyCategoryBarChart = new CanvasJS.Chart("columnchartContainer", {
animationEnabled: true,
axisX: {
labelFontSize: 16
},
axisY: {
title: "",
labelFontSize: 13
},
legend: {
verticalAlign: "bottom",
horizontalAlign: "center",
fontSize: 16
},
theme: "theme2",
data: [
{
type: "column",
showInLegend: true,
legendMarkerColor: "grey",
legendText: "Name of Category",
dataPoints: categoryLabelsNdVals
}
]
});
hourlyCategoryBarChart.render();
Now for the given datapoints (which is in "{y: Some_Value, label: Some_Name}" format) I am not getting any chart as output, unless I explicitly declare all the y-axis values and label names myself, which fails reflect database info.
What is the right way to accomplish my objective?

how to convert high charts code to nvd3.js

Here is my High Chart code for showing live Bitcoin Charts. I really am a noob at PHP, JavaScript etc, so i really need help in converting this code to nvd3.js
PHP Code:
<?php
// Set the JSON header
header("Content-type: text/json");
function getPrice($url){
$decode = file_get_contents($url);
return json_decode($decode, true);
}
$btce = getPrice('https://btc-e.com/api/2/btc_usd/ticker');
$btcePrice = round($btce["ticker"]["last"], 2);
// The x value is the current JavaScript time, which is the Unix time multiplied
// by 1000.
$x = time() * 1000;
// The y value is a random number
// Create a PHP array and echo it as JSON
$ret = array($x, $btcePrice);
echo json_encode($ret);
?>
HTML and Javascript Code:
<html>
<head>
<script src="http://ajax.googleapis.com/ajax/libs/jquery/1.8.2/jquery.min.js"></script>
<script src="http://code.highcharts.com/highcharts.js"></script>
</head>
<body>
<script type="text/javascript">
var chart; // global
/**
* Request data from the server, add it to the graph and set a timeout
* to request again
*/
function requestData() {
$.ajax({
url: 'x.php',
success: function(point) {
var series = chart.series[0],
shift = series.data.length > 175; // shift if the series is longer than 20
// add the point
chart.series[0].addPoint(point, true, shift);
// call it again after one second
setTimeout(requestData, 3000);
},
cache: false
});
}
$(document).ready(function() {
chart = new Highcharts.Chart({
chart: {
renderTo: 'container',
defaultSeriesType: 'spline',
events: {
load: requestData
}
},
title: {
text: 'Average price chart'
},
xAxis: {
type: 'datetime',
tickPixelInterval: 150,
maxZoom: 20 * 1000
},
yAxis: {
minPadding: 0.2,
maxPadding: 0.2,
title: {
text: 'USD',
margin: 80
}
},
series: [{
name: 'Live BTC USD Chart',
data: []
}]
});
});
</script>
<div id="container" style="width:100%; height:400px;"></div>
</body>
</html>
any help in explaining how to convert this code to work with nvd3.js would be greatly appreciated
Thanks!

Updating jqplot Pie Chart via JS not working

I am trying to update jqplot PieChart via JS since yesterday and I am not having any breakthrough with this. I have searched online and cant seem to get any solution work
The chart data is saved in session and this session is continuously being updated by the application.
This is what the JSON looks like
[ ['Take home pay', 44228.33], ['Tax', 8771.67], ['Super', 4162.5 ], ['Regular expenses', 0 ], ['Unallocated', 44228.33], ['Testing', 8000] ]
The chart loads fine when the user navigates to the page for the first time.
This is the DIV where the chart loads
<div id="savings_expense" class="jqplot-target"></div>
This is the jqplot JS when the page loads which works fine
$(document).ready(function () {
var storedData = <?php echo $_SESSION['chart_data'] ?>;
var plot1;
jQuery.jqplot.config.enablePlugins = false;
plot1 = jQuery.jqplot('savings_expense', [storedData],
{
seriesDefaults: {
renderer: jQuery.jqplot.PieRenderer
},
legend: {
show: true,
rendererOptions: {
numberRows: 6
},
placement: 'outside',
location: 's',
marginTop: '15px'
}
}
);
});
This is the button that user clicks to update the chart.
<li onclick="updateGraph()">YOUR TAKE-HOME PAY</li>
I have tried two ways to update the PieChart
Solution 1
In this solution I get the error Uncaught TypeError: Cannot read property 'replot' of undefined.
var storedData = <?php echo $_SESSION['chart_data'] ?>;
var plot1;
function renderGraph() {
plot1.replot({
seriesDefaults: {
renderer: jQuery.jqplot.PieRenderer
},
legend: {
show: true,
rendererOptions: {
numberRows: 6
},
placement: 'outside',
location: 's',
marginTop: '15px'
}
});
}
function updateGraph() {
alert('updateGraph');
var newVal = <?php echo $_SESSION['chart_data'] ?>;
storedData.push(newVal);
renderGraph();
}
Solution 2
In this solution the pie chart goes blank but the legends stay
var storedData = <?php echo $_SESSION['SMP']['chart_data'] ?>;
var plot1;
function renderGraph() {
if ( plot1) {
plot1.destroy();
}
jQuery.jqplot.config.enablePlugins = false;
plot1 = jQuery.jqplot('savings_expense',[storedData],
{
seriesDefaults: {
renderer: jQuery.jqplot.PieRenderer
},
legend: {
show: true,
rendererOptions: {
numberRows: 6
},
placement: 'outside',
location: 's',
marginTop: '15px'
}
}
);
}
I will really appreciate any help here. Please do not share any links as I have gone through about every solution I could find on StackOverflow and on net
You have to keep on document.ready code as it is and then add function updateGraph outside document.ready (keep all variable at global level). Also modify updateGraph, here you need to call .replot() on plot1 variable as you are only changing data and not other setting.
put id to li like this : <li id="updateGraph">YOUR TAKE-HOME PAY</li>
See below code :
// declare variable outside document.ready
var plot1;
var storedData;
$(document).ready(function () {
storedData = <?php echo $_SESSION['chart_data'] ?>;
jQuery.jqplot.config.enablePlugins = false;
plot1 = jQuery.jqplot('savings_expense', [storedData],
{
seriesDefaults: {
renderer: jQuery.jqplot.PieRenderer
},
legend: {
show: true,
rendererOptions: {
numberRows: 6
},
placement: 'outside',
location: 's',
marginTop: '15px'
}
}
);
$('#updateGraph').click(function(){updateGraph();});
});
function updateGraph() {
var newVal = <?php echo $_SESSION['chart_data'] ?>;
plot1.destroy();
plot1.series[0].data = newVal;
plot1.replot(true);
}

Highcharts Won't load from php json, but it could load from data.json file

I tried to make a highchart from JSON data. I make a php file that generating the json and insert the address to the getJSON() like this.
$(document).ready(function() {
$.getJSON("data.php", function(json) {
chart = new Highcharts.Chart({
chart: {...
and it wont work, so i decided to put the php inside the highcharts file like this.
<?php
$mysqli = new mysqli("localhost", "root", "", "test");
$resu = array();
$measurement = $_POST["choosenmeasurement"];
for($i = 0; $i < count($_POST["choosenbusid"]); $i++)
{
$busid = $_POST["choosenbusid"][$i];
$clusid = $_POST["choosenclusterid"][$i];
$fieldname = ''.$measurement.'_BUSID_'.$busid.'_CLUSTERID_'.$clusid;
$sql= "SELECT unix_timestamp, $measurement as $fieldname FROM `get` WHERE bus_id = $busid and cluster_id = $clusid";
$sth = $mysqli->query($sql);
$out = array();
$out['name'] = $fieldname;
while ($rr = $sth->fetch_assoc()) {
$out['data'][] = $rr[$fieldname];
}
array_push($resu,$out);
}
$jsonresult = json_encode($resu);
?>
<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=utf-8">
<title>Highcharts Example</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(<?php $jsonresult>, function(json) {
chart = new Highcharts.Chart({
chart: {
renderTo: 'container',
type: 'line',
marginRight: 130,
marginBottom: 25
},
title: {
text: 'testchart',
x: -20 //center
},
subtitle: {
text: '',
x: -20
},
yAxis: {
title: {
text: ''
},
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>
and it won't load either and i tried many ways with that method like put $jsonresult into javascript variable, echoing the json, print the json, print/echo into the getJSON() and still wont work eventhough if i echo the json to a blank space it'll print a json structure that i want.
BUT
if i put the JSON file into getJSON() like this
$(document).ready(function() {
$.getJSON("test.json", function(json)
it will works. but i would not copy paste the json that generated into the json file everytime i would load the charts.
i just wondering why. Any help?
I'm doing the same so in javascript part you have to inclide this:
var json = "<?php echo $pepito; ?>";
datar = JSON.parse(json);
This way you have the data from php in javascript
Also it's important to pass data in array and time in timestamp format multiplied by 1000. for example:
$timestamp=strtotime($fila[0].$fila[1])*1000;
//echo "\n".$timestamp;
$hola[0][]=array( $timestamp, (float)$fila[2]);//RGD
$hola[1][]=array( $timestamp, (float)$fila[3]);//RGA
You have to include the libraries before your script, not sure it's important but you should change it just in case:
<script src="//code.jquery.com/jquery-1.11.0.min.js"></script>
<script src="//code.jquery.com/jquery-migrate-1.2.1.min.js"></script>
<script src="http://code.highcharts.com/stock/highstock.js"></script>
<script src="http://code.highcharts.com/stock/modules/exporting.js"></script>
If you have any other quiestion or you need more info let me know.

Dojo Chart issues in naming label of X-axis name

I am new to dojo chart. I am trying to create a stacked column chart using dojo . I am trying to show bar chart with line chart using dojo chart.Chart is appear. But here is my problem is how can i write my x-axis label name which comes from my database.I want to naming each bar's name on X-axis. My actual values comes from database. I searches from all stack overflow suggestion,dojo guides and from others but i could not found any proper solution.So i request to you please help me where my code is wrong.So here i can rectify me for futures.
Here is my code index.php
<?php
include "connection.php";
$array = array();
$array1 = array();
$array2 =array();
$query1 = "SELECT name,rate1,rate2 FROM TEST";
$result = mysql_query($query1) or die ('Could not find Projects');
while ($rows = mysql_fetch_array($result)){
$array1[]=$rows['name'];
$array1[]=$rows['rate1'];
$array2[]=$rows['rate2'];
}
print_r($array1);
print_r (json_encode($array1,JSON_NUMERIC_CHECK));
print_r (json_encode($array2,JSON_NUMERIC_CHECK));
<html><head>
<link rel="stylesheet" href="dijit/themes/tundra/tundra.css">
<script>dojoConfig = {parseOnLoad: true}</script>
<script src='dojo/dojo.js'></script>
<script type="text/javascript">
require(["dojox/charting/Chart",
//"dojox/charting/plot2d/Lines",
"dojox/charting/axis2d/Default",
"dojox/charting/plot2d/StackedColumns",
"dojox/charting/action2d/Tooltip",
"dojo/ready",
"dojox/charting/widget/SelectableLegend"],
function(Chart, Default, StackedColumns, Tooltip, ready, SelectableLegend) {
ready(function() {
var chart1 = new Chart("chart1");
chart1.addPlot("stackedColumnsPlot", {
type: StackedColumns,
lines: true,
areas: true,
markers: true,
tension: "S"
});
chart1.addPlot("linesPlot", {
type: Lines,
markers: true,
stroke: {
width: 2
},
tension: 2
});
chart1.addAxis("x");
chart1.addAxis("y", {
vertical: true
});
chart1.addSeries("Series 1", <?php echo json_encode($array1,JSON_NUMERIC_CHECK); ?>
, {
plot: "stackedColumnsPlot",
stroke: {
color: "blue"
},
fill: "lightblue"
});
chart1.addSeries("Series 2", <?php echo json_encode($array2,JSON_NUMERIC_CHECK); ?>, {
plot: "stackedColumnsPlot",
stroke: {
color: "green"
},
fill: "lightgreen"
});
new Tooltip(chart1, "stackedColumnsPlot", {
text: function(chartItem) {
console.debug(chartItem);
return "Value: " + chartItem.run.data[chartItem.index] + "; Stacked Value: " + chartItem.y;
}
});
chart1.render();
new SelectableLegend({
chart: chart1,
horizontal: false
}, "chart1SelectableLegend");
});
});
</script>
This is my code what i am writing for stacked column chart.So suggest me how can i write label name of x-axis in my chart which comes from my database.
Add a label to the x axis:
Here are a few examples:
Use title property for one label for the entire axis.
chart.addAxis("x", {
min: 0, max: 100,
fontColor: "blue",
vertical: true,
fixLower: "major", fixUpper: "major",
title: "X axis title",
titleFont: "bold bold bold 12pt Arial,sans-serif",
titleOrientation: "axis"
});
For labels on each tick mark on the x axis:
var xAxisLabels = [{text: "Today",value: 1},{text: "-1",value: 2},{text: "-2",value: 3},{text: "-3",value: 4},{text: "-4",value: 5},{text: "-5",value: 6},{text: "-6",value: 7},{text: "WK-1",value: 8},{text: "WK-2",value: 9},{text: "WK-3",value: 10},{text: "WK-4",value: 11}];
chart.addAxis("x", {
labels: xAxisLabels,
fontColor: "blue",
majorTicks:true,
majorTickStep:1,
minorTicks:false,
max: 11
});
Not sure about the database part

Categories

Resources