Error Date type (Google visualization) - javascript

This is my code for displaying the chart
$scope.course_chart = function(response){
var data2 = new google.visualization.DataTable();
data2.addColumn('date', 'pv_date');
data2.addColumn('string', 'pageviews');
_.each(response.result.rows, function(item){
var formattedDate = item[0].slice(0, 4) + ", " + item[0].slice(4, 6) + ", " + item[0].slice(6, 8);
var date_format = new Date(formattedDate);
date_format = $filter('date')(date_format);
data2.addRow([
date_format,
item[1]
]);
});
var chart = new google.visualization.AreaChart(document.querySelector('#course_chart'));
chart.draw(data2, options2);
};
google.load('visualization', '1', {packages:['corechart'], callback: $scope.course_chart});
My date_format value is Sep 27, 2016
what is the requirement output for this data type "date" in google visualization?

if you have column with data type: 'date'
then you must pass a date object --> new Date()
you can use any of the javascript date contructors
such as...
new Date(2016, 8, 26)
remember in javascript, months are zero based (8 = Sept)
or...
new Date('09/26/2016')
this creates the date from a string and does not set the format when displayed
adding rows to the data table...
data2.addColumn('date', 'pv_date');
data2.addRow(new Date(2016, 8, 26));
if you already have the date formatted, you can use object notation when adding rows
(v = value, f = formatted value)...
data2.addRow({
v: new Date(2016, 8, 26)
f: 'Sep 26, 2016'
});
you can also use the DateFormat provided by google
data2.addRow(new Date(2016, 8, 26));
var formatDate = new google.visualization.DateFormat({
pattern: 'MMM d, yyyy'
});
formatDate.format(data2, 0);
finally, you can provide raw dates and let the axis format the dates
i.e. hAxis.format: 'MMM d, yyyy'...
here are a few examples using each scenario...
1. use hAxis.format
google.charts.load('current', {
callback: function () {
var data2 = new google.visualization.DataTable();
data2.addColumn('date', 'pv_date');
data2.addColumn('number', 'pageviews');
data2.addRows([
[new Date(2016, 8, 26), 100],
[new Date(2016, 8, 27), 101]
]);
var options = {
hAxis: {
format: 'MMM d, yyyy'
}
};
var chart = new google.visualization.AreaChart(document.getElementById('chart_div'));
chart.draw(data2, options);
},
packages:['corechart']
});
<script src="https://www.gstatic.com/charts/loader.js"></script>
<div id="chart_div"></div>
2. use DateFormat
google.charts.load('current', {
callback: function () {
var data2 = new google.visualization.DataTable();
data2.addColumn('date', 'pv_date');
data2.addColumn('number', 'pageviews');
data2.addRows([
[new Date(2016, 8, 26), 100],
[new Date(2016, 8, 27), 101]
]);
var formatDate = new google.visualization.DateFormat({
pattern: 'MMM d, yyyy'
});
formatDate.format(data2, 0);
var chart = new google.visualization.AreaChart(document.getElementById('chart_div'));
chart.draw(data2);
},
packages:['corechart']
});
<script src="https://www.gstatic.com/charts/loader.js"></script>
<div id="chart_div"></div>
3. use Object notation {v: , f:}
google.charts.load('current', {
callback: function () {
var data2 = new google.visualization.DataTable();
data2.addColumn('date', 'pv_date');
data2.addColumn('number', 'pageviews');
data2.addRows([
[{v: new Date(2016, 8, 26), f: 'Sep 26, 2016'}, 100],
[{v: new Date(2016, 8, 27), f: 'Sep 27, 2016'}, 101]
]);
var chart = new google.visualization.AreaChart(document.getElementById('chart_div'));
chart.draw(data2);
},
packages:['corechart']
});
<script src="https://www.gstatic.com/charts/loader.js"></script>
<div id="chart_div"></div>
also, for AreaChart, the columns after the first should be of type: 'number' -- not 'string'

Related

How to generate the current year, month and date using google chart api

