OOCharts monthly timeline - google-analytics-api

I'm using Oocharts.com's API and I'm doing a 12 month timeline chart, but it displays a daily data point for each day instead of combining them into a monthly amount. So, instead of displaying 1 visit per day, I want it to show 30 visits for the month. How can I do that?
Here's a link to their documentation, I read the entire thing and don't see how to do this. I even changed my date range from 1y to 12m and it didn't do anything.
http://docs.oocharts.com/

I solved this by using an oocharts query + google's visualization API. Here's my code for displaying filtered results for the last 12 months:
// What's our months?
$months = array();
for ($i = -12; $i < 0; $i++)
{
$month_time = strtotime($i . ' months');
$months[] = date('F Y', $month_time);
}
// Add js code to get unique page views for last year on a timeline chart
$oocharts_js .= '
oo.load(function(){
var query = new oo.Query("' . $this->config->item('oocharts_profile_id') . '", "13m");
query.addMetric("ga:uniquePageviews");
query.addDimension("ga:nthMonth");
query.setFilter("' . $oochart_filter . '");
query.setIndex(2);
query.execute(function(data){
console.log(data.rows);
google.load("visualization", "1", {packages:["corechart"]});
var dataTable = google.visualization.arrayToDataTable([
["Month", "Page Visits"],
';
foreach ($months as $key => $value)
{
$oocharts_js .= '["' . $value . '", data.rows[' . $key . '][1]],';
}
$oocharts_js .= '
]);
var options = {
chartArea: {top: 10, left: 30, height: "60%"},
hAxis: {
slantedText: true,
},
vAxis: {
viewWindow:{
min:0,
},
},
pointSize: 5,
lineWidth: 3,
};
var chart = new google.visualization.LineChart(document.getElementById("chart_' . $business->business_id . '"));
chart.draw(dataTable, options);
});
});
';

Related

Google Charts -- Axis Values overlapping and how to avoid

How do I avoid this axis overlap in google charts? I am working with a large data set and not sure what to do to solve this issue. I am using a large number of dates for the x axis. The options I use for my chart are
var options = {
tooltip: {
trigger: 'both',
},
width: 1900,
height: 400,
vAxis: { 'title': 'Volume' },
crosshair: { trigger: 'both'}
};
EDIT::
PHP creation of the containers
if( isset($db_graph_query)){
while($row = mysqli_fetch_array($db_graph_query)) {
$rowcount2++;
// removed the hard coded column set and made it driven off of the array below
// could have pulled it from the $cols array above, but there might be columns that we don't wish to show
echo " <tr>";
$colindex = 0;
foreach( $cols as $column_name ) {
$style = "";
$val = $row[$column_name];
if ( isset($column_callback)) {
$style=$column_callback($colindex, $val);
}
if ($colindex == 0) {
echo "<td style='text-align: left; width: 1pt;'><a href='#' class='toggle' onClick='drawChart(\"$val\");'>$val</a></td>";
$tempval = $val;
} else {
echo "<td $style>$val</td>";
}
$colindex++;
}
echo "</tr>";
echo "<tr class='tablesorter-childRow'>";
echo "<td colspan='12'>";
echo "<div id='$tempval' style='height: 400px;'></div>";
echo "</td>";
echo "</tr>";
}
}
EDIT::
Draw Chart Script, creates the chart options, grabs data from SQL DB and adds into the data:
<script type="text/javascript" src="https://www.gstatic.com/charts/loader.js"></script>
<script type="text/javascript">
google.charts.load('current', {'packages':['corechart']});
function drawChart(inputname) {
var data = new google.visualization.DataTable();
data.addColumn('string', 'Name');
data.addColumn('string', 'RunDate');
data.addColumn('number', 'Runs');
data.addColumn('number', 'Fails');
data.addRows([
<?php
$dbName = "mydb";
$config = parse_ini_file("configfile.ini",true);
$dbUser = $config["DB"]["db_user"];
$dbServer = $config["DB"]["db_ip"];
$dbPassword = $config["DB"]["db_pass"];
$con = mysql_connect($dbServer, $dbUser, $dbPassword);
if (!$con) {
die('Could not connect: ' . mysql_error());
}
mysql_select_db($dbName, $con);
$sql = mysql_query("SELECT * From MyTestTable");
$output = array();
while($row = mysql_fetch_array($sql)) {
// create a temp array to hold the data
$temp = array();
// add the data
$temp[] = '"' . $row['Name'] . '"';
$temp[] = '"' . $row['RunDate'] . '"';
$temp[] = (int) $row['Runs'];
$temp[] = (int) $row['FailCount'];
// implode the temp array into a comma-separated list and add to the output array
$output[] = '[' . implode(', ', $temp) . ']';
}
// implode the output into a comma-newline separated list and echo
echo implode(",\n", $output);
mysql_close($con);
?>
]);
var view = new google.visualization.DataView(data);
view.setRows(data.getFilteredRows([
{column: 0, value: inputname}
]));
view.setColumns([1,2,3]);
var options = {
tooltip: {
trigger: 'both',
},
vAxis: { 'title': 'Volume' },
crosshair: { trigger: 'both'},
width: 1900,
height: 400
};
var chart = new google.visualization.LineChart(document.getElementById(inputname));
chart.draw(view, options);
}
</script>
try using option for slanted text...
hAxis: {slantedText: true}
The horizontal axis ticks should not be overlapping at all, and I believe the only way this could be happening is if your chart is not visible at the time you draw it, in which case the chart thinks the ticks don't take up any space and can be packed in as dense as possible. Slanting or alternating would not necessarily help until you get down to the minimum spacing constraint.
So the only real solution, at this time, is to make sure your chart is visible when you draw it.

