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>
Related
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.
how can I highlight a single grid line? I would like to set an optical temperature limit at 35 ° C.
Thanks! I have now added it to my code, but it does not work .... do you see my mistake? Or did I not understand something in your explanation?
Here is the edited version :
//Google Chart
google.charts.load('current', {
callback: function drawChart(peanut) {
const div = document.createElement('div');
div.id = peanut.color + peanut.mac.split(':').join('');
$('#charts').appendChild(div);
peanut.data = new google.visualization.DataTable();
peanut.data.addColumn('datetime', 'Time');
peanut.data.addColumn('number', '🥜 ' + peanut.label);
for (var i = 0, len = localStorage.length; i < len; i++) {
let dateTime = new Date(parseInt(localStorage.key(i)));
let item = JSON.parse(localStorage.getItem(localStorage.key(i)));
if (item.peanutMac === peanut.mac) {
if (item.temperatureCelsius) {
let temperature = parseFloat(item.temperatureCelsius);
peanut.data.addRows([ [dateTime, temperature] ]);
} else if (item.alert) {
let data = parseInt(item.alert);
peanut.data.addRows([ [dateTime, data] ]);
}
}
}
if (peanut.type == 'thermo') {
peanut.chart = new google.visualization.LineChart($('#' + div.id));
peanut.chartOptions = {
interpolateNulls: true,
fontName: 'Roboto',
curveType: 'function',
colors: [peanut.rgbColor],
width: document.body.clientWidth,
height: (window.innerHeight - 224) / 2,
legend: 'none',
lineWidth: 3,
vAxis: {
format: '#.## °C',
ticks: [15.00, 20.00, 25.00, 30.00, 35.00, 40.00]
},
hAxis: {
gridlines: {
color: '#fff'
}
}
};
peanut.viewColumns = [];
$.each(new Array(data.getNumberOfColumns()), function (colIndex) {
peanut.viewColumns.push(colIndex);
});
peanut.viewColumns.push({
calc: function () {
return 35;
},
label: 'optical temperature limit',
type: 'number'
});
}
peanut.view = new google.visualiation.DataView(data);
peanut.view.setColumns(viewColumns);
if (peanut.data.getNumberOfRows()) {
peanut.chart.draw(peanut.view, peanut.chartOptions);
}
}
packages:['corechart', 'table']
});
add another series with the value set to 35 for all rows
here, a data view is used to add a calculated column for the optical temperature limit
google.charts.load('current', {
callback: function () {
var data = new google.visualization.DataTable();
data.addColumn('number', 'x');
data.addColumn('number', 'y0');
data.addColumn('number', 'y1');
data.addColumn('number', 'y2');
data.addRows([
[1, 32.8, 20.8, 21.8],
[2, 30.9, 29.5, 32.4],
[3, 25.4, 27, 25.7],
[4, 21.7, 28.8, 20.5],
[5, 21.9, 27.6, 20.4]
]);
var options = {
interpolateNulls: true,
fontName: 'Roboto',
curveType: 'function',
legend: 'none',
lineWidth: 3,
vAxis: {
format: '#.## °C',
ticks: [20.00, 25.00, 30.00, 35.00, 40.00]
},
hAxis: {
gridlines: {
color: '#fff'
}
}
};
var viewColumns = [];
$.each(new Array(data.getNumberOfColumns()), function (colIndex) {
viewColumns.push(colIndex);
});
viewColumns.push({
calc: function () {
return 35;
},
label: 'optical temperature limit',
type: 'number'
});
var view = new google.visualization.DataView(data);
view.setColumns(viewColumns);
var chart = new google.visualization.LineChart($('#chart').get(0));
chart.draw(view, options);
},
packages:['corechart', 'table']
});
<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>
Its not the best and safest way but I didnt find something on the google documentation:
You could use Jquery for it Ive tried it on the example from google docs and it works click
var line = $("svg g line")[4]
$(line).attr('stroke','red');
A simple way is to set the vAxis baseline to the value you want, say 35, and change the baselineColor. There is no option to change the width of this line, however, so if you need that, you should follow the suggestion above to add a series just to draw this line, and set its lineWidth.
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
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']} // <-----
}
}
}
I use Material column charts in my Web App.
and I have following out
and codes are below,
google.charts.load('current', {'packages':['bar']});
google.charts.setOnLoadCallback(drawChart);
function drawChart() {
var data = google.visualization.arrayToDataTable([
['Structure', 'Estimated', 'Actual'],
['hours', 6, 8],
['hours2', 20, 18],
]);
var options = {
chart: {
title: 'Structures by Hours',
subtitle: 'Estimated vs Actual',
}
};
var chart = new google.charts.Bar(document.getElementById('columnchart_hours'));
chart.draw(data, options);
What I want to do two things / need your hand, (on red circled area the image.)
to name the Y-Axis as Hours
and make the same axis scale 2 hours by 2 hours so that the Y-Axis / Hours Axis become 2, 4, 6, 8, 10 so on.
Thanks in advance,
Need to set configuration options for the vAxis.
vAxis: {
title: 'Hours',
ticks: [0, 2, 4, 6, 8, 10, 12, 14, 16, 18, 20]
}
Use title for the axis label.
Supply an array to ticks for the axis tick marks.
However, it doesn't appear ticks works for Material charts.
Note the options have to be converted as well...
google.charts.Bar.convertOptions
This example shows both a Core chart and a Material chart...
google.load('visualization', '1', {
packages: ['corechart', 'bar'],
callback: drawBarChart
});
function drawBarChart() {
var data = google.visualization.arrayToDataTable([
['Structure', 'Estimated', 'Actual'],
['hours', 6, 8],
['hours2', 20, 18],
]);
var options = {
chart: {
title: 'Structures by Hours',
subtitle: 'Estimated vs Actual',
},
vAxis: {
title: 'Hours',
ticks: [0, 2, 4, 6, 8, 10, 12, 14, 16, 18, 20]
}
};
var chart = new google.visualization.ColumnChart(document.getElementById('columnchart_hours'));
chart.draw(data, options);
var chart2 = new google.charts.Bar(document.getElementById('columnchart_hours2'));
chart2.draw(data, google.charts.Bar.convertOptions(options));
}
<script src="https://www.google.com/jsapi"></script>
<div id="columnchart_hours"></div>
<div id="columnchart_hours2"></div>