Change datetime format on a Google Graph timeline - javascript

I have a Google Graph that shows Temperatures values / Epoch Datetime
I would like to toggle with a button the dates in X axis in 24h format like this : 'dd/MM/yyyy HH:mm' instead of current AM / PM format.
For some reasons, I can't get it working, dates stay in AM PM.
Can you tell me what is wrong ?
https://jsfiddle.net/lcoulon/ds7vgLvd/
google.charts.load('current', {
'packages': ['corechart']
});
google.charts.setOnLoadCallback(drawChart);
function drawChart() {
var data = new google.visualization.DataTable();
data.addColumn('datetime', 'Date');
data.addColumn('number', 'Temperatures');
data.addRows([
[new Date(1485320400000), 22.5],
[new Date(1485342000000), 23.8],
[new Date(1485360000000), 24.2],
[new Date(1485363600000), 21.0],
[new Date(1485410400000), 25.5],
[new Date(1485439200000), 23.0],
]);
var options = {
title: 'X Axis datetime epoch (ms) / Y Axis Temperature (°C)',
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 = 'dd/MM/yyyy HH:mm' :
options.hAxis.format = 'M/d/yy';
chart.draw(data, options);
};
}
<script 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>

It seems that according to the docs, the date and time format is set separately (go to the very bottom of the page):
hAxis: {
viewWindow: {
min: new Date(2014, 11, 31, 18),
max: new Date(2015, 0, 3, 1)
},
gridlines: {
count: -1,
units: {
days: {format: ['MMM dd']}, // <-----
hours: {format: ['HH:mm', 'ha']}, // <-----
}
},
minorGridlines: {
units: {
hours: {format: ['HH:mm', 'ha']}, // <-----
minutes: {format: ['HH:mm a Z', ':mm']} // <-----
}
}
}

Related

Google Chart columnChart haxis dates are wrong

I have a Google Chart (column-chart) showing a single dated (Jan-2010 = 2010-01-01) column - but the resulting column seems to run from 1-Jul-09 through to 1-Jul-10 (note this seems to change depending on the width of the screen); how can I fix this so that the column sits only on the 01-Jan-2010 date? (**Note, the dates/values are variable and can include one or hundreds of column values so we CANNOT simply hard code this or change the column type from 'date' to 'string').
var arr = eval("[[new Date(2010, 0, 1), 0,1]]");
var data = new google.visualization.DataTable();
data.addColumn('date', 'Dt');
data.addColumn('number', 'Open');
data.addColumn('number', 'Closed');
data.addRows(arr);
var options_stacked = {
isStacked: true,
height: 300,
colors: ['#111', '#a00'],
hAxis: {
slantedText: false,
format: 'd/MMM/yy',
},
legend: {
position: 'top',
},
vAxis: {
minValue: 0
}
};
var chart = new google.visualization.ColumnChart(document.getElementById('chart_div'));
chart.draw(data, options_stacked);
A demonstrator for this can be found on https://jsfiddle.net/Abeeee/d5fojtp2/34/
you can add custom ticks to ensure each column "sits" on the correct date.
the ticks option expects an array of values.
we can use DataTable method --> getDistinctValue(colIndex)
to return the date values from the data table.
var xTicks = data.getDistinctValues(0);
hAxis: {
slantedText: false,
format: 'd.MMM.yy', <---- changed from 'd/MMM/yy' to avoid line breaks
ticks: xTicks
},
see following working snippet...
function doTest() {
var arr = eval("[[new Date(2010, 0, 1), 0,1]]");
var data = new google.visualization.DataTable();
data.addColumn('date', 'Dt');
data.addColumn('number', 'Open');
data.addColumn('number', 'Closed');
data.addRows(arr);
var xTicks = data.getDistinctValues(0);
var options_stacked = {
isStacked: true,
height: 300,
colors: ['#111', '#a00'],
hAxis: {
slantedText: false,
format: 'd/MMM/yy',
ticks: xTicks
},
legend: {
position: 'top',
},
vAxis: {
minValue: 0
}
};
var chart = new google.visualization.ColumnChart(document.getElementById('chart_div'));
chart.draw(data, options_stacked);
}
window.addEventListener('resize', doTest);
google.charts.load('current', {
packages: ['corechart', 'bar']
});
google.charts.setOnLoadCallback(doTest);
<script type="text/javascript" src="https://www.gstatic.com/charts/loader.js"></script>
<h1>Google Charts</h1>
<div id="chart_div"></div>

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.

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 formatter not modifying tooltip

