How to use Time in Google Charts? - charts

I'm using Google Charts. Here's an example data from Google's website:
var data = new google.visualization.DataTable(
{
cols: [{id: 'task', label: 'Employee Name', type: 'string'},
{id: 'startDate', label: 'Start Date', type: 'date'}],
rows: [{c:[{v: 'Mike'}, {v: new Date(2008, 1, 28), f:'February 28, 2008'}]},
{c:[{v: 'Bob'}, {v: new Date(2007, 5, 1)}]},
{c:[{v: 'Alice'}, {v: new Date(2006, 7, 16)}]},
{c:[{v: 'Frank'}, {v: new Date(2007, 11, 28)}]},
{c:[{v: 'Floyd'}, {v: new Date(2005, 3, 13)}]},
{c:[{v: 'Fritz'}, {v: new Date(2011, 6, 1)}]}
]
}
)
I'd like to use hours and minutes also in the date variables. I haven't found an example syntax on the website, has anyone tried this before? Thanks in advance.

The Mozilla Developer Network has an extensive JavaScript reference, including on the Date object. See the following constructor syntax:
new Date()
new Date(milliseconds)
new Date(dateString)
new Date(year, month, day [, hour, minute, second, millisecond ])
So for 2011-06-01 at 1:37 PM, you could do:
new Date(2011, 5, 1, 13, 37)
Please note that months are zero-based, so the 5 above represents the 6th month (i.e. June).
N.B. I have very little familiarity with Google Charts, so I would accept edits to make this question more relevant to the O.P.'s question.

Related

Google Chart Calendar - change value in gradient scale to string

I am using Google Chart Calendar and I would like to modify the gradient values - min and max. From the official documentation I can do it by modifying colorAxis:
{minValue: 0, maxValue: 5, colors: ['#FF0000', '#00FF00']}
But it supports only type number and I would prefer to indicate it by using string, something like "Lowest value" for minValue and "Highest value" for maxValue.
Any suggestions how can I do it?
in order to calculate the gradient on the 'Activity' column,
options for minValue and maxValue can only be numbers...
but if you just want to change the label that is displayed on the legend,
that can be done manually on the chart's 'ready' event
see following working snippet...
google.charts.load('current', {
packages: ['calendar']
}).then(function () {
var dataTable = new google.visualization.DataTable();
dataTable.addColumn({type: 'date', id: 'Date'});
dataTable.addColumn({type: 'number', id: 'Activity'});
dataTable.addRows([
[new Date(2018, 0, 3), 1],
[new Date(2018, 0, 16), 2],
[new Date(2018, 1, 6), 3],
[new Date(2018, 1, 15), 4],
[new Date(2018, 1, 25), 5]
]);
var chart = new google.visualization.Calendar(document.getElementById('chart_div'));
var options = {
colorAxis: {minValue: 0, maxValue: 5, colors: ['#FF0000', '#00FF00']},
width: 1000
};
google.visualization.events.addListener(chart, 'ready', function () {
if ($('#chart_div text').length > 1) {
$($('#chart_div text').get(0)).text('Lowest');
$($('#chart_div text').get(1)).text('Highest');
}
});
chart.draw(dataTable, options);
});
<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>

Passing JSON String to Google Charts in Play Framework controller to Scala view is not recognized nor do the charts display

