Dates on x-axis on Google Charts - javascript

I'm trying to make a google chart with prices on the y-axis and dates on the x-axis. I don't understand why my code is not working. It is not displaying anything.
In header:
<script type="text/javascript" src="https://www.gstatic.com/charts/loader.js"></script>
<script type="text/javascript">
google.charts.load('current', {'packages':['corechart']});
google.charts.setOnLoadCallback(drawChart);
function drawChart() {
var data = new google.visualization.DataTable();
data.addColumn('date', 'Dato');
data.addColumn('number', 'Anbefalet pris');
data.addColumn('number', 'Nuværende pris');
data.addRows([
[new Date (2016, 8, 6), 378, 418],
[new Date (2016, 8, 13), 66, 324],
[new Date (2016, 8, 20), 254, 257],
[new Date (2016, 8, 27), 117, 105],
[new Date (2016, 9, 3), 119, 66],
[new Date (2016, 9, 10), 88, 77],
[new Date (2016, 9, 17), 76, 96],
[new Date (2016, 9, 24), 123, 106],
[new Date (2016, 10, 1), 66, 148],
[new Date (2016, 10, 8), 128, 116]
]);
var options = {
chart: {
title: 'Anbefalede og nuværende ugepriser',
subtitle: 'Blå: Anbefalede priser, Rød: Nuværende priser'
},
legend: { position:'none' },
width: '100%',
pointSize: 10,
explorer: { actions: ['dragToZoom', 'rightClickToReset'] }
};
var chart = new google.charts.LineChart(document.getElementById('linechart_material'));
chart.draw(data, options);
}
</script>
In body:
<div id="linechart_material" class="chart"></div>
Any help will be much appreciated.

material charts use the namespace google.charts
core charts use the namespace google.visualization
so for core chart line chart -- google.visualization.LineChart
for material line chart -- google.charts.Line
see following snippet, which draws both...
for packages, use 'corechart' or 'line' for material
if using material, don't forget google.charts.Line.convertOptions
however, there are several options that won't work in material
recommend using corechart with option for theme: 'material'
google.charts.load('current', {
callback: function () {
var data = new google.visualization.DataTable();
data.addColumn('date', 'Dato');
data.addColumn('number', 'Anbefalet pris');
data.addColumn('number', 'Nuværende pris');
data.addRows([
[new Date (2016, 8, 6), 378, 418],
[new Date (2016, 8, 13), 66, 324],
[new Date (2016, 8, 20), 254, 257],
[new Date (2016, 8, 27), 117, 105],
[new Date (2016, 9, 3), 119, 66],
[new Date (2016, 9, 10), 88, 77],
[new Date (2016, 9, 17), 76, 96],
[new Date (2016, 9, 24), 123, 106],
[new Date (2016, 10, 1), 66, 148],
[new Date (2016, 10, 8), 128, 116]
]);
var tickMarks = [];
for (var i = 0; i < data.getNumberOfRows(); i++) {
tickMarks.push(data.getValue(i, 0));
}
var options = {
chart: {
title: 'Anbefalede og nuværende ugepriser',
subtitle: 'Blå: Anbefalede priser, Rød: Nuværende priser'
},
legend: { position:'none' },
width: '100%',
pointSize: 10,
explorer: { actions: ['dragToZoom', 'rightClickToReset'] },
hAxis: {
format: 'MM/dd/yyyy',
ticks: tickMarks
}
};
var chart = new google.charts.Line(document.getElementById('linechart_material'));
chart.draw(data, google.charts.Line.convertOptions(options));
chart = new google.visualization.LineChart(document.getElementById('linechart_core'));
chart.draw(data, options);
},
packages: ['corechart', 'line']
});
<script src="https://www.gstatic.com/charts/loader.js"></script>
<div>Material Chart</div>
<div id="linechart_material"></div>
<div>Core Chart</div>
<div id="linechart_core"></div>

Related

Line chart (google chart) custom labels