I want to generate the Year, Month and Day inside the google chart API using the foreach method I'm getting the value for the chart. Please help me to solve this problem. I have attached my code as follows:
google.charts.load('current', {'packages':['corechart']});
google.charts.setOnLoadCallback(drawChart);
function drawChart() {
var data = new google.visualization.DataTable();
data.addColumn('date', 'Time of Day');
data.addColumn('number', 'Users');
data.addRows([
[new Date(2019, 2, 1), 5],[new Date(2019, 2, 2), 5],[new Date(2019, 2, 3), 5],[new Date(2019, 2, 4), 5],[new Date(2019, 2, 5), 5]
<?php
foreach($TotPosts as $totPos)
{
echo "[new Date(2019, 2, 1), ".$totPos->totUser."],";
}
?>
]);
var options = {
is3D:true,
title: 'Rate the Day on a Scale of 1 to 10',
width: 900,
height: 500,
hAxis: {
format: 'd/M/yy',
gridlines: {count: 15}
},
vAxis: {
gridlines: {color: 'none'},
minValue: 0
}
};
var chart = new google.visualization.LineChart(document.getElementById('chart_div'));
chart.draw(data, options);
var button = document.getElementById('change');
button.onclick = function () {
// If the format option matches, change it to the new option,
// if not, reset it to the original format.
options.hAxis.format === 'M/d/yy' ?
options.hAxis.format = 'MMM dd, yyyy' :
options.hAxis.format = 'M/d/yy';
chart.draw(data, options);
};
}
Here total user count is coming but I don't know how to generate the Year, Month and Dat here.

A way to set custom start and end time for Google Timeline Chart

