Displaying currency in Google chart API - php

I am using Google chart API to display a line chart, but I need the numbers to show as currency. On the chart itself, I have been able to get the numbers to display like currency, but when the mouse hovers over a point and the dialog box displays, the number is not displayed as specified.
<script type="text/javascript">
google.load("visualization", "1", {packages:["corechart"]});
google.setOnLoadCallback(drawChart);
function drawChart() {
var data = google.visualization.arrayToDataTable(<?php echo $data; ?>);
var options = {
chartArea:{left:40,top:10},
pointSize: 6,
vAxis: {format:'$###,###,###.00'}, // Money format
legend: {position:'none'}
};
var chart = new google.visualization.LineChart(document.getElementById('chart_div'));
chart.draw(data, options);
}
</script>
As you can see from this image, the vertical column displayed on the left does use decimal points as specified using vAxis.format in the above code, but the dialog box does not show the decimals or the dollar sign (I added the dollar sign after the screen capture).
How can I get the number in the dialog box to display the same as the numbers in the left aligned vertical column?
I tried updating the PHP array I am using to populate the data into currency format there, but then the Google chart does not render since it is not a plain digit.

This is perfect format to Brazilian currency:
var formatter = new google.visualization.NumberFormat({decimalSymbol: ',',groupingSymbol: '.', negativeColor: 'red', negativeParens: true, prefix: 'R$ '});
formatter.format(data, 1);
Works fine whit dollar also, just change R$ to $
10500.5 stay 10.500,50, more prefix
10500 stay 10.500,00, more prefix

There's a format for specifying both the raw value and formatted value for a cell: when loading the value into the chart, rather than, e.g. addRow(['2012-08-31, 4]); it would be addRow(['2012-08-31', {v: 4, f: '$4.00'}]); More examples of that syntax are sprinkled through the docs but I couldn't find a good place to link to it. It shouldn't be too hard to change the method by which the $data object from your example is generated to include that formatting, but there are other formatting options too.
If you'd rather define that formatting in the JS for whatever reason, you can use a NumberFormatter.

Try this:
var formatter = new google.visualization.NumberFormat({pattern:'###,###'} );
formatter.format(data, 1);
Worked great for me. Found at:
Comma Separated Data in Google Visualisation API

Another option that I found very useful, and similar in concept to the arrayToDataTable() method is the JavaScript literal initializer syntax as follows:
var data = new google.visualization.DataTable(
{
cols: [
{id: 'date', label: 'Date', type: 'string'},
{id: 'parnter1', label: 'Partner A', type: 'number'},
{id: 'partner2', label: 'Partner B', type: 'number'}
],
rows: [
{ c: [{ v: '06/2012' }, { v: 12345, f: '$12,345' }, { v: 98765, f: '$98,765'}] },
{ c: [{ v: '07/2012' }, { v: 10123, f: '$10,123' }, { v: 123123, f: '$123,123'}] }
]
}
);
https://google-developers.appspot.com/chart/interactive/docs/datatables_dataviews

Related

Load data from Google Analytics in a Chart.js chart

My question is: How do I load data from Google Analytics in a Chart.js chart?
I am writing a program with the Laravel framework (version 5.6) and use the Google Analytics API (not the Google Analytics Embed API)(version 3).
I get the data correctly presented in an array but I want to show it in a graph.
Subquestion: Do I need to replace the data in datasets with a connection to the Google Analytics API?
A simple chart from Chart.js:
<canvas id="userChart"></canvas>
<script>
var ctx = document.getElementById('userChart').getContext('2d');
var chart = new Chart(ctx, {
// The type of chart we want to create
type: 'line',
// The data for our dataset
data: {
labels: ["dag 1", "dag 8", "dag 15", "dag 22", "dag 30"],
datasets: [{
label: "users",
//backgroundColor: '#2f5ec4',
borderColor: '#2f5ec4',
data: [138, 163, 115, 124, 49],
}]
},
// Configuration options go here
options: {}
});
Update:
Example of how I get the Analytics data:
Route::get('/datatest', function()
{
$analyticsData =
Analytics::fetchTotalVisitorsAndPageViews(Period::days(30));
dd($analyticsData);
});
Example of the DD array:
It might be too late but for anyone who is in need, try the following. For your case you have your $analyticsData collection, which is a good start. Chartjs uses lists to map and compare data.
So for example we want to see a chart of date vs visitors
//transfer all of this code out of the routes to your controller
$analyticsData = Analytics::fetchTotalVisitorsAndPageViews(Period::days(30));
//send these two variables to your view
$dates = $analyticsData->pluck('date');
$visitors = $analyticsData->pluck('visitors');
In your script, the labels should receive $dates in a list as follows;
labels: {!! json_encode($dates) !!},
And data in datasets receive $visitors as a list;
data: {!! json_encode($visitors) !!}
See this article on my website for more in-depth explanations.