Well, I am using a LineChart with Angular 4 and I make sure to change labels according to window size like the following:
#HostListener('window:resize', ['$event']) onResize(event) {
if (event.target['innerWidth'] < 420) {
this.stockAnalysisService.getOptionsY()['hAxis']['format'] = 'MMM';
} else if (event.target['innerWidth'] < 760) {
this.stockAnalysisService.getOptionsY()['hAxis']['format'] = 'MM. yy\'';
} else { this.stockAnalysisService.getOptionsY()['hAxis']['format'] = 'MMM d, yyyy'; }
this.drawBasic();
}
This is just basic Angular syntax to detect resize or window and change the hAxis labels accordingly.
My question is, if I want a custom label where I present months on the labels and the months are presented with values of DAY OF THE MONTH and ONLY the first day of the month will have an addition of text to it like the following image:
RED: days of the month (jumps 5 days each time but not relevant)
BLACK: first indication of the month (Should not be NOV 10, but NOV 1, not relevant)
Any idea?
to have one or more labels different from than rest,
will need to use option --> hAxis.ticks
this means you will need to build an array of the labels that should be displayed
using object notation, for each tick you can provide
the value of the tick (v:)
and the formatted value of the tick (f:)
{v: dateValue, f: displayValue}
the value (v:) should be the same type as the x-axis, in this case --> 'date'
the formatted value (f:) should be --> 'string'
if you don't use object notation, and just provide a date for the tick,
the label will be displayed according to --> hAxis.format
so, for the dates that should have the month prefix,
use object notation, for the rest, just provide the date
see following working snippet for an example...
google.charts.load('current', {
packages: ['controls', 'corechart', 'table']
}).then(function () {
var data = new google.visualization.DataTable();
data.addColumn('date', 'x');
data.addColumn('number', 'y0');
data.addRows([
[new Date(2017, 7, 1), 2],
[new Date(2017, 7, 2), 3],
[new Date(2017, 7, 4), 1],
[new Date(2017, 7, 8), 5],
[new Date(2017, 7, 16), 6],
[new Date(2017, 7, 20), 7],
[new Date(2017, 7, 24), 1],
[new Date(2017, 7, 26), 2],
[new Date(2017, 7, 27), 3],
[new Date(2017, 8, 1), 2],
[new Date(2017, 8, 2), 3],
[new Date(2017, 8, 4), 9],
[new Date(2017, 8, 8), 5],
[new Date(2017, 8, 16), 6],
[new Date(2017, 8, 20), 7],
[new Date(2017, 8, 24), 1],
[new Date(2017, 8, 26), 2],
[new Date(2017, 8, 27), 3]
]);
var oneDay = (1000 * 60 * 60 * 24);
var dateRange = data.getColumnRange(0);
var formatMonth = new google.visualization.DateFormat({
pattern: 'MMM dd'
});
// build ticks
var ticksX = [];
for (var i = dateRange.min.getTime(); i <= dateRange.max.getTime(); i = i + oneDay) {
var rowDate = new Date(i);
if (rowDate.getDate() === 1) {
// add first day of month
ticksX.push({
v: rowDate,
f: formatMonth.formatValue(rowDate)
});
} else if (((i - dateRange.min.getTime()) % 7) === 0) {
// add date every seven days
ticksX.push(rowDate);
}
}
var container = document.getElementById('chart_div');
var chart = new google.visualization.LineChart(container);
chart.draw(data, {
chartArea: {
bottom: 36,
left: 48,
right: 12,
top: 12,
width: '100%',
height: '100%'
},
hAxis: {
format: 'dd',
ticks: ticksX
},
width: 800
});
});
<script src="https://www.gstatic.com/charts/loader.js"></script>
<div id="chart_div"></div>

Google Dashboard - chartRangeFilter , how to know when slider controls move, then stop

