Queried Data as Datapoints on Chart.js - javascript

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?

Related

Passing values to chart.js - Laravel

I am able to fetch data from database which i want to pass to a chart.js. With the code below,
the chart displays ["{items: Nike}",total:20"},"{items: Addidas}",total:40"}] in the xaxis.
But then i want it to display like
categories: ['Nike', 'Addidas'];
Controller
$items = DB::table('items_tbl')->select('name', DB::raw('count(*) as total'))->groupBy('name')
->get();
return view('home',compact('items'));
HTML
<script>
var items_pass = #json($items)
</script>
JS
xaxis: {
categories: [JSON.stringify(items_pass)],
axisBorder: {
show: true,
color: '#bec7e0',
},
axisTicks: {
show: true,
color: '#bec7e0',
},
},

Highcharts adding series for every selectbox selection

I'm using Highcharts with MySQL and PHP... I have a Selectbox (Multiple Selections allowed) which contains company sections.
What I'm trying to do is create a new chart series for every selection the user chooses.
Example: If I choose from selectbox "option1,option2,option3" ... the chart will have 3 series for these 3 selected options. However, If I chose only option1, the chart will have only 1 series.
My code so far:
<script type="text/javascript">
$(function () {
$('#container').highcharts({
title: {
text: 'Daily Volume of Calls',
x: -20 //center
},
xAxis: {
type: 'datetime'
},
plotOptions: {
series: {
pointStart: Date.UTC(<?php echo $datefixed; ?>),
pointInterval: 24 * 3600 * 1000 // one day
}
},
yAxis: {
title: {
text: 'Total Calls'
},
plotLines: [{
value: 0,
width: 1,
color: '#808080'
}]
},
tooltip: {
valueSuffix: ' Calls'
},
legend: {
layout: 'vertical',
align: 'right',
verticalAlign: 'middle',
borderWidth: 0
},
series: [{
name: <?php echo $firstselection ?>,
data: [<?php echo join($callsarray, ',') ?>]
}, {
name: <?php echo $secondselection ?>, //**<<< THE PROBLEM IS HERE**
showInLegend: true,
data: []
}]
});
The problem on my code is if the variable $secondselection is empty or not set(meaning the user didn't chose more than 1 option), the chart will return a blank page even if $firstselection variable is set. But if the user chooses a second option, it will show fine.
Any help guys? :)

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

flot doesn't draw bars chart

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:

Graphing Data with jQuery Flot from a MySQL database

I am trying to have a graph display registration data generated from the mysql database. The format for data seems to be coming out correctly but the data is not being plotted. Please note that I am using CodeIgniter.
PHP:
public function graph_registrations()
{
$send = array();
$i = 1;
while($i <= 30){
$startTime = mktime(0, 0, 0, date('m'), date('d')-$i, date('Y'));
$endTime = mktime(23, 59, 59, date('m'), date('d')-$i, date('Y'));
$data = $this->admin_model->total_users_date($startTime, $endTime);
$new = array(date("M j", $startTime), $data);
$send[] = $new;
$i++;
}
echo json_encode($send);
}
JS:
var jsonData = $.ajax({
url: default_url+"admin/graph_registrations",
dataType:"json",
async: false
}).responseText;
console.log(jsonData);
var graphData = [{
// Visits
data: jsonData,
color: '#71c73e',
points: { radius: 4, fillColor: '#71c73e' }
}
];
// Lines
$.plot($('#graph-lines'), graphData, {
series: {
points: {
show: true,
radius: 5
},
lines: {
show: true
},
shadowSize: 0
},
grid: {
color: '#646464',
borderColor: 'transparent',
borderWidth: 20,
hoverable: true
},
xaxis: {
tickColor: 'transparent',
tickDecimals: 2
},
yaxis: {
tickSize: 1000
}
});
Everything works if I manually hard code the data in, but not when I grab it via ajax.
This is what console.log(jsonData) produces:
[["Dec 5",0],["Dec 4",0],["Dec 3",0],["Dec 2",0],["Dec 1",0],["Nov 30",0],["Nov 29",0],["Nov 28",0],["Nov 27",0],["Nov 26",0],["Nov 25",0],["Nov 24",0],["Nov 23",0],["Nov 22",0],["Nov 21",0],["Nov 20",0],["Nov 19",0],["Nov 18",0],["Nov 17",0],["Nov 16",0],["Nov 15",0],["Nov 14",0],["Nov 13",0],["Nov 12",0],["Nov 11",0],["Nov 10",0],["Nov 9",1],["Nov 8",0],["Nov 7",0],["Nov 6",0]]
I tried doing it without the date and just a plain number, but it did not work.
Thank you
For me you are trying to plot the data before having them. I can see you are using "async:false" to wait for the data to be loaded by I'd rather used the default "true" option and placed the plotting function in "success" callback of $.ajax.

Categories

Resources