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.
Related
I want to plot the synchronized charts like this https://www.highcharts.com/demo/synchronized-charts.
The JSON data will come from SQL database and the xData (x-axis) looks like below which are in year-month format:
xData: [
"2004-04","2004-04","2004-04","2004-04","2004-04","2004-04","2004-04",
"2004-04","2004-04","2004-04","2004-04","2012-08","2004-04","2004-04","2004-04",
"2004-04","2004-04","2004-04","2004-04","2004-04","2004-04","2004-04","2004-04",
"2004-04","2004-04","2004-04","2004-04","2004-04","2013-12","2004-04","2004-04",
"2007-11","2007-11","2012-08","2005-05","2004-04","2004-04","2004-04","2004-04",
"2004-04","2004-04","2004-04","2016-04","2004-04","2012-08","2004-04","2004-04",
"2004-04","2004-04","2004-04","2004-04","2004-04","2005-05","2004-04","2004-04",
"2012-08","2016-04","2004-04","2004-04","2004-04","2004-04","2012-08","2004-04",
"2004-04","2004-04","2004-04","2012-08","2004-04","2004-04","2004-04","2004-04",
"2004-04","2006-02","2007-11","2004-04","2004-04","2004-04","2005-05","2004-04",
"2004-04","2005-05","2004-04","2004-04","2012-08","2012-08","2006-02","2005-05",
"2004-04","2016-04","2004-04","2004-04","2004-04","2006-02","2004-04","2004-04",
"2004-04","2004-04","2004-04","2005-05","2007-11"
]
So, how to plot those data as x-axis for synchronized charts?
you could simply use that one array as the labels for the xAxis:
xAxis: {
labels: {
format: '{value}'
}
},
but in order to plot on a timeline axis, you may need to convert these strings into integer values, which can be done with PHP: strtotime($date.'-01 00:00:00') ...hint: you need to multiply the result (in seconds) with 1000 for JavaScript timestamps (in milliseconds).
I added categories: "activity.xData" to to the chart
and set the labels format to "this.value"
xAxis: {
crosshair: true,
categories: activity.xData,
events: {
setExtremes: syncExtremes
},
labels: {
format: this.value
}
},
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?
I have this simple code:
var store = {
"(name)": "My Object",
"Created": Ext.Date.parse('10/15/2006', 'm/d/Y'),
"Available": false,
"Version": 0.01,
"Description": "A test object"
}
Ext.create('Ext.grid.property.Grid', {
title: 'Properties Grid',
width: 300,
renderTo: Ext.getBody(),
source: store,
dockedItems: [{
xtype: 'toolbar',
dock: 'bottom',
ui: 'footer',
items: ['->', {
//iconCls: 'icon-save',
text: 'Sync',
scope: this,
// handler: this.onSync
}]
}]
});
The panel looks like this:
My app uses similar grid, the only difference is that the store variable is created dynamically (but has similar structure) and I also have a sync button that should save any changes to the grid's value field.
As of now, value field can be edited but not saved anywhere of course. I have been trying to add an event on sync button click, that would get all the rows from value and update the database.
Can anyone tell me step-by-step what to add in property.Grid's code, so that when I click sync
it would send all the values via AJAX to my php file, that would do the sync with database?
Thanks
Something like this should do the trick:
{
text: 'Sync',
handler: function() {
// get values
var gridvalues = this.up( 'propertygrid' ).getSource();
// send AJAX request
Ext.Ajax.request({
url: 'somephpurl...',
params: gridvalues
});
}
}
The docs, BTW, for these are as follows:
Get property grid values: http://docs.sencha.com/extjs/4.2.1/#!/api/Ext.grid.property.Grid-method-getSource
Create AJAX request: http://docs.sencha.com/extjs/4.2.1/#!/api/Ext.Ajax-method-request
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
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