I have a controller in Play that passes a string in JSON format to a Scala view:
public Result reportsPieChart() {
String jsonString = "{cols: [{id: 'task', label: 'Task', type: 'string'}, {id: 'hours', label: 'Hours per Day', type: 'number'}],rows: [{c:[{v: 'Work'}, {v: 11}]}, {c:[{v: 'Eat'}, {v: 2}]}, {c:[{v: 'Commute'}, {v: 2}]}, {c:[{v: 'Watch TV'}, {v:2}]}, {c:[{v: 'Sleep'}, {v:7, f:'7.000'}]}]}";
return ok(piechart.render(jsonString));
}
In the view, I am using this variable in the Javascript to display the Google Chart:
#(jsonString: String)
#main(null) {
<script type="text/javascript" src="https://www.gstatic.com/charts/loader.js"></script>
<script type="text/javascript" src="//ajax.googleapis.com/ajax/libs/jquery/1.10.2/jquery.min.js"></script>
<script type="text/javascript">
google.charts.load('current', {
packages : [ 'corechart' ]
});
google.charts.setOnLoadCallback(drawChart);
function drawChart() {
var jsonString = "#jsonString";
var newJSON = jsonString.replace(/'/g, "'");
console.log("newJSON: " + newJSON);
// Define the chart to be drawn.
var data = new google.visualization.DataTable(newJSON);
// Instantiate and draw the chart.
var chart = new google.visualization.PieChart(document.getElementById('myPieChart'));
chart.draw(data, null);
}
</script>
<section id="displayResults" style="padding: 30px;">
<!-- Identify where the chart should be drawn. -->
<div id="myPieChart"/>
</section>
}
WHen passing the newJSON variable to the DataTable, it seems not to recognize it -- no errors, nothing to the console -- and does not display any charts.
The newJSON variable prints out to console in the correct format:
newJSON: {cols: [{id: 'task', label: 'Task', type: 'string'}, {id: 'hours', label: 'Hours per Day', type: 'number'}],rows: [{c:[{v: 'Work'}, {v: 11}]}, {c:[{v: 'Eat'}, {v: 2}]}, {c:[{v: 'Commute'}, {v: 2}]}, {c:[{v: 'Watch TV'}, {v:2}]}, {c:[{v: 'Sleep'}, {v:7, f:'7.000'}]}]}
I am following the instructions from Google:
https://developers.google.com/chart/interactive/docs/reference#datatable-class
In the example, I copied that JSON into my string.
Is there something I missing within Scala in a view to get this variable to work? According to Google, you can pass a literal string to the DataTable.
I appreciate the help!
Based on a little trial and error, the solution is to wrap both name and values in double quotes.
My JSON String looks like this:
String jsonString = "{'cols': [{'id': 'task', 'label': 'Task', 'type': 'string'}, {'id': 'hours', 'label': 'Hours per Day', 'type': 'number'}],'rows': [{'c':[{'v': 'Work'}, {'v': 11}]}, {'c':[{'v': 'Eat'}, {'v': 2}]}, {'c':[{'v': 'Commute'}, {'v': 2}]}, {'c':[{'v': 'Watch TV'}, {'v':2}]}, {'c':[{'v': 'Sleep'}, {'v':7, 'f':'7.000'}]}]}";
and I changed the Javascript to:
var newJSON = jsonString.replace(/'/g, '"');
Works like a charm...

Google chart table formatting cell as percentage

I am trying to format a cell in a google chart table as a percentage field.
For a column it works with :
var flow_format2 = new google.visualization.NumberFormat( {suffix: '%', negativeColor: 'red', negativeParens: true, fractionDigits: 0} );
But as far as I can read there is no possibility for a row, therefore I would like to do it on cell level - is that possible?
Is it with setProperty I need to do it and what is the formatting syntax.
you can use the formatValue method of NumberFormat to get the formatted string
rather than applying to the entire column
then you can manually setFormattedValue on the DataTable cell
to change the color, use setProperty to change the cell's 'style' property
the chart must be drawn afterwards
--or--
when the chart's 'ready' event fires, you can change the cell value using the DOM
the Table chart produces a normal set of html <table> tags
following is a working snippet, demonstrating both approaches...
google.charts.load('current', {
callback: function () {
var dataTable = new google.visualization.DataTable({
cols: [
{label: 'Name', type: 'string'},
{label: 'Amount', type: 'number'},
],
rows: [
{c:[{v: 'Adam'}, {v: -1201}]},
{c:[{v: 'Mike'}, {v: 2235}]},
{c:[{v: 'Stephen'}, {v: -5222}]},
{c:[{v: 'Victor'}, {v: 1288}]},
{c:[{v: 'Wes'}, {v: -6753}]}
]
});
var container = document.getElementById('chart_div');
var tableChart = new google.visualization.Table(container);
var patternFormat = {
suffix: '%',
negativeColor: '#FF0000',
negativeParens: true,
fractionDigits: 0
};
// create the formatter
var formatter = new google.visualization.NumberFormat(patternFormat);
// format cell - first row
dataTable.setFormattedValue(0, 1, formatter.formatValue(dataTable.getValue(0, 1)));
if (dataTable.getValue(0, 1) < 0) {
dataTable.setProperty(0, 1, 'style', 'color: ' + patternFormat.negativeColor + ';');
}
google.visualization.events.addOneTimeListener(tableChart, 'ready', function () {
// format cell via DOM - third row
var tableCell = container.getElementsByTagName('TR')[3].cells[1];
tableCell.innerHTML = formatter.formatValue(dataTable.getValue(2, 1));
if (dataTable.getValue(2, 1) < 0) {
tableCell.style.color = patternFormat.negativeColor;
}
});
tableChart.draw(dataTable, {
allowHtml: true
});
},
packages: ['table']
});
<script src="https://www.gstatic.com/charts/loader.js"></script>
<div id="chart_div"></div>

Draw Google Line Chart with multiple missing values

I copied this code from Google Line Chart reference and made some small changes:
function drawChart() {
var data = new google.visualization.DataTable();
data.addColumn('number', 'Dag');
data.addColumn('number', 'Målvikt');
data.addColumn('number', 'Uppmätt vikt');
data.addRows([
[1, 37.8, 55.0],
[2, null, 69.5],
[3, null, 57],
[4, null, 18.8],
[5, null, 17.6],
[6, null, 13.6],
[7, null, 12.3],
[8, null, 29.2],
[9, null, 42.9],
[10, null, 30.9],
[11, null, 7.9],
[12, null, 8.4],
[13, null, 6.3],
[14, 30.8, 6.2]
]);
var options = {
chart: {
title: 'Box Office Earnings in First Two Weeks of Opening',
subtitle: 'in millions of dollars (USD)',
interpolateNulls: true
},
width: 900,
height: 500
};
var chart = new google.charts.Line(document.getElementById('linechart_material'));
chart.draw(data, options);
}
My first line is not generated at all.
As you see, I want to just give the first and last value for the curve named "Målvikt" and draw a straight line between them. I found this related question and added interpolateNulls: true but actually it did not solve my problem.
I then changed all nulls except one to some value, but there still was no line between its neighbors. What am I doing wrong?
It seems that google.charts.Line component does not support interpolateNulls option.
Secondly, there is typo in specifying interpolateNulls option.
Since interpolateNulls property does not belong to chart property according to Configuration Options, the line:
var options = {
chart: {
interpolateNulls: true
}
};
should be replaced with:
var options = {
interpolateNulls: true
};
Having said that, i would recommend to utilize google.visualization.LineChart from corechart package instead of google.charts.Line component from line package. In that case interpolateNulls option could applied as demonstrated below:
Working example
google.load('visualization', '1.1', { packages: ['corechart'] });
google.setOnLoadCallback(drawChart);
function drawChart() {
var data = new google.visualization.DataTable();
data.addColumn('number', 'Dag');
data.addColumn('number', 'Målvikt');
data.addColumn('number', 'Uppmätt vikt');
data.addRows([
[1, 37.8, 55.0],
[2, null, 69.5],
[3, null, 57],
[4, null, 18.8],
[5, null, 17.6],
[6, null, 13.6],
[7, null, 12.3],
[8, null, 29.2],
[9, null, 42.9],
[10, null, 30.9],
[11, null, 7.9],
[12, null, 8.4],
[13, null, 6.3],
[14, 30.8, 6.2]
]);
var options = {
title: 'Box Office Earnings in First Two Weeks of Opening',
subtitle: 'in millions of dollars (USD)',
interpolateNulls: true,
width: 900,
height: 500
};
//var chart = new google.charts.Line(document.getElementById('linechart_material'));
var chart = new google.visualization.LineChart(document.getElementById('linechart_material'));
chart.draw(data, options);
}
<script type="text/javascript" src="https://www.google.com/jsapi"></script>
<div id="linechart_material" style="width: 640px; height: 480px"></div>

how to get x-axis line and value of the google bar chart to the top of the chart

Im using google chart for my application. I need a chart like
Expected
and i used this code to get the expected chart.
google.load("visualization", "1", {packages: ["corechart"]});
function drawVisualization() {
// Create and populate the data table.
var data = google.visualization.arrayToDataTable([
['numbers', 'Austria', 'Bulgaria'],
[2003, 1336060, 400361],
[2004, 1538156, 366849],
[2005, 1576579, 440514],
[2006, 1600652, 434552],
[2007, 1968113, 393032],
[2008, 1901067, 517206]
]);
var hAxisTick = [{v: '2003', f: "3-4"}, {v: '2004', f: "5-9"}, {v: '2005', f: "9-13"}, {v: '2006', f: "13-14"}, {v: '2007', f: "14-24"}, {v: '2008', f: "24-84"}];
var vAxisTick = [0, 1968113];
// Create and draw the visualization.
new google.visualization.BarChart(document.getElementById('chart_div')).
draw(data,
{width: 600, height: 250,
colors: ['706C6B', 'D6D3D3'],
legend: {position: 'none'},
vAxis: {ticks: hAxisTick, gridlines: {color: 'FFFFFF'}},
hAxis: {gridlines: {color: 'FFFFFF'}, ticks: vAxisTick, baselineColor: '#FFFFFF'},
enableInteractivity: false}
);
}
google.setOnLoadCallback(drawVisualization);
but,
Actual
how to get the x-axis line to the top and also i need to show the tick mark for the given points.