I can add an event handler to the ChartRangeFilter controlWrapper to find out when the sliders are moving:
google.visualization.events.addListener(control, 'statechange', selectHandler);
and I have a handler for it:
function selectHandler(e){
var state = control.getState();
console.log(state);
if (state != 'inProgress') {
currentLeftSliderPos = control.getState().range.start;
currentRightSliderPos = control.getState().range.end;
console.log(currentLeftSliderPos);
console.log(currentRightSliderPos);
}
}
It's not working and I know why. control.getstate()returns an object and is not really what I want. I know there is a way to check if the sliders are 'inProgress', but I can't figure out from what I have read on how to do that. Or do I check the 'ready' status? I don't want to reload graph data until the slider has stopped because I have a large dataset.
use the inProgress property on the argument sent to the event handler
it has the following properties...
{
"inProgress": false,
"startChanged": true,
"endChanged": false
}
see following working snippet...
google.charts.load('current', {
callback: drawDashboard,
packages: ['corechart', 'controls']
});
function drawDashboard() {
var data = new google.visualization.DataTable();
data.addColumn('date', 'x');
data.addColumn('number', 'y0');
data.addRows([
[new Date(2017, 6, 12), 9],
[new Date(2017, 6, 13), 8],
[new Date(2017, 6, 14), 10],
[new Date(2017, 6, 15), 8],
[new Date(2017, 6, 16), 22],
[new Date(2017, 6, 17), 25],
[new Date(2017, 6, 18), 24],
[new Date(2017, 6, 19), 14],
[new Date(2017, 6, 20), 12],
[new Date(2017, 6, 21), 8],
[new Date(2017, 6, 22), 9],
[new Date(2017, 6, 23), 4]
]);
var dashboard = new google.visualization.Dashboard(
document.getElementById('dashboard')
);
var chart = new google.visualization.ChartWrapper({
chartType: 'AreaChart',
containerId: 'chart'
});
var control = new google.visualization.ControlWrapper({
controlType: 'ChartRangeFilter',
containerId: 'control',
options: {
filterColumnIndex: 0
}
});
google.visualization.events.addListener(control, 'statechange', function (eventArgs) {
document.getElementById('info').innerHTML = 'control is moving = ' + eventArgs.inProgress;
});
dashboard.bind(control, chart);
dashboard.draw(data);
}
<script src="https://www.gstatic.com/charts/loader.js"></script>
<div id="dashboard">
<div id="chart"></div>
<div id="control"></div>
</div>
<div id="info"></div>

Add section to annotation chart?