Unable to draw google Line Chart with Multiple columns with different data types

I am facing issues while implementing multi-line google chart. While plotting the line chart I am getting "All the series on given axis must be of the same data type".
Below is my Google line chart code snippet and I am fetching the values of frmyear, toyear and makes from database.(It is dynamic drop-down list).
function drawChart(frmyear, toyear, makes)
{
alert('hiii');
console.log(makes);
$_token = "{{ csrf_token() }}";
var jsondata = '';
$.ajax({
type: 'POST',
url: 'salesone',
data: {frmyear: frmyear, toyear: toyear, makes: makes, _token: $_token },
}).success(function(data) {
}).done(function(data){
jsondata = JSON.stringify(data);
console.log(jsondata);
drawgraph(jsondata);
})
.fail(function(data) {
alert( "error" );
});
}
function drawgraph(jsondata)
{
var data = new google.visualization.DataTable(jsondata);
var options = {
curveType: 'function',
legend: { position: 'bottom' }
};
var chart = new google.visualization.LineChart(document.getElementById('chart_div'));
chart.draw(data, {width: 200, height: 300});
chart.draw(data, options);
}
If user select two brands e.g. Mahindra & Hyundai for duration of Jan 2011 to June 2011 then my JSON data looks like below:
{"cols":[{"label":"Datetime","type":"date"},{"label":"Make","type":"string"},{"label":"Sales","type":"number"}],"rows":[{"c":[{"v":"Date(2011, 0, 31)"},{"v":"Hyundai"},{"v":28989}]},{"c":[{"v":"Date(2011, 1, 28)"},{"v":"Hyundai"},{"v":31405}]},{"c":[{"v":"Date(2011, 2, 31)"},{"v":"Hyundai"},{"v":30529}]},{"c":[{"v":"Date(2011, 3, 30)"},{"v":"Hyundai"},{"v":30522}]},{"c":[{"v":"Date(2011, 4, 31)"},{"v":"Hyundai"},{"v":30076}]},{"c":[{"v":"Date(2011, 5, 30)"},{"v":"Hyundai"},{"v":29461}]},{"c":[{"v":"Date(2011, 0, 31)"},{"v":"Mahindra"},{"v":16620}]},{"c":[{"v":"Date(2011, 1, 28)"},{"v":"Mahindra"},{"v":14523}]},{"c":[{"v":"Date(2011, 2, 31)"},{"v":"Mahindra"},{"v":16044}]},{"c":[{"v":"Date(2011, 3, 30)"},{"v":"Mahindra"},{"v":14709}]},{"c":[{"v":"Date(2011, 4, 31)"},{"v":"Mahindra"},{"v":15892}]},{"c":[{"v":"Date(2011, 5, 30)"},{"v":"Mahindra"},{"v":15286}]}]}
Here I have three columns Datetime, Make & Sales and all are of different data types hence I am unable to plot Line chart for Hyundai & Mahindra.
I want the data in below format:
Date Hyndai Mahindra
Date(2011, 1, 28) 31405 16620
Date(2011, 2, 31) 30529 14523
Date(2011, 3, 30) 30522 16044
In this case either I have to create data view or I need to modify the JSON. But in both approaches I will not be aware of how many brands selected by user.
My application is in Laravel 5.1 & MySQL as Database. what is the possible solution available to plot the line graph using google charts in this scenario?

Javascript, using Highcharts to display a chart of rankings with JSON Data