Couldn't find answer in the official documentation.
By default, Google Timeline "shrinks" the chart area, so that first bar touches the left edge, and last bar touches the right:
|XXXXX-----YYYY---------|
|----ZZZ---YYYY----AAAAA|
Apr May Jun Jul
I want to override this behaviour and manually set start and end time for chart (override the scale), like this:
|------------XXXXX-----YYYY----------------|
|---------------ZZZ----YYYY-----AAAAA------|
Jan Feb Mar Apr May Jun Jul Aug
In my example, I want to show the chart from January till August.
listed in the Release Notes from October 2, 2015
use options hAxis.minValue & hAxis.maxValue
hAxis: {
minValue: new Date(2017, 0, 1),
maxValue: new Date(2017, 7, 1)
}
see following working snippet...
google.charts.load('current', {
callback: function () {
var container = document.getElementById('chart_div');
var chart = new google.visualization.Timeline(container);
var dataTable = new google.visualization.DataTable();
dataTable.addColumn({ type: 'string', id: 'Room' });
dataTable.addColumn({ type: 'string', id: 'Name' });
dataTable.addColumn({ type: 'date', id: 'Start' });
dataTable.addColumn({ type: 'date', id: 'End' });
dataTable.addRows([
[ '1', 'A', new Date(2017, 1, 1), new Date(2017, 1, 10) ],
[ '2', 'B', new Date(2017, 3, 1), new Date(2017, 3, 10) ],
[ '3', 'C', new Date(2017, 5, 1), new Date(2017, 5, 10) ],
]);
function drawChart() {
chart.draw(dataTable, {
hAxis: {
minValue: new Date(2017, 0, 1),
maxValue: new Date(2017, 7, 1)
}
});
}
$(window).resize(drawChart);
drawChart();
},
packages: ['timeline']
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<script src="https://www.gstatic.com/charts/loader.js"></script>
<div id="chart_div"></div>

Google visualization set column dock

I am struggling with google charts. I want bars to be displayed from bottom, rather than from top. Currently they are "hanging" like on the image below:
I don't see proper setting in docs, if it is there, please correct me. This is the code responsible for handling the display:
function parseInterval(value) {
var result = new Date(1,1,1);
result.setMilliseconds(value*1000);
return result;
}
(function($) {
$(document).ready(function(){
var loading = $('#loading');
$.getJSON("/api/v1/users", function(result) {
var dropdown = $("#user_id");
$.each(result, function(item) {
dropdown.append($("<option />").val(this.user_id).text(this.name));
});
dropdown.show();
loading.hide();
});
$('#user_id').change(function(){
var selected_user = $("#user_id").val();
var chart_div = $('#chart_div');
if(selected_user) {
loading.show();
chart_div.hide();
$.getJSON("/api/v1/mean_time_month/"+selected_user, function(result) {
$.each(result, function(index, value) {
value[1] = parseInterval(value[1]);
});
var data = new google.visualization.DataTable();
data.addColumn('string', 'Month');
data.addColumn('datetime', 'Mean time (h:m:s)');
data.addRows(result);
var options = {
hAxis: {
title: 'Month'
},
vAxis: {
title: 'Mean presence time',
minValue: new Date(1, 1, 1, 0, 0)
},
};
var formatter = new google.visualization.DateFormat({pattern: 'HH:mm:ss'});
formatter.format(data, 1);
chart_div.show();
loading.hide();
var chart = new google.visualization.ColumnChart(chart_div[0]);
chart.draw(data, options);
});
}
});
});
})(jQuery);
try using option vAxis.direction...
The direction in which the values along the vertical axis grow. Specify -1 to reverse the order of the values.
vAxis: {
direction: -1
}
see following working snippet...
google.charts.load('current', {
callback: drawChart,
packages:['corechart']
});
function drawChart() {
var data = new google.visualization.DataTable();
data.addColumn('string', 'Month');
data.addColumn('datetime', 'Mean time (h:m:s)');
data.addRows([
['Jan', new Date(1, 1, 1, 8, 16, 13)],
['Feb', new Date(1, 1, 1, 9, 24, 45)],
['Mar', new Date(1, 1, 1, 7, 36, 56)],
['Apr', new Date(1, 1, 1, 4, 20, 42)],
['May', new Date(1, 1, 1, 6, 51, 16)]
]);
var options = {
hAxis: {
title: 'Month'
},
vAxis: {
direction: -1,
title: 'Mean presence time',
minValue: new Date(1, 1, 1, 0, 0)
}
};
var formatter = new google.visualization.DateFormat({pattern: 'HH:mm:ss'});
formatter.format(data, 1);
var chart = new google.visualization.ColumnChart(document.getElementById('chart_div'));
chart.draw(data, options);
}
<script src="https://www.gstatic.com/charts/loader.js"></script>
<div id="chart_div"></div>
but i think the real problem lies within the data
notice the y-axis values the chart displays in the example above,
the order doesn't seem right, as well as the range (10am - 12am)
it appears you're only interested in the time values
as such, recommend using 'timeofday' vs. 'datetime'
(see --> working with timeofday)
The DataTable 'timeofday' column data type takes an array of either 3 or 4 numbers, representing hours, minutes, seconds, and optionally milliseconds, respectively. Using timeofday is different than using date and datetime in that the values are not specific to a date, whereas date and datetime always specify a date.
For example, the time 8:30am would be: [8, 30, 0, 0], with the 4th value being optional ([8, 30, 0] would output the same 'timeofday' value).
see following working snippet for example using 'timeofday'...
google.charts.load('current', {
callback: drawChart,
packages:['corechart']
});
function drawChart() {
var data = new google.visualization.DataTable();
data.addColumn('string', 'Month');
data.addColumn('timeofday', 'Mean time (h:m:s)');
data.addRows([
['Jan', [8, 16, 13]],
['Feb', [9, 24, 45]],
['Mar', [7, 36, 56]],
['Apr', [4, 20, 42]],
['May', [6, 51, 16]]
]);
var options = {
hAxis: {
title: 'Month'
},
vAxis: {
title: 'Mean presence time',
minValue: [0, 0, 0]
}
};
var formatter = new google.visualization.DateFormat({pattern: 'HH:mm:ss'});
formatter.format(data, 1);
var chart = new google.visualization.ColumnChart(document.getElementById('chart_div'));
chart.draw(data, options);
}
<script src="https://www.gstatic.com/charts/loader.js"></script>
<div id="chart_div"></div>

How to generate a Google graph from date time timestamps from a csv file

I have a CSV file with datetime timestamps (in milliseconds from 1970) as X axis separed tis a comma ',' and an associated Temperature value as Y axis.
ie :
1485097200000,22.5
1485098100000,23.8
1485099000000,24.2
etc ...
From that kind of CSV file i would like to generate a google graph code like this :
google.charts.load('current', {'packages':['corechart']});
google.charts.setOnLoadCallback(drawChart);
google.load('visualization', '1', {'packages':['annotatedtimeline']});
google.setOnLoadCallback(drawChart);
function drawChart() {
var data = new google.visualization.DataTable();
data.addColumn('datetime', 'Date');
data.addColumn('number', 'Temperatures');
data.addRows([
[new Date(1485097200000), 22.5],
[new Date(1485098100000), 23.8],
[new Date(1485099000000), 24.2]
]);
var options = {
title: 'Temperature measured every 15 minutes',
width: 900,
height: 500,
hAxis: {
gridlines: {count: 15}
},
vAxis: {
gridlines: {color: 'none'},
minValue: 0
}
};
var chart = new google.visualization.LineChart(document.getElementById('chart_div'));
chart.draw(data, options);
var button = document.getElementById('change');
button.onclick = function () {
// If the format option matches, change it to the new option,
// if not, reset it to the original format.
options.hAxis.format === 'M/d/yy' ?
options.hAxis.format = 'MMM dd, yyyy' :
options.hAxis.format = 'M/d/yy';
chart.draw(data, options);
};
}
<script type="text/javascript" src="https://www.gstatic.com/charts/loader.js"></script>
<button id="change">Click to change the format</button>
<div id="chart_div"></div>
Would you please tell if it is possible and how i could do it so , i'm newbie.
Regards,
Here is an example for how to get the get the data from a CSV file (in this case come from a string but the principal is the same.
The CSV file should look like this:
1486727700000,5\n1486728600000,7\n1486729200000,3\n1486729800000,1\n1486730400000,3\n1486731000000,4\n1486731600000,3\n1486732200000,4\n1486732800000,4
Also you need to extract the data from the file so here is the function.
function getData(csv) {
var output = [];
csv.split(/\n/).forEach(function(row) {
var cells = row.split(','),
date = new Date(parseInt(cells[0])),
value = parseFloat(cells[1]);
output.push([date, value]);
});
return output;
}
And live demo here:
google.charts.load('current', {'packages':['corechart']});
google.charts.setOnLoadCallback(drawChart);
// google.load('visualization', '1', {'packages':['annotatedtimeline']});
// google.setOnLoadCallback(drawChart);
function drawChart() {
var data = new google.visualization.DataTable();
data.addColumn('datetime', 'Date');
data.addColumn('number', 'Temperatures');
// data.addRows([
// [new Date(2017, 1, 10, 13, 55), 5], [new Date(2017, 1, 10, 14, 10), 7], [new Date(2017,1, 10,14,20), 3],
// [new Date(2017, 1, 10, 14, 30), 1], [new Date(2017, 1, 10, 14,40), 3], [new Date(2017, 1, 10, 14,50), 4],
// [new Date(2017, 1, 10,15,00), 3], [new Date(2017, 1, 10,15,10), 4], [new Date(2017, 1, 10,15,20), 2]
// ]);
data.addRows(getData(csvFile));
var options = {
title: 'Temperature measured every 15 minutes',
width: 900,
height: 500,
hAxis: {
gridlines: {count: 15}
},
vAxis: {
gridlines: {color: 'none'},
minValue: 0
}
};
var chart = new google.visualization.LineChart(document.getElementById('chart_div'));
chart.draw(data, options);
var button = document.getElementById('change');
button.onclick = function () {
// If the format option matches, change it to the new option,
// if not, reset it to the original format.
options.hAxis.format === 'M/d/yy' ? options.hAxis.format = 'MMM dd, yyyy' : options.hAxis.format = 'M/d/yy';
chart.draw(data, options);
};
}
var csvFile = '1486727700000,5\n1486728600000,7\n1486729200000,3\n1486729800000,1\n1486730400000,3\n1486731000000,4\n1486731600000,3\n1486732200000,4\n1486732800000,4';
function getData(csv) {
var output = [];
csv.split(/\n/).forEach(function(row) {
var cells = row.split(','),
date = new Date(parseInt(cells[0])),
value = parseFloat(cells[1]);
output.push([date, value]);
});
return output;
}
<script type="text/javascript" src="https://www.gstatic.com/charts/loader.js"></script>
<button id="change">Click to change the format</button>
<div id="chart_div"></div>
http://output.jsbin.com/coxemay
Update
How to get the CSV from file using ajax
google.charts.load('current', {'packages':['corechart']});
google.charts.setOnLoadCallback(drawChart);
function drawChart(csvData) {
var data = new google.visualization.DataTable();
data.addColumn('datetime', 'Date');
data.addColumn('number', 'Temperatures');
getData(function(csvData) {
data.addRows(csvData);
var options = {
title: 'Temperature measured every 15 minutes',
width: 900,
height: 500,
hAxis: {
gridlines: {count: 15}
},
vAxis: {
gridlines: {color: 'none'},
minValue: 0
}
};
var chart = new google.visualization.LineChart(document.getElementById('chart_div'));
chart.draw(data, options);
});
var button = document.getElementById('change');
button.onclick = function () {
// If the format option matches, change it to the new option,
// if not, reset it to the original format.
options.hAxis.format === 'M/d/yy' ? options.hAxis.format = 'MMM dd, yyyy' : options.hAxis.format = 'M/d/yy';
chart.draw(data, options);
};
}
function getData(callback) {
$.get('https://gist.githubusercontent.com/moshfeu/e3fd00cb57ae5b5cffbda44422dff112/raw/bcadcdfb5a532cc5711949a60cce639b2da235e6/csv-file', function(csv) {
var output = [];
csv.split(/\n/).forEach(function(row) {
var cells = row.split(','),
date = new Date(parseInt(cells[0])),
value = parseFloat(cells[1]);
output.push([date, value]);
});
callback(output);
});
}
<script type="text/javascript" src="https://www.gstatic.com/charts/loader.js"></script>
<script src="https://code.jquery.com/jquery-3.1.0.js"></script>
<button id="change">Click to change the format</button>
<div id="chart_div"></div>
http://jsbin.com/coxemay/3/edit?html,js,console

Google Charts range filter control for date format

I have a page that displays data using LineChart with a ChartRangeFilter control.
<script type="text/javascript" src="https://www.google.com/jsapi"></script>
<script type="text/javascript">
google.load('visualization', '1', {packages: ['controls', 'charteditor']});
google.setOnLoadCallback(drawChart);
function drawChart() {
var data = new google.visualization.DataTable();
data.addColumn('date', 'X');
data.addColumn('number', 'Y1');
data.addColumn('number', 'Y2');
for (var i = 0; i < 12; i++) {
data.addRow([new Date(2016, i,1), Math.floor(Math.random() * 200), Math.floor(Math.random() * 200)]);
}
var dash = new google.visualization.Dashboard(document.getElementById('dashboard'));
var control = new google.visualization.ControlWrapper({
controlType: 'ChartRangeFilter',
containerId: 'control_div',
options: {
filterColumnIndex: 0,
ui: {
chartOptions: {
height: 50,
width: 600,
chartArea: {
width: '80%'
}
},
chartView: {
columns: [0, 1]
}
}
}
});
var chart = new google.visualization.ChartWrapper({
chartType: 'LineChart',
containerId: 'chart_div'
});
function setOptions (wrapper) {
wrapper.setOption('width', 620);
wrapper.setOption('chartArea.width', '80%');
}
setOptions(chart);
dash.bind([control], [chart]);
dash.draw(data);
google.visualization.events.addListener(control, 'statechange', function () {
var v = control.getState();
document.getElementById('dbgchart').innerHTML = v.range.start+ ' to ' +v.range.end;
return 0;
});
}
</script>
<div id="dashboard">
<div id="chart_div"></div>
<div id="control_div"></div>
<p><span id='dbgchart'></span></p>
</div>
And here's a working JSFiddle.
Here the control starts from Jan 1. When I change start range to Jan 2, the graph date starts to show from Feb. I could not identify the reason for this. Can anyone help me in this? In the end range it is working fine it seems.
In this example, on 'statechange' -- the value for the begin and end months, for the selected chart range, are modified to ensure data points are plotted.
The chart is then redrawn with updated options.
google.charts.load('44', {
callback: drawChart,
packages: ['controls', 'corechart']
});
function drawChart() {
var data = new google.visualization.DataTable();
data.addColumn('date', 'X');
data.addColumn('number', 'Y1');
data.addColumn('number', 'Y2');
data.addRow([new Date(2016, 0, 1), 1,123]);
data.addRow([new Date(2016, 1, 1), 6,42 ]);
data.addRow([new Date(2016, 2, 1), 4,49 ]);
data.addRow([new Date(2016, 3, 1), 23,486 ]);
data.addRow([new Date(2016, 4, 1), 89,476 ]);
data.addRow([new Date(2016, 5, 1), 46,444 ]);
data.addRow([new Date(2016, 6, 1), 178,442 ]);
data.addRow([new Date(2016, 7, 1), 12,274 ]);
data.addRow([new Date(2016, 8, 1), 123,4934 ]);
data.addRow([new Date(2016, 9, 1), 144,4145 ]);
data.addRow([new Date(2016, 10, 1), 135,946 ]);
data.addRow([new Date(2016, 11, 1), 178,747 ]);
var control = new google.visualization.ControlWrapper({
controlType: 'ChartRangeFilter',
containerId: 'control_div',
options: {
filterColumnIndex: 0,
ui: {
chartOptions: {
height: 50,
width: 600,
chartArea: {
width: '80%'
}
}
}
}
});
var chart = new google.visualization.ChartWrapper({
chartType: 'LineChart',
containerId: 'chart_div',
options: {
width: 620,
chartArea: {
width: '80%'
},
hAxis: {
format: 'MMM',
slantedText: false,
maxAlternation: 1
}
}
});
function setOptions() {
var firstDate;
var lastDate;
var v = control.getState();
if (v.range) {
document.getElementById('dbgchart').innerHTML = v.range.start + ' to ' + v.range.end;
firstDate = new Date(v.range.start.getTime() + 1);
lastDate = new Date(v.range.end.getTime() - 1);
data.setValue(v.range.start.getMonth(), 0, firstDate);
data.setValue(v.range.end.getMonth(), 0, lastDate);
} else {
firstDate = data.getValue(0, 0);
lastDate = data.getValue(data.getNumberOfRows() - 1, 0);
}
var ticks = [];
for (var i = firstDate.getMonth(); i <= lastDate.getMonth(); i++) {
ticks.push(data.getValue(i, 0));
}
chart.setOption('hAxis.ticks', ticks);
chart.setOption('hAxis.viewWindow.min', firstDate);
chart.setOption('hAxis.viewWindow.max', lastDate);
if (dash) {
chart.draw();
}
}
setOptions();
google.visualization.events.addListener(control, 'statechange', setOptions);
var dash = new google.visualization.Dashboard(document.getElementById('dashboard'));
dash.bind([control], [chart]);
dash.draw(data);
}
<script src="https://www.gstatic.com/charts/loader.js"></script>
<div id="dashboard">
<div id="chart_div"></div>
<div id="control_div"></div>
<p><span id='dbgchart'></span></p>
</div>
It is because you only have one value for January (1st the jan) and when you set the start range to jan 2 the next value in your data if for Feb 1st.
The month value for month in the data object is zero-based.

Categories