I'm using Google Charts' Annotation Chart to display data. Everything's working but it's not showing the volume section, as seen in this google finance chart that, I believe, uses the same chart.
Here's what I have so far, but I don't know how to include that section:
google.charts.load('current', {'packages':['annotationchart']});
google.charts.setOnLoadCallback(drawChart);
function drawChart() {
var data = new google.visualization.DataTable();
data.addColumn('date', 'Date');
data.addColumn('number', 'Col1');
data.addColumn('string', 'Col2');
data.addColumn('string', 'Col3');
data.addColumn('number', 'Col4');
data.addColumn('string', 'Col5');
data.addColumn('string', 'Col6');
data.addRows([
[new Date(2017, 2, 15), 85, 'More', 'Even More',
91, undefined, undefined],
[new Date(2017, 2, 16), 93, 'Sales', 'First encounter',
99, undefined, undefined],
[new Date(2017, 2, 17), 75, 'Sales', 'Reached milestone',
96, 'Att', 'Good'],
[new Date(2017, 2, 18), 60, 'Sales', 'Low',
80, 'HR', 'Absences'],
[new Date(2017, 2, 19), 95, 'Sales', 'Goals',
85, 'HR', 'Vacation'],
[new Date(2017, 2, 20), 40, 'Sales', 'Training',
67, 'HR', 'PTO']
]);
var chart = new google.visualization.AnnotationChart(document.getElementById('chart_div'));
var options = {
displayAnnotations: true
};
chart.draw(data, options);
}
<script type="text/javascript" src="https://www.gstatic.com/charts/loader.js"></script>
<div id='chart_div' style='width: 900px; height: 500px;'></div>
This is what the google finance chart looks like, but I can't seem to include the volume section marked in red:
the annotation chart does not include an option for the middle chart / volume section
this could be added manually by drawing another, separate chart
however, the second chart cannot be placed in between the annotation chart and it's range filter
as such, you would need to turn off the annotation's range filter
and draw your own ChartRangeFilter
typically, custom filters are bound to charts using a dashboard
however, while building the example for this answer,
i noticed the annotation chart doesn't re-draw properly
after the filter has been applied, and then removed,
the annotation chart does not return to the original state
to correct, need to create the annotation chart every time it is drawn
see following working snippet,
a column chart is used for the volume section
the range filter is bound manually using the 'statechange' event
google.charts.load('current', {
callback: drawDashboard,
packages: ['annotationchart', 'controls', 'corechart']
});
function drawDashboard() {
var data = new google.visualization.DataTable();
data.addColumn('date', 'Date');
data.addColumn('number', 'Col1');
data.addColumn('string', 'Col2');
data.addColumn('string', 'Col3');
data.addColumn('number', 'Col4');
data.addColumn('string', 'Col5');
data.addColumn('string', 'Col6');
data.addRows([
[new Date(2017, 2, 15), 85, 'More', 'Even More',
91, undefined, undefined],
[new Date(2017, 2, 16), 93, 'Sales', 'First encounter',
99, undefined, undefined],
[new Date(2017, 2, 17), 75, 'Sales', 'Reached milestone',
96, 'Att', 'Good'],
[new Date(2017, 2, 18), 60, 'Sales', 'Low',
80, 'HR', 'Absences'],
[new Date(2017, 2, 19), 95, 'Sales', 'Goals',
85, 'HR', 'Vacation'],
[new Date(2017, 2, 20), 40, 'Sales', 'Training',
67, 'HR', 'PTO']
]);
var rangeFilter = new google.visualization.ControlWrapper({
controlType: 'ChartRangeFilter',
containerId: 'control_div',
dataTable: data,
options: {
filterColumnLabel: 'Date',
ui: {
chartOptions: {
height: 60,
width: '100%',
chartArea: {
width: '100%'
},
chartType: 'AreaChart'
}
}
},
view: {
columns: [0, 1, 4]
}
});
google.visualization.events.addListener(rangeFilter, 'ready', drawCharts);
google.visualization.events.addListener(rangeFilter, 'statechange', drawCharts);
rangeFilter.draw();
function drawCharts() {
var filterState = rangeFilter.getState();
var filterRows = data.getFilteredRows([{
column: 0,
minValue: filterState.range.start,
maxValue: filterState.range.end
}]);
var viewAnn = new google.visualization.DataView(data);
viewAnn.setRows(filterRows);
var chartAnn = new google.visualization.AnnotationChart(document.getElementById('chart_ann'));
var optionsAnn = {
displayAnnotations: false,
displayRangeSelector: false
};
chartAnn.draw(viewAnn, optionsAnn);
var viewCol = new google.visualization.DataView(data);
viewCol.setColumns([0, 1, 4]);
viewCol.setRows(filterRows);
var chartCol = new google.visualization.ColumnChart(document.getElementById('chart_col'));
var optionsCol = {
hAxis: {
textStyle: {
color: 'transparent'
}
},
height: 72,
legend: 'none',
theme: 'maximized',
vAxis: {
textStyle: {
color: 'transparent'
}
}
};
chartCol.draw(viewCol, optionsCol);
}
}
<script src="https://www.gstatic.com/charts/loader.js"></script>
<div id="chart_ann"></div>
<div id="chart_col"></div>
<div id="control_div"></div>

How to fill a Google chart with PHP from a TXT data file?