I am trying to use javascript Highcharts to display a chart of rankings from JSON data. I can't seem to get the chart to display.
This is the javascript code:
$(document).ready(function() {
var options = {
chart: {
renderTo: 'drawing',
zoomType: 'x',
width: 900,
height: 222
},
exporting: {
enabled:true
},
title: {
text: url+' - '+keyword
},
credits: {
text: '****',
href: 'http://***/'
},
xAxis: {
type: 'datetime',
dateTimeLabelFormats: {
day: '%b %e '
}
},
yAxis: [{
//min: 1,
allowDecimals: false,
reversed: true,
///: .2,
//maxPadding: .2,
title: {
text: 'Rankings'
}
},],
tooltip: {
crosshairs: true,
shared: true
},
series: [{}]
};
var url = "http://*******/chart.php";
$.getJSON(url, function(data) {
$.each(data, function(arrayID,group) {
$.each(group.data, function(id,val) {
arg = val[0].replace(/Date.UTC\((.*?)\)/, '$1').split(',');
var timestamp = Date.UTC.apply( null , arg );
date=new Date(timestamp);
data[arrayID].data[id][0] = timestamp;
});
});
options.series[0].data = data;
var chart = new Highcharts.Chart(options);
});
});
Our PHP Script gives us this JSON:
[{"name":"Google Rank","data":[["Date.UTC(2013,04,05)","23"],["Date.UTC(2013,04,04)","23"],["Date.UTC(2013,04,03)","22"],["Date.UTC(2013,04,02)","24"],["Date.UTC(2013,04,01)","26"],["Date.UTC(2013,03,31)","24"],["Date.UTC(2013,03,30)","24"],["Date.UTC(2013,03,29)","25"],["Date.UTC(2013,03,28)","25"],["Date.UTC(2013,03,27)","25"],["Date.UTC(2013,03,26)","26"],["Date.UTC(2013,03,25)","25"],["Date.UTC(2013,03,24)","24"],["Date.UTC(2013,03,23)","-"],["Date.UTC(2013,03,22)","10"],["Date.UTC(2013,03,21)","10"],["Date.UTC(2013,03,20)","10"],["Date.UTC(2013,03,19)","10"],["Date.UTC(2013,03,18)","10"],["Date.UTC(2013,03,17)","10"],["Date.UTC(2013,03,16)","9"],["Date.UTC(2013,03,15)","9"],["Date.UTC(2013,03,14)","9"],["Date.UTC(2013,03,13)","9"],["Date.UTC(2013,03,12)","9"]],"visible":"true","pointInterval":"86400000","showInLegend":"false"},{"name":"Bing Rank","data":["Date.UTC(2013,2,9)",9],"visible":"true","pointInterval":"86400000","showInLegend":"false"}]
Note the JSON data represents numbers as strings which could be a problem.
PHP Code which generates the JSON data:
$googledata = array();
while($gkdata = mysql_fetch_assoc($keywordquery)){
$explodedate = explode("-", $gkdata['date']);
$year = $explodedate[0];
$month = $explodedate[1];
$day = $explodedate[2];
$googledata[] = array(
"".$year.",".$month.",".$day."",
$gkdata['grank'] //$gkdata['grank'] should be a number, but is sometimes a dash so it's cast to an accommodating datatype: string.
);
}
$chartdata = array(
array(
"name" => 'Google Rank',
"data" => $googledata,
"visible" => 'true',
"pointInterval" => '86400000',
"showInLegend" => 'false',
),
array(
"name" => 'Bing Rank',
"data" => array(
'Date.UTC(2013,2,9)',
9
),
"visible" => 'true',
"pointInterval" => '86400000',
"showInLegend" => 'false',
)
);
The Highcharts won't display anything other than the chart itself with no data. The Date.UTC(2013,03,12) is supposed to go on the X-Axis & the number next to it is supposed to be the rank number. Can anyone see what is wrong?
The chart takes data as [x,y]. You just need to reverse the order of your data to ['value',datestamp'] if you want the date to be on the y axis.
Edit:
I am not sure from the text what the problem you are having is, but one problem that will arise from your code is that your number data values are being returned as strings, in quotes.
You will need to cast them as integers in your php before json encoding in order for them to come through unquoted, as integers.
You should be seeing an error from this: http://www.highcharts.com/errors/14
You are expecting $gkdata['grank'] to always return a number, it sometimes returns a dash -. The Array Object is using the datatype which best represents the data, and it chooses string. If you want to force it as int, you'll have to use a data structure that only allows integers to be put in it. Then it will puke when you try to put in a dash, which it should be doing, because how do you plot a DASH on a chart?
Had you taken off your blindfold, and looked at the error HighCharts returned to you, you would see this:
Highcharts Error #14 String value sent to series.data, expected Number
This happens if you pass in a string as a data point, for example in a setup like this:
series: [{
data: ["3", "5", "1", "6"]
}]
Highcharts expects the data values to be numbers. The most common reason for this is that data is parsed from CSV or from a XML source, and the implementer forgot to run parseFloat on the parsed value.
For performance reasons internal type casting is not performed, and only the first value is checked (since 2.3).
So fix your code to make grank always a number. HighCharts won't plot strings for performance reasons.

Javascript Pie Chart php to javascript object array

I am using the code at http://jsfiddle.net/MX7JC/9/ to build a pie chart.
But I want the data to come from php variables. How do I change :
var agg = { label: 'Aggressive', pct: [60, 10, 6, 30, 14, 10] },
as seen in the code on the link, so that pct consists of an array of php variables rather than fixed numbers. Such as :
var agg = { label: 'Aggressive', pct: [$r1, $r2, $r3, $r4, $r5, $r6]},
How do I alter the code to allows this? I tried json encode and I am having problems.
You can generate the Javascript when it's defined using PHP:
<script type="text/javascript">
var agg = { label: 'Aggressive', pct: [
<?php echo $r1.", ".$r2.", ".$r3.", ".$r4.", ".$r5.", ".$r6; ?>
]},
</script>

Highcharts/Highstocks jQuery - Scroll, Zoom and Margin issue

I'm working on displaying my stock data live in charts. I am using Highcharts for it. But I'm not getting proper output of it. See the image
Problems:
Margin:
As you can see the margin on the y axis is very high, because of which my ohlc data is showing very thin.
Some points are not getting highlighted on hovering over them:
When I try to hover on some points it does not show me that point's data. It sticks on the previous point's data.
Blue Area shade at the bottom:
As you can see the blue area at the bottom is not changing according to data in particular region.
Scroll issue:
When I try to move the scroll bar or try to increase its size, it gets stuck at the extreme right side. (So not able to move scroll since it gets stuck on the right side when I try to move it.)
Zoom Issue:
When I try to zoom in with zoom options I'm not able to zoom ro my data. For all zooms it remains same as "All" option
I have made some changes in this script: (Two panes, candlestick and volume) to receive my data.
I am retrieving all live data from PHP file using $.getJSON and doing all thing.
I can't create a fiddle of it because it's my live stock market data.
Here is the code :
$(function() {
$.getJSON('get_data.php?type=ohlc', function(data) {
// split the data set into ohlc and volume
var ohlc = [],
volume = [],
dataLength = data.length;
alert(data);
for (i = 0; i < dataLength; i++) {
ohlc.push([
data[i]['SQLDT'], // the date
parseFloat(data[i]['OPN']), // open
parseFloat(data[i]['HGH']), // high
parseFloat(data[i]['LWE']), // low
parseFloat(data[i]['CLS']) // close
]);
volume.push([
data[i]['SQLDT'], // the date
parseFloat(data[i]['VOL']) // the volume
])
}
// set the allowed units for data grouping
var groupingUnits = [[
'week', // unit name
[1] // allowed multiples
], [
'month',
[1, 2, 3, 4, 6]
]];
// create the chart
chart = new Highcharts.StockChart({
chart: {
renderTo: 'container',
alignTicks: false
},
rangeSelector: {
selected: 1
},
title: {
text: 'AAPL Historical'
},
xAxis:[ {
min: 10
},{
min: 10
}],
yAxis: [{
title: {
text: 'OHLC'
},
height: 200,
lineWidth: 2,
}, {
title: {
text: 'Volume'
},
top: 300,
height: 100,
offset: 0,
lineWidth: 2
}],
scrollbar: {
enabled: true
},
series: [{
type: 'candlestick',
name: 'AAPL',
data: ohlc,
dataGrouping: {
units: groupingUnits
}
}, {
type: 'column',
name: 'Volume',
data: volume,
yAxis: 1,
dataGrouping: {
units: groupingUnits
}
}]
});
});
});
Margin:
As you can see the margin on y axis is very high !! because of which my ohlc data is showing very thin.
Try adjusting the max to better utilize real estate
Some points not getting highlighted on hovering over them:
when i tried to hover on some points it does not show me that point's data. it sticks on the previous point's data.
Try disabling Stick Tracking
Blue Area shade at the bottom:
As you can see the blue area at the bottom is not changing according to data in particular region.
Make sure the navigator is pointing to the correct base series
Scroll issue:
When i try to move scroll bar or try to increase it's size, it gets stuck at extreme right side. (So not able to move scroll since it gets stick in right side when i try to move it.)
Zoom Issue:
When i try to zoom in with zoom options m not able to zoom ro my data. for all zooms it remains same as "All" option
These issues can come if something else is broken in your javascript. Check console for errors.
I can understand that you can't share your real code, but a jsFiddle reproduction of the issue may help. Use dummy values, or share the resultant json of the $.getJSON call

Categories