i am trying to create a line chart using google charts libraries.
The data contains, date (x axis), number (col 1), number (col 2), float (col 3).
I want to display two decimals on the 3rd column tooltip while keeping its y axis 0 to 100, this is my current code (running here https://jsfiddle.net/uqh56hsu/1/):
google.charts.load('current', {'packages':['line']});
google.charts.setOnLoadCallback(drawChart);
function drawChart() {
var data = new google.visualization.DataTable();
data.addColumn('datetime', 'Hours');
data.addColumn('number', 'col1');
data.addColumn('number', 'col2');
data.addColumn('number', 'percent');
data.addRows([
[new Date(1454950800*1000),0,0,0],[new Date(1454947200*1000),0,0,0],[new Date(1454943600*1000),2,0,0.00],[new Date(1454940000*1000),24,1,4.17],[new Date(1454936400*1000),12,1,8.33],[new Date(1454932800*1000),64,4,6.25],[new Date(1454929200*1000),176,11,6.25],[new Date(1454925600*1000),142,7,4.93],[new Date(1454922000*1000),114,7,6.14],[new Date(1454918400*1000),0,0,0],[new Date(1454914800*1000),0,0,0],[new Date(1454911200*1000),0,0,0],[new Date(1454907600*1000),0,0,0],[new Date(1454904000*1000),0,0,0],[new Date(1454900400*1000),0,0,0],[new Date(1454896800*1000),0,0,0],[new Date(1454893200*1000),0,0,0],[new Date(1454889600*1000),0,0,0],[new Date(1454886000*1000),0,0,0],[new Date(1454882400*1000),0,0,0],[new Date(1454878800*1000),0,0,0],[new Date(1454875200*1000),0,0,0],[new Date(1454871600*1000),180,10,5.56], ]);
var formatter = new google.visualization.NumberFormat({
fractionDigits: 2,
suffix: '%'
});
formatter.format(data, 3);
var options = {
width: 900,
height: 500,
backgroundColor: '#f1f1f1',
colors: ['#ff851b', '#03a9f4', '#8dc859'],
dateFormat: 'H',
vAxes:[
{ titleTextStyle: {color: '#FF0000'}},
{ titleTextStyle: {color: '#FF0000'}, minValue: 0, maxValue: 100, format: '#\'%\'', viewWindowMode : 'explicit', viewWindow:{
max:100,
min:0
}}
],
series:[
{targetAxisIndex:0},
{targetAxisIndex:0},
{targetAxisIndex:1}
]
};
var chart = new google.charts.Line(document.getElementById('linechart_material'));
chart.draw(data, google.charts.Line.convertOptions(options));
}
I've tried adding the formatter code earlier and later in the code, trying to apply it to other columns, etc, nothing seem to work. The 3rd column tooltip always gets the decimals removed.
What am I doing wrong?
The format is being set in the vAxes option, which was overriding the formatter...
Just set the format to --> format: '#,##0.00\'%\''
No need for a formatter here...
google.charts.load('current', {'packages':['line']});
google.charts.setOnLoadCallback(drawChart);
function drawChart() {
var data = new google.visualization.DataTable();
data.addColumn('datetime', 'Hours');
data.addColumn('number', 'col1');
data.addColumn('number', 'col2');
data.addColumn('number', 'percent');
data.addRows([
[new Date(1454950800*1000),0,0,0],
[new Date(1454947200*1000),0,0,0],
[new Date(1454943600*1000),2,0,0.00],
[new Date(1454940000*1000),24,1,4.17],
[new Date(1454936400*1000),12,1,8.33],
[new Date(1454932800*1000),64,4,6.25],
[new Date(1454929200*1000),176,11,6.25],
[new Date(1454925600*1000),142,7,4.93],
[new Date(1454922000*1000),114,7,6.14],
[new Date(1454918400*1000),0,0,0],
[new Date(1454914800*1000),0,0,0],
[new Date(1454911200*1000),0,0,0],
[new Date(1454907600*1000),0,0,0],
[new Date(1454904000*1000),0,0,0],
[new Date(1454900400*1000),0,0,0],
[new Date(1454896800*1000),0,0,0],
[new Date(1454893200*1000),0,0,0],
[new Date(1454889600*1000),0,0,0],
[new Date(1454886000*1000),0,0,0],
[new Date(1454882400*1000),0,0,0],
[new Date(1454878800*1000),0,0,0],
[new Date(1454875200*1000),0,0,0],
[new Date(1454871600*1000),180,10,5.56]
]);
var options = {
width: 900,
height: 500,
backgroundColor: '#f1f1f1',
colors: ['#ff851b', '#03a9f4', '#8dc859'],
dateFormat: 'H',
vAxes:[
{
titleTextStyle: {color: '#FF0000'}
},
{
titleTextStyle: {
color: '#FF0000'
},
minValue: 0,
maxValue: 100,
format: '#,##0.00\'%\'', // set format here -- formatter not needed
viewWindowMode : 'explicit',
viewWindow: {
max:100,
min:0
}
}
],
series:[
{targetAxisIndex:0},
{targetAxisIndex:0},
{targetAxisIndex:1}
]
};
var chart = new google.charts.Line(document.getElementById('linechart_material'));
chart.draw(data, google.charts.Line.convertOptions(options));
}
<script src="https://www.gstatic.com/charts/loader.js"></script>
<div id="linechart_material"></div>

Categories