I have a DATAS.TXT file automatically filled-in with TIME and TEMPERATURE datas.
TIME is already formatted as per Google Charts requirements:
new Date(Year, Month, Day, Hours, Minutes)
TIME datas and TEMPERATURES datas are separated by a SPACE character and each line terminates with \r.
The DATAS.TXT file shows something like this:
new Date(2017, 01, 01, 05, 15) 20.5
new Date(2017, 01, 01, 18, 50) 21.7
new Date(2017, 01, 19, 12, 35) 22.4
etc ...
From this DATA file I would like to generate a Google Chart like this example:
<script type='text/javascript' src='http://www.google.com/jsapi'></script>
<script type='text/javascript'>
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(2001, 0, 1, 0), 0.0],
[new Date(2001, 0, 1, 1), 4.8],
[new Date(2001, 0, 1, 2), 4.6],
[new Date(2001, 0, 1, 3), 2.6],
[new Date(2001, 0, 1, 4), 3.6],
// ...
// Rest of year data here...
// ...
[new Date(2001, 11, 31, 20), 9.4],
[new Date(2001, 11, 31, 21), 7.0],
[new Date(2001, 11, 31, 22), 8.5],
[new Date(2001, 11, 31, 23), 2.2]
]);
var chart = new google.visualization.AnnotatedTimeLine(document.getElementById('chart_div'));
chart.draw(data, {displayAnnotations: true});
}
</script>
My question is, how can I fill-in data.addRows([ ... ] contents with the datas issued from my DATAS.TXT file?
I need a function that could pick-up TIMES, detect the space character insertion, pick-up the associated TEMPERATURE data and detect the \r character.
I'm not confortable with PHP, any help will be highly appreciated.

Google Line Chart - Year displaying as 2K

I'm trying to use google line chart and everything works great except all the year's at the x axis are displayed as 2K instead of e.g. 2015, 2016.
Here are my test page: http://bokhald.trubador.is/bokhald/testGraf.html
Here are my code:
<html>
<head>
<script src='http://cdnjs.cloudflare.com/ajax/libs/jquery/2.1.3/jquery.min.js'></script>
<script type="text/javascript" src="https://www.gstatic.com/charts/loader.js"></script>
<script type="text/javascript">
google.charts.load('current', {'packages':['line']});
google.charts.setOnLoadCallback(drawChart);
function drawChart() {
var data = new google.visualization.DataTable();
data.addColumn('number', 'Year');
data.addColumn('number', 'Altogether');
data.addColumn('number', 'Product 1');
data.addColumn('number', 'Product 2');
data.addRows([
[2009, 21, 13, 8], [2010, 32, 17, 15],
[2011, 48, 38, 10], [2012, 53, 34, 19],
[2013, 59, 44, 15], [2014, 56, 46, 10],
[2015, 56, 48, 8], [2016, 6, 5, 1]
]);
var options = {
height: 500,
axes: {
}
};
var chart = new google.charts.Line(document.getElementById('my_chart'));
chart.draw(data, options);
}
$(window).resize(function(){
drawChart();
});
</script>
</head>
<body>
<div id="my_chart"></div>
</body>
</html>
Change the date in the addColum to date and make the dates new javascript date objects, set format to yyyy for the x colons
google.charts.load('current', {'packages':['line']});
google.charts.setOnLoadCallback(drawChart);
function drawChart() {
var data = new google.visualization.DataTable();
data.addColumn('date', 'Year');
data.addColumn('number', 'Altogether');
data.addColumn('number', 'Product 1');
data.addColumn('number', 'Product 2');
data.addRows([
[new Date(2009,1,1), 21, 13, 8], [new Date(2010,1,1), 32, 17, 15],
[new Date(2011,1,1), 48, 38, 10], [new Date(2012,1,1), 53, 34, 19],
[new Date(2013,1,1), 59, 44, 15], [new Date(2014,1,1), 56, 46, 10],
[new Date(2015,1,1), 56, 48, 8], [new Date(2016,1,1), 6, 5, 1]
]);
var options = {
width: 1000,
height:500,
hAxis: {
format: 'yyyy',
gridlines: {count: 15}
},
axes: {
}
};
var chart = new google.charts.Line(document.getElementById('my_chart'));
chart.draw(data, options);
}
$(window).resize(function(){
drawChart();
});
https://developers.google.com/chart/interactive/docs/datesandtimes
https://jsfiddle.net/rzqa598j/2/

Categories

Resources