jQuery UI Autocomplete category is selecting only results in all categories

I have used the jQuery UI Autocomplete demo source code for the Categories example (http://jqueryui.com/autocomplete/#categories) and have it working (querying a database which returns a JSON array).
I'm building a search function for an art gallery and my categories are Artists and Exhibitions. I want to show results from one or both categories. My problem is that results are only showing when the search term covers a result in both categories.
My suggestions script uses the search term to query two different database tables. I format and append the results into a single JSON array with rows for ["id"], ["value"], ["label"] and ["category"].
So for the search term CORN, the results that come back might be:
{ label: "Christopher Corner", category: "Artists" },
{ label: "New Pictures From Cornwall", category: "Exhibitions" },
{ label: "Cornie Collins", category: "Artists" },
At the moment when I type a search term, the possible results are only shown as long as a result is possible in ALL my categories, rather than what I want, which is one or more. So when I type CORN, I can see an Artist named Corner, and an Exhibition about Cornwall, but the minute I type the E of CORNE, all the options disappear, including the Artist whose name is Corner (which I would expect to remain).
I'm new to jQuery and jQuery UI and struggling to understand where the logic would be to select a list item from any category rather than all of them.
I have edited to add my code. This is the backend suggestions file - search_suggestions.php:
<?php
# if the 'term' variable is not sent with the request, exit
if (!isset($_REQUEST['term'])) {
exit;
}
# retrieve the search term that autocomplete sends
$term = trim(strip_tags($_GET['term']));
$a_json = array();
$a_json_row = array();
# connect to database, send relevant query and retrieve recordset
include 'includes/db_access.php';
$compoundFind = $fm->newCompoundFindCommand('web_Artists');
$request1 = $fm->newFindRequest('web_Artists');
$request2 = $fm->newFindRequest('web_Artists');
$request1->addFindCriterion('Last name', '*'.$term.'*');
$request2->addFindCriterion('First name', '*'.$term.'*');
$compoundFind->add(1, $request1);
$compoundFind->add(2, $request2);
$compoundFind->addSortRule('Last name', 1, FILEMAKER_SORT_ASCEND);
$result = $compoundFind->execute();
if (FileMaker::isError($result)) {
die();
}
$records = $result->getRecords();
# loop through records compiling JSON array
foreach ($records as $record) {
$artistID = htmlentities(stripslashes($record->getRecordID())) ;
$artistName = htmlentities(stripslashes($record->getField('Full name'))) ;
$a_json_row["id"] = $artistID;
$a_json_row["value"] = $artistName;
$a_json_row["label"] = $artistName;
$a_json_row["category"] = "Artists";
array_push($a_json, $a_json_row);
}
$findCommand = $fm->newFindCommand('web_Exhibitions');
$findCommand->addFindCriterion('Title', '*'.$term.'*');
$result = $findCommand->execute();
if (FileMaker::isError($result)) {
die();
}
$records = $result->getRecords();
foreach ($records as $record) {
$exhibitionID = htmlentities(stripslashes($record->getField('Exhibition ID'))) ;
$exhibitionTitle = htmlentities(stripslashes($record->getField('Title'))) ;
$a_json_row["id"] = $exhibitionID;
$a_json_row["value"] = $exhibitionTitle;
$a_json_row["label"] = $exhibitionTitle;
$a_json_row["category"] = "Exhibitions";
array_push($a_json, $a_json_row);
}
echo json_encode($a_json);
flush();
?>
And here is the JS in my section which sets things up:
<style>
.ui-autocomplete-category {
font-weight: bold;
padding: .2em .4em;
margin: .8em 0 .2em;
line-height: 1.5;
}
</style>
<script>
$.widget( "custom.catcomplete", $.ui.autocomplete, {
_create: function() {
this._super();
this.widget().menu( "option", "items", "> :not(.ui-autocomplete-category)" );
},
_renderMenu: function( ul, items ) {
var that = this,
currentCategory = "";
$.each( items, function( index, item) {
var li;
if ( item.category != currentCategory ) {
ul.append( "<li class='ui-autocomplete-category'>" + item.category + "</li>" );
currentCategory = item.category;
}
li = that._renderItemData( ul, item );
if ( item.category ) {
li.attr( "aria-label", item.category + " : " + item.label );
}
});
}
});
</script>
<script>
$(function() {
$( "#searchInput" ).catcomplete({
minLength: 2,
source:'search_suggestions.php'
});
});
</script>
Finally this is the actual input field on the page:
<input class="u-full-width" placeholder="Search" id="searchInput" />
Sorry if this is too much code!

How put dates on flot

I've a little problem, I need to do a curve with on y axis numbers and x axis dates.. but I can't display some dates...
My code :
<script type="text/javascript">
$(function () {
<?php
echo " var data = [";
$cpt="0";
include ('../connect.php');
// Requete SQL
$req = 'select "SPP_NB_IND" from "STAT_PERPHY" where "SPP_SAGES" = \''.$sages.'\' AND "SPP_DATE" between \''.$jourtableau.' 00:00:00\' and \''.$jourfinw.' 23:59:59\'';
$res = pg_query($req);
$reqd = 'select "SPP_DATE" from "STAT_PERPHY" where "SPP_SAGES" = \''.$sages.'\' AND "SPP_DATE" between \''.$jourtableau.' 00:00:00\' and \''.$jourfinw.' 23:59:59\' AND "SPP_NB_IND" IS NOT NULL ';
$resd = pg_query($reqd);
// On met les valeurs obtenues dans un tableau
while ( $row = pg_fetch_assoc ($res) )
{
//echo $row['SPP_NB_IND']."<br>";
$var=$row['SPP_NB_IND'];
while ( $roww = pg_fetch_assoc ($resd) )
{
$abscisse=date('d-m', strtotime($roww['SPP_DATE']));
}
echo "[$abscisse, $var],";
$cpt++;
}
echo "];";
?>
var options = {
lines: {
show: true
},
points: { show: true
},
xaxis: {
mode: "time",
timeformat : "%d/%m"
}
};
<?php
echo "$.plot($(\"#graph1\"), [ data ], options);";
?>
});
</script>
[/CODE]
When I put $abscisse, my curve is vertical and if I put $cpt, I have a "normal" curve... but I want to see dates corresponding with numbers..
Freindly,
Tanaes.
See the documentation:
You have to give flot timestamps, not already formated dates. For PHP use something like
$abscisse = strtotime($roww['SPP_DATE']) * 1000;

highcharts, json data: line and column

May be really basic question:
I'm playing with highcharts with two series, one represented with line and other with column, data is loaded using json, the problem is in how to tell highcharts one serie should be represented with line and the other with column type, like this
The problem (for me) comes when Series options in json mode of highcharts are only like this:
},
series: json
});
whilst in "normal mode" you can set for example:
series: [{
**type: 'column',**
name: 'Name',
data: [],
},{
type: 'spline',
name: 'Max Pax',
data: [],
draggableY: true,
dragMinY: 0,
dragMaxY: 200,
.......
Am I missing something?
php code that retrives data from db:
$con = mysql_connect("localhost", "*******","*******");
if (!$con) {
die('Could not connect: ' . mysql_error());
}
mysql_select_db("wordpress_8", $con);
$sth = mysql_query("SELECT * FROM wp_maxpax_A where fecha='12/11/2013' ");
$rows = array();
$rows['name'] = 'MaxPax';
while($r = mysql_fetch_array($sth)) {
$rows['data'][] = $r['a1300'];
$rows['data'][] = $r['a1315'];
$rows['data'][] = $r['a1330'];
$rows['data'][] = $r['a1345'];
}
$sth = mysql_query("SELECT overhead FROM projections_sample");
$rows1 = array();
$rows1['name'] = 'Overhead';
while($rr = mysql_fetch_assoc($sth)) {
$rows1['data'][] = $rr['overhead'];
}
$result = array();
array_push($result,$rows);
array_push($result,$rows1);
print json_encode($result, JSON_NUMERIC_CHECK);
Output looks like:
[{"name":"MaxPax","data":[40,19,40,21]},{"name":"Overhead","data": [21990,22365,21987,22369,22558,22987,23521,23003,22756,23112,22987,22897]}]
You need to define this parameter in JSON, or parse your json after receive, and set this paraemter, then use in Highcharts.
EDIT:
You can replace this lines
$sth = mysql_query("SELECT * FROM wp_maxpax_A where fecha='12/11/2013' ");
$rows = array();
$rows['name'] = 'MaxPax';
with
$sth = mysql_query("SELECT * FROM wp_maxpax_A where fecha='12/11/2013' ");
$rows = array();
$rows['name'] = 'MaxPax';
$rows['type'] = 'line';
Similar in next series.
Second solution is push type after getting json like:
$getJSON('path/to/json',function(data){
data[0].type='column';
data[1].type='line';
var options = {
// your options
series: data
};
$('#container').highcharts(options);
});

google chart api date format

The below answer suggested works using mysql_ however I have decided to switch to PDO for the increased security if offers. However When I apply the same code, I am struggling to get it to work.I had to switch the while to foreach for PDO.
UPDATE: Using PHP PDO
$sql = "SELECT * FROM userrecords";
$stmt = $conn->prepare($sql);
$stmt->execute();
$data = $stmt->fetchAll();
foreach ($data as $row)
{
$dateArray = explode('-', $row['eventdate']);
$year = $dateArray[0];
$month= $dateArray[1] - 1;
$day= $dateArray[2];
$dataArray[] = "[new Date ($year, $month, $day), {$row['scientificname']}, {$row['category_of_taxom']}]";
}
echo $dataArray;
Building on the solution from your other question, you have to parse your dates into javascript's Date object format:
$dataArray = array();
while($row = mysqli_fetch_array($result)) {
$dateArray = explode('-', $row['Date']);
$year = $dateArray[0];
$month = $dateArray[1] - 1; // subtract 1 since javascript months are zero-indexed
$day = $dateArray[2];
$dataArray[] = "[new Date($year, $month, $day), {$row['SpeciesA']}, {$row['Speciesb']}]";
}
Because the json_encode function will break the dates here, we have to parse it into the DataTable constructor a bit differently:
var data = new google.visualization.DataTable();
data.addColumn('date', 'Date');
data.addColumn('number', 'Species A');
data.addColumn('number', 'Species B');
data.addRows(<?php echo '[' . implode(',', $dataArray) . ']'; ?>);