Google Bar chart take full width - javascript

I have a google chart that I need to take the full width of the chart area, how can I do it? As you can see in the picture above it doesn't´t take neither the full width or hight.
My option right now are:
var options = {
title: 'Baterry Packs Voltages',
legend: { position: 'none' },
hAxis: { title: 'Pack', viewWindow: { min: 0, max: 13 }, gridlines: { count: 0 }, ticks: [ 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12 ] },
vAxis: { title: 'Pack Voltage [V]', viewWindow: { min: 0, max: 5 }, gridlines: { count: 10 }, ticks: [0, 1, 2, 3, 4, 5] },
chartArea: { left: '8%', top: '8%', width: "70%", height: "70%" },
height: 450,
width: 700
};

here are a couple options...
1)
use option --> theme: 'maximized'
this will expand the chart area to the edges of the container
and place all labels, including titles, inside the chart area
see following working snippet...
google.charts.load('current', {
callback: function () {
drawChart();
$(window).on('resize', drawChart);
},
packages:['corechart']
});
function drawChart() {
var formatDate = new google.visualization.DateFormat({
pattern: 'dd/MM'
});
var oneDay = (1000 * 60 * 60 * 24);
var startDate = new Date(2017, 0, 16);
var endDate = new Date();
var dataTable = new google.visualization.DataTable();
dataTable.addColumn('date', 'Date');
dataTable.addColumn('number', 'Value');
for (var i = startDate.getTime(); i < endDate.getTime(); i = i + oneDay) {
dataTable.addRow([
new Date(i),
(2 * ((i - startDate.getTime()) / oneDay) + 8)
]);
}
var chartColumn = new google.visualization.ChartWrapper({
chartType: 'LineChart',
containerId: 'chart-line',
dataTable: dataTable,
options: {
theme: 'maximized'
}
});
chartColumn.draw();
}
<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-line"></div>
2)
manually size the chart and the chart area...
here, room is left on the edges (top, right, bottom, left)
for the various labels...
chartArea: {
top: 12,
right: 12,
bottom: 24,
left: 24,
height: '100%',
width: '100%'
}
see following working snippet...
google.charts.load('current', {
callback: function () {
drawChart();
$(window).on('resize', drawChart);
},
packages:['corechart']
});
function drawChart() {
var formatDate = new google.visualization.DateFormat({
pattern: 'dd/MM'
});
var oneDay = (1000 * 60 * 60 * 24);
var startDate = new Date(2017, 0, 16);
var endDate = new Date();
var dataTable = new google.visualization.DataTable();
dataTable.addColumn('date', 'Date');
dataTable.addColumn('number', 'Value');
for (var i = startDate.getTime(); i < endDate.getTime(); i = i + oneDay) {
dataTable.addRow([
new Date(i),
(2 * ((i - startDate.getTime()) / oneDay) + 8)
]);
}
var chartColumn = new google.visualization.ChartWrapper({
chartType: 'LineChart',
containerId: 'chart-line',
dataTable: dataTable,
options: {
chartArea: {
top: 12,
right: 12,
bottom: 24,
left: 24,
height: '100%',
width: '100%'
}
}
});
chartColumn.draw();
}
<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-line"></div>

Related

Bubbles chart: how to avoid bubbles being cut off? google visualization

I'm using google visualization for bubble chart, data to x axis and Y axis is dynamic. I'm facing issue here is that bubbles get cut-off and there size is also not uniform.
using following options
options = {
'title': 'Chart',
'width': '100%',
'height': 550,
legend: {position: 'right'},
vAxis: {
title: 'Score',
viewWindow: {
min: 0,
max: 5
},
baselineColor: {
color: '#4c78c6',
},
sizeAxis : {minValue: 0, maxSize: 15},
ticks: [1, 2, 3, 4, 5]
},
hAxis: {
title: 'Years',
baselineColor: {
color: '#4c78c6',
}
},
sizeAxis : {minValue: 0, maxSize: 15},
bubble: {
textStyle: {
color: 'none',
}
},
tooltip: {
isHtml: true,
},
colors: colors,
chartArea: { width: "30%", height: "50%" }
};
EDIT data passed to
var rows = [
['ID','YEAR','SCORE', 'AVG1', 'AVG']
['Deka marc', 2.5, 5, '76-100%', 100]
['Max cala', 28.2,3.4,'76-100%', 77]
['shane root',4.2, 1, '0-25%', 0]
]
var data = google.visualization.arrayToDataTable(rows);
from above array I'm removing element 3 on hover as do not wish to show in tooltip. AVG1 column is for legend
getting o/p like this
use
var rangeX = data.getColumnRange(1);
to know the range of column
and then use
hAxis: {
viewWindow: {
min: rangeX.min-10,
max: rangeX.max+10
}
},
}
do similarly for yAxis
https://jsfiddle.net/geniusunil/nt4ymrLe/4/
Add inside hAxis the viewWindow option.
This is a sample code:
viewWindow: {
min: 0,
max: 40
}
You can change max according your biggest value in your dataset you want to show. I mean if is 30 (as in your example) you can set max: 40, or if is 75 you can set max equal to 85.
JSfiddle here.
to find the range of each axis dynamically, use data table method --> getColumnRange
then you can use the ticks option to increase the range.
var rangeX = data.getColumnRange(1);
var ticksX = [];
for (var i = (Math.floor(rangeX.min / 10) * 10); i <= (Math.ceil(rangeX.max / 10) * 10); i = i + 10) {
ticksX.push(i);
}
var rangeY = data.getColumnRange(2);
var ticksY = [];
for (var i = Math.floor(rangeY.min) - 1; i <= Math.ceil(rangeY.max) + 1; i++) {
ticksY.push(i);
}
to make the size of the bubble uniform, set minSize & maxSize to the same value.
sizeAxis : {minSize: 15, maxSize: 15},
see following working snippet...
google.charts.load('current', {
packages: ['corechart']
}).then(function () {
var rows = [
['ID','YEAR','SCORE', 'AVG1', 'AVG'],
['Deka marc', 2.5, 5, '76-100%', 100],
['Max cala', 28.2,3.4,'76-100%', 77],
['shane root',4.2, 1, '0-25%', 0]
];
var data = google.visualization.arrayToDataTable(rows);
var rangeX = data.getColumnRange(1);
var ticksX = [];
for (var i = (Math.floor(rangeX.min / 10) * 10); i <= (Math.ceil(rangeX.max / 10) * 10); i = i + 10) {
ticksX.push(i);
}
var rangeY = data.getColumnRange(2);
var ticksY = [];
for (var i = Math.floor(rangeY.min) - 1; i <= Math.ceil(rangeY.max) + 1; i++) {
ticksY.push(i);
}
var options = {
title: 'Chart',
width: '100%',
height: 550,
legend: {position: 'right'},
vAxis: {
title: 'Score',
baselineColor: {
color: '#4c78c6',
},
sizeAxis : {minSize: 15, maxSize: 15},
ticks: ticksY
},
hAxis: {
title: 'Years',
baselineColor: {
color: '#4c78c6',
},
ticks: ticksX
},
sizeAxis : {minSize: 10, maxSize: 10},
bubble: {
textStyle: {
color: 'none',
}
},
tooltip: {
isHtml: true,
},
//colors: colors,
chartArea: { width: "30%", height: "50%" }
};
var chart = new google.visualization.BubbleChart(document.getElementById('chart_div'));
chart.draw(data, options);
});
<script src="https://www.gstatic.com/charts/loader.js"></script>
<div id="chart_div"></div>
Add 10% of the difference between the max and min
vAxis: {
viewWindow: {
min: rangeY.min - ((+rangeY.max - rangeY.min) * 10 / 100),
max: rangeY.max + ((+rangeY.max - rangeY.min) * 10 / 100)
}
},
hAxis: {
viewWindow: {
min: rangeX.min - ((+rangeX.max - rangeX.min) * 10 / 100),
max: rangeX.max + ((+rangeX.max - rangeX.min) * 10 / 100)
}
},

Multiple group on AxisX with javascript

I'm trying to create a chart with multiple AxisX with a javascript library (google or chartjs preferable).
I have made an example on excel to illustrate what i'm looking for, here is the example:
I've tried the next fiddle but obviously without success.
google.charts.load('current', {'packages':['corechart']});
google.charts.setOnLoadCallback(drawVisualization);
function drawVisualization() {
// Some raw data (not necessarily accurate)
var data = google.visualization.arrayToDataTable([
['Month', ['Activo, inactivo'], ['Activo, inactivo'], ['Activo, inactivo'], ['Activo, inactivo']],
['Gestor A', [165,100], [938,800], [522,100], [998, 1000]],
['Gestor B', [135,90], [1120,1000], [599,1000], [1268,700]],
['Gestor C', [157,70], [1167,800], [587,400], [807,900]],
['Gestor D', [139,160], [1110,1200], [615,500], [968,1000]],
['Gestor E', [136,200], [691,800], [629,700], [1026,1200]]
]);
var options = {
title : 'Monthly Coffee Production by Country',
vAxis: {title: 'Cups'},
hAxis: {title: ['Month']},
seriesType: 'bars',
series: {5: {type: 'line'}}
};
var chart = new google.visualization.ComboChart(document.getElementById('chart_div'));
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>
google charts does not offer multiple group labels
but you can add them manually on the chart's 'ready' event
see following working snippet,
the position of the x-axis labels are used to draw the group labels and lines
google.charts.load('current', {
packages: ['corechart']
}).then(function () {
var data = google.visualization.arrayToDataTable([
['Month', 'Gestor A', 'Gestor B', 'Gestor C', 'Gestor D', 'Gestor E'],
['Activo', 165, 135, 157, 139, 136],
['Inactivo', 100, 90, 70, 160, 200],
['Activo', 938, 1120, 1167, 1110, 691],
['Inactivo', 800, 1000, 800, 1200, 800],
['Activo', 522, 599, 587, 615, 629],
['Inactivo', 100, 1000, 400, 500, 700],
['Activo', 998, 1268, 807, 968, 1026],
['Inactivo', 1000, 700, 900, 1000, 1200]
]);
var options = {
chartArea: {
bottom: 64,
left: 48,
right: 16,
top: 64,
width: '100%',
height: '100%'
},
hAxis: {
maxAlternation: 1,
slantedText: false
},
height: '100%',
legend: {
alignment: 'end',
position: 'top'
},
seriesType: 'bars',
title : 'Title',
width: '100%'
};
var container = document.getElementById('chart_div');
var chart = new google.visualization.ComboChart(container);
google.visualization.events.addListener(chart, 'ready', function () {
var chartLayout = chart.getChartLayoutInterface();
var chartBounds = chartLayout.getChartAreaBoundingBox();
var indexGroup = 0;
var indexRow = 0;
var months = ['Janeiro', 'Fevereiro', 'Marco', 'Abril'];
var xCoords = [];
Array.prototype.forEach.call(container.getElementsByTagName('text'), function(text) {
// process x-axis labels
var xAxisLabel = data.getFilteredRows([{column: 0, value: text.textContent}]);
if (xAxisLabel.length > 0) {
// save label x-coordinate
xCoords.push(parseFloat(text.getAttribute('x')));
// add first / last group line
if (indexRow === 0) {
addGroupLine(chartBounds.left, chartBounds.top + chartBounds.height);
}
if (indexRow === (data.getNumberOfRows() - 1)) {
addGroupLine(chartBounds.left + chartBounds.width, chartBounds.top + chartBounds.height);
}
// add group label / line
if ((indexRow % 2) !== 0) {
// calc label coordinates
var xCoord = xCoords[0] + ((xCoords[1] - xCoords[0]) / 2);
var yCoord = parseFloat(text.getAttribute('y')) + (parseFloat(text.getAttribute('font-size')) * 1.5);
// add group label
var groupLabel = text.cloneNode(true);
groupLabel.setAttribute('y', yCoord);
groupLabel.setAttribute('x', xCoord);
groupLabel.textContent = months[indexGroup];
text.parentNode.appendChild(groupLabel);
// add group line
addGroupLine(chartBounds.left + ((chartBounds.width / 4) * (indexGroup + 1)), chartBounds.top + chartBounds.height);
indexGroup++;
xCoords = [];
}
indexRow++;
}
});
function addGroupLine(xCoord, yCoord) {
var parent = container.getElementsByTagName('g')[0];
var groupLine = container.getElementsByTagName('rect')[0].cloneNode(true);
groupLine.setAttribute('x', xCoord);
groupLine.setAttribute('y', yCoord);
groupLine.setAttribute('width', 0.8);
groupLine.setAttribute('height', options.chartArea.bottom);
parent.appendChild(groupLine);
}
});
window.addEventListener('resize', function () {
chart.draw(data, options);
});
chart.draw(data, options);
});
html, body {
height: 100%;
margin: 0px 0px 0px 0px;
overflow: hidden;
padding: 0px 0px 0px 0px;
}
.chart {
height: 100%;
}
<script src="https://www.gstatic.com/charts/loader.js"></script>
<div class="chart" id="chart_div"></div>
note: elements drawn manually will not show when using chart method getImageURI,
if you need an image of the chart, you can use html2canvas
Exemple with chartjs - https://jsfiddle.net/6c0L1yva/392/
JAVASCRIPT -
var ctx = document.getElementById('c');
var myChart = new Chart(ctx, {
type: 'bar',
data: {
labels: ["Active;January", "Inactive;January", "Active;February", "Inactive;February", "Active;March", "Inactive;March"],
datasets: [{
label: "Gestor A",
backgroundColor: "blue",
data: [3, 7, 4, 2, 3, 1]
}, {
label: "Gestor B",
backgroundColor: "red",
data: [4, 3, 5, 3, 1, 2]
}, {
label: "Gestor C",
backgroundColor: "green",
data: [7, 2, 6, 8, 2, 1]
}]
},
options:{
scales:{
xAxes:[
{
id:'xAxis1',
type:"category",
ticks:{
callback:function(label){
var state = label.split(";")[0];
var user = label.split(";")[1];
return state;
}
}
},
{
id:'xAxis2',
type:"category",
gridLines: {
drawOnChartArea: false, // only want the grid lines for one axis to show up
},
ticks:{
callback:function(label){
var state = label.split(";")[0];
var user = label.split(";")[1];
if(state === "Inactive"){
return user;
}else{
return "";
}
}
}
}],
yAxes:[{
ticks:{
beginAtZero:true
}
}]
}
}
});

Continuous Axis Google Chart Loaded with CSV?

I've managed to implement a continuous axis google chart on my page and got it formatted the way I want it. Now my requirements have changed and I'm trying to load this chart from a CSV as opposed to hard coded and randomly generated data.
I've confused myself and gotten in over my head on how to convert my working chart into pulling from a CSV. I'm going to post a few things here,
One of my other charts that utilizes a CSV, this is what I was trying to recreate
My working continuous axis chart running off hard coded data
My current state of the chart now that I've tried to implement the change.
Here is #1:
function drawPieVisualization() {
$.get("Thornton.M2.csv", function(csvString) {
// transform the CSV string into a 2-dimensional array
var arrayData = $.csv.toArrays(csvString, {onParseValue: $.csv.hooks.castToScalar}, {onParseValue: $.csv.hooks.castToScalar});
// this new DataTable object holds all the data
var data = new google.visualization.arrayToDataTable(arrayData);
// CAPACITY - En-route ATFM delay - YY - CHART
var pieMain = new google.visualization.ChartWrapper({
chartType: 'BarChart',
containerId: 'pieMain',
dataTable: data,
options:{
title: 'Bar Chart Test',
'vAxis': { title: "Bar Chart Test" },
'width': 1100,
'height': 540,
'backgroundColor': 'Ivory',
'color':'Black',
'hAxis': {
title: "Date",
gridlines: { count: 3, color: '#CCC' },
format: 'dd-MMM-yyyy'
},
title: 'Bar Chart Test',
titleTextStyle : {color: 'Black', fontSize: 16},
}
});
pieMain.draw();
});
}
google.setOnLoadCallback(drawPieVisualization)
changeRange = function() {
pieMain.sort({column: 0, desc: false});
pieMain.draw();
};
changeRangeBack = function() {
pieMain.sort({column: 0, desc: true});
pieMain.draw();
};
Here is #2:
function drawVisualization() {
var data = new google.visualization.DataTable();
data.addColumn('date', 'Date');
data.addColumn('number', 'Value');
// add 100 rows of pseudo-random-walk data
for (var i = 0, val = 50; i < 100; i++) {
val += ~~(Math.random() * 5) * Math.pow(-1, ~~(Math.random() * 2));
if (val < 0) {
val += 5;
}
if (val > 100) {
val -= 5;
}
data.addRow([new Date(2014, 0, i + 1), val]);
}
var chart = new google.visualization.ChartWrapper({
chartType: 'ComboChart',
containerId: 'slider_chart_div',
options: {
'title': 'Average Ratings',
'vAxis': { title: "Average Rating" },
'backgroundColor': 'Ivory',
'color':'Black',
width: 1100,
height: 400,
// omit width, since we set this in CSS
chartArea: {
width: '75%' // this should be the same as the ChartRangeFilter
}
}
});
var control = new google.visualization.ControlWrapper({
controlType: 'ChartRangeFilter',
containerId: 'control_div',
options: {
filterColumnIndex: 0,
ui: {
chartOptions: {
'backgroundColor': 'Ivory',
'color':'Black',
width: 1100,
height: 50,
// omit width, since we set this in CSS
chartArea: {
width: '75%' // this should be the same as the ChartRangeFilter
}
}
}
}
});
var dashboard = new google.visualization.Dashboard(document.querySelector('#dashboard_div'));
dashboard.bind([control], [chart]);
dashboard.draw(data);
function zoomLastDay () {
var range = data.getColumnRange(0);
control.setState({
range: {
start: new Date(range.max.getFullYear(), range.max.getMonth(), range.max.getDate() - 1),
end: range.max
}
});
control.draw();
}
function zoomLastWeek () {
var range = data.getColumnRange(0);
control.setState({
range: {
start: new Date(range.max.getFullYear(), range.max.getMonth(), range.max.getDate() - 7),
end: range.max
}
});
control.draw();
}
function zoomLastMonth () {
// zoom here sets the month back 1, which can have odd effects when the last month has more days than the previous month
// eg: if the last day is March 31, then zooming last month will give a range of March 3 - March 31, as this sets the start date to February 31, which doesn't exist
// you can tweak this to make it function differently if you want
var range = data.getColumnRange(0);
control.setState({
range: {
start: new Date(range.max.getFullYear(), range.max.getMonth() - 1, range.max.getDate()),
end: range.max
}
});
control.draw();
}
var runOnce = google.visualization.events.addListener(dashboard, 'ready', function () {
google.visualization.events.removeListener(runOnce);
if (document.addEventListener) {
document.querySelector('#lastDay').addEventListener('click', zoomLastDay);
document.querySelector('#lastWeek').addEventListener('click', zoomLastWeek);
document.querySelector('#lastMonth').addEventListener('click', zoomLastMonth);
}
else if (document.attachEvent) {
document.querySelector('#lastDay').attachEvent('onclick', zoomLastDay);
document.querySelector('#lastWeek').attachEvent('onclick', zoomLastWeek);
document.querySelector('#lastMonth').attachEvent('onclick', zoomLastMonth);
}
else {
document.querySelector('#lastDay').onclick = zoomLastDay;
document.querySelector('#lastWeek').onclick = zoomLastWeek;
document.querySelector('#lastMonth').onclick = zoomLastMonth;
}
});
}
And Here is #3:
function drawVisualization() {
$.get("Source7Days.csv", function(csvString) {
// transform the CSV string into a 2-dimensional array
var arrayData = $.csv.toArrays(csvString, {onParseValue: $.csv.hooks.castToScalar}, {onParseValue: $.csv.hooks.castToScalar});
// this new DataTable object holds all the data
var data = new google.visualization.arrayToDataTable(arrayData);
var chart = new google.visualization.ChartWrapper({
chartType: 'ComboChart',
containerId: 'slider_chart_div',
dataTable: data,
options: {
'title': 'Average Ratings',
'vAxis': { title: "Average Rating" },
'backgroundColor': 'Ivory',
'color':'Black',
width: 1100,
height: 400,
// omit width, since we set this in CSS
chartArea: {
width: '75%' // this should be the same as the ChartRangeFilter
}
}
});
var control = new google.visualization.ControlWrapper({
controlType: 'ChartRangeFilter',
containerId: 'control_div',
options: {
filterColumnIndex: 0,
ui: {
chartOptions: {
'backgroundColor': 'Ivory',
'color':'Black',
width: 1100,
height: 50,
// omit width, since we set this in CSS
chartArea: {
width: '75%' // this should be the same as the ChartRangeFilter
}
}
}
}
});
var dashboard = new google.visualization.Dashboard(document.querySelector('#dashboard_div'));
dashboard.bind([control], [chart]);
dashboard.draw(data);
function zoomLastDay () {
var range = data.getColumnRange(0);
control.setState({
range: {
start: new Date(range.max.getFullYear(), range.max.getMonth(), range.max.getDate() - 1),
end: range.max
}
});
control.draw();
}
function zoomLastWeek () {
var range = data.getColumnRange(0);
control.setState({
range: {
start: new Date(range.max.getFullYear(), range.max.getMonth(), range.max.getDate() - 7),
end: range.max
}
});
control.draw();
}
function zoomLastMonth () {
// zoom here sets the month back 1, which can have odd effects when the last month has more days than the previous month
// eg: if the last day is March 31, then zooming last month will give a range of March 3 - March 31, as this sets the start date to February 31, which doesn't exist
// you can tweak this to make it function differently if you want
var range = data.getColumnRange(0);
control.setState({
range: {
start: new Date(range.max.getFullYear(), range.max.getMonth() - 1, range.max.getDate()),
end: range.max
}
});
control.draw();
}
var runOnce = google.visualization.events.addListener(dashboard, 'ready', function () {
google.visualization.events.removeListener(runOnce);
if (document.addEventListener) {
document.querySelector('#lastDay').addEventListener('click', zoomLastDay);
document.querySelector('#lastWeek').addEventListener('click', zoomLastWeek);
document.querySelector('#lastMonth').addEventListener('click', zoomLastMonth);
}
else if (document.attachEvent) {
document.querySelector('#lastDay').attachEvent('onclick', zoomLastDay);
document.querySelector('#lastWeek').attachEvent('onclick', zoomLastWeek);
document.querySelector('#lastMonth').attachEvent('onclick', zoomLastMonth);
}
else {
document.querySelector('#lastDay').onclick = zoomLastDay;
document.querySelector('#lastWeek').onclick = zoomLastWeek;
document.querySelector('#lastMonth').onclick = zoomLastMonth;
}
});
}
)}
And here is a sample of the CSV Data I'm utilizing
Time,Value
2017/05/22 00:05:00,6710.4305066168
2017/05/22 00:10:00,6667.5043776631
2017/05/22 00:15:00,6615.6655550003
2017/05/22 00:20:00,6554.988194257
2017/05/22 00:25:00,6532.4164219201
2017/05/22 00:30:00,6520.8965539932
The bottom part 'runOnce' in both #2 and #3 are to change the slider control on the chart from 1 day - 1 week - or 1 month of range on the chart, for clarification.
My chart is currently giving me the errors:
One or more participants failed to draw(). (Two of these)
And
The filter cannot operate on a column of type string. Column type must
be one of: number, date, datetime or timeofday. Column role must be
domain, and correlate to a continuous axis.
the second error message reveals that arrayToDataTable
creates the first column as --> type: 'string'
instead of --> type: 'date'
use a DataView to convert the string to a date
you can create calculated columns in a data view using method --> setColumns
use view in place of data when drawing the dashboard
see following snippet...
$.get("Source7Days.csv", function(csvString) {
var arrayData = $.csv.toArrays(csvString, {onParseValue: $.csv.hooks.castToScalar}, {onParseValue: $.csv.hooks.castToScalar});
// this is a static method, "new" keyword should not be used here
var data = google.visualization.arrayToDataTable(arrayData);
// create view
var view = new google.visualization.DataView(data);
view.setColumns([
// first column is calculated
{
calc: function (dt, row) {
// convert string to date
return new Date(dt.getValue(row, 0));
},
label: data.getColumnLabel(0),
type: 'date'
},
// just use index # for second column
1
]);
var chart = new google.visualization.ChartWrapper({
chartType: 'ComboChart',
containerId: 'slider_chart_div',
options: {
title: 'Average Ratings',
vAxis: { title: 'Average Rating' },
backgroundColor: 'Ivory',
color: 'Black',
width: 1100,
height: 400,
chartArea: {
width: '75%'
}
}
});
var control = new google.visualization.ControlWrapper({
controlType: 'ChartRangeFilter',
containerId: 'control_div',
options: {
filterColumnIndex: 0,
ui: {
chartOptions: {
backgroundColor: 'Ivory',
color: 'Black',
width: 1100,
height: 50,
chartArea: {
width: '75%'
}
}
}
}
});
var dashboard = new google.visualization.Dashboard(document.querySelector('#dashboard_div'));
dashboard.bind([control], [chart]);
// use data view
dashboard.draw(view);
...

Annotation Google Chart API

i'm trying to use Google Chart API for building an Waterfall chart. I noticed that Candlestick/Waterfall charts are not supporting the annotations.
See this jsfiddle sample
google.charts.load('current', {'packages':['corechart']});
google.charts.setOnLoadCallback(drawChart);
function drawChart() {
var data = new google.visualization.DataTable();
data.addColumn('string', 'Category');
data.addColumn('number', 'MinimumLevel');
data.addColumn('number', 'MinimumLevel1');
data.addColumn('number', 'MaximumLevel');
data.addColumn('number', 'MaximumLevel1');
data.addColumn({type: 'number', role: 'tooltip'});
data.addColumn({type: 'string', role: 'style'});
data.addColumn({type: 'number', role: 'annotation'});
data.addRow(['Category 1', 0 , 0, 5, 5, 5,'gray',5]);
data.addRow(['Category 2', 5 , 5, 10, 10, 10,'red',10]);
data.addRow(['Category 3', 10 , 10, 15, 15, 15,'blue',15]);
data.addRow(['Category 4', 15 , 15, 10, 10, 10,'yellow',10]);
data.addRow(['Category 5', 10 , 10, 5, 5, 5,'gray',5]);
var options = {
legend: 'none',
bar: { groupWidth: '60%' } // Remove space between bars.
};
var chart = new google.visualization.CandlestickChart(document.getElementById('chart_div'));
chart.draw(data, options);
}
I would like to put the value of the 5th column at the top of every candlestick.
It should look like this :
Is there a way to do this?
Thanks
I add annotations to candlestick charts by adding annotations to a hidden scatter plot. You can set exactly where you want the annotations to sit by changing the plot.
google.charts.load('current', { 'packages': ['corechart'] });
google.charts.setOnLoadCallback(drawChart);
function drawChart() {
var data = new google.visualization.DataTable();
data.addColumn('date', 'Date');
data.addColumn('number', 'Low');
data.addColumn('number', 'Open');
data.addColumn('number', 'Close');
data.addColumn('number', 'High');
data.addColumn('number'); //scatter plot for annotations
data.addColumn({ type: 'string', role: 'annotation' }); // annotation role col.
data.addColumn({ type: 'string', role: 'annotationText' }); // annotationText col.
var high, low, open, close = 160;
for (var i = 0; i < 10; i++) {
open = close;
close += ~~(Math.random() * 10) * Math.pow(-1, ~~(Math.random() * 2));
high = Math.max(open, close) + ~~(Math.random() * 10);
low = Math.min(open, close) - ~~(Math.random() * 10);
annotation = '$' + close;
annotation_text = 'Close price: $' + close;
data.addRow([new Date(2014, 0, i + 1), low, open, close, high, high, annotation, annotation_text]);
}
var view = new google.visualization.DataView(data);
var chart = new google.visualization.ComboChart(document.querySelector('#chart_div'));
chart.draw(view, {
height: 400,
width: 600,
explorer: {},
chartArea: {
left: '7%',
width: '70%'
},
series: {
0: {
color: 'black',
type: 'candlesticks',
},
1: {
type: 'scatter',
pointSize: 0,
targetAxisIndex: 0,
},
},
candlestick: {
color: '#a52714',
fallingColor: { strokeWidth: 0, fill: '#a52714' }, // red
risingColor: { strokeWidth: 0, fill: '#0f9d58' } // green
},
});
}
<script type="text/javascript"src="https://www.gstatic.com/charts/loader.js"></script>
<div id="chart_div" style="width: 900px; height: 500px;"></div>
just so happens, i ran into the same problem this week
so I added my own annotations, during the 'animationfinish' event
see following working snippet...
google.charts.load('current', {
callback: drawChart,
packages:['corechart']
});
function drawChart() {
var dataChart = new google.visualization.DataTable({"cols":[{"label":"Category","type":"string"},{"label":"Bottom 1","type":"number"},{"label":"Bottom 2","type":"number"},{"label":"Top 1","type":"number"},{"label":"Top 2","type":"number"},{"role":"style","type":"string","p":{"role":"style"}}],"rows":[{"c":[{"v":"Budget"},{"v":0},{"v":0},{"v":22707893.613},{"v":22707893.613},{"v":"#007fff"}]},{"c":[{"v":"Contract Labor"},{"v":22707893.613},{"v":22707893.613},{"v":22534350.429},{"v":22534350.429},{"v":"#1e8449"}]},{"c":[{"v":"Contract Non Labor"},{"v":22534350.429},{"v":22534350.429},{"v":22930956.493},{"v":22930956.493},{"v":"#922b21"}]},{"c":[{"v":"Materials and Equipment"},{"v":22930956.493},{"v":22930956.493},{"v":22800059.612},{"v":22800059.612},{"v":"#1e8449"}]},{"c":[{"v":"Other"},{"v":22800059.612},{"v":22800059.612},{"v":21993391.103},{"v":21993391.103},{"v":"#1e8449"}]},{"c":[{"v":"Labor"},{"v":21993391.103},{"v":21993391.103},{"v":21546003.177999996},{"v":21546003.177999996},{"v":"#1e8449"}]},{"c":[{"v":"Travel"},{"v":21546003.177999996},{"v":21546003.177999996},{"v":21533258.930999994},{"v":21533258.930999994},{"v":"#1e8449"}]},{"c":[{"v":"Training"},{"v":21533258.930999994},{"v":21533258.930999994},{"v":21550964.529999994},{"v":21550964.529999994},{"v":"#922b21"}]},{"c":[{"v":"Actual"},{"v":0},{"v":0},{"v":21550964.52999999},{"v":21550964.52999999},{"v":"#007fff"}]}]});
var waterFallChart = new google.visualization.ChartWrapper({
chartType: 'CandlestickChart',
containerId: 'chart_div',
dataTable: dataChart,
options: {
animation: {
duration: 1500,
easing: 'inAndOut',
startup: true
},
backgroundColor: 'transparent',
bar: {
groupWidth: '85%'
},
chartArea: {
backgroundColor: 'transparent',
height: 210,
left: 60,
top: 24,
width: '100%'
},
hAxis: {
slantedText: false,
textStyle: {
color: '#616161',
fontSize: 9
}
},
height: 272,
legend: 'none',
tooltip: {
isHtml: true,
trigger: 'both'
},
vAxis: {
format: 'short',
gridlines: {
count: -1
},
textStyle: {
color: '#616161'
},
viewWindow: {
max: 24000000,
min: 16000000
}
},
width: '100%'
}
});
google.visualization.events.addOneTimeListener(waterFallChart, 'ready', function () {
google.visualization.events.addListener(waterFallChart.getChart(), 'animationfinish', function () {
var annotation;
var chartLayout;
var container;
var numberFormatShort;
var positionY;
var positionX;
var rowBalance;
var rowBottom;
var rowFormattedValue;
var rowIndex;
var rowTop;
var rowValue;
var rowWidth;
container = document.getElementById(waterFallChart.getContainerId());
chartLayout = waterFallChart.getChart().getChartLayoutInterface();
numberFormatShort = new google.visualization.NumberFormat({
pattern: 'short'
});
rowIndex = 0;
Array.prototype.forEach.call(container.getElementsByTagName('rect'), function(rect) {
switch (rect.getAttribute('fill')) {
// use colors to identify bars
case '#922b21':
case '#1e8449':
case '#007fff':
rowWidth = parseFloat(rect.getAttribute('width'));
if (rowWidth > 2) {
rowBottom = waterFallChart.getDataTable().getValue(rowIndex, 1);
rowTop = waterFallChart.getDataTable().getValue(rowIndex, 3);
rowValue = rowTop - rowBottom;
rowBalance = Math.max(rowBottom, rowTop);
positionY = chartLayout.getYLocation(rowBalance) - 6;
positionX = parseFloat(rect.getAttribute('x'));
rowFormattedValue = numberFormatShort.formatValue(rowValue);
if (rowValue < 0) {
rowFormattedValue = rowFormattedValue.replace('-', '');
rowFormattedValue = '(' + rowFormattedValue + ')';
}
annotation = container.getElementsByTagName('svg')[0].appendChild(container.getElementsByTagName('text')[0].cloneNode(true));
$(annotation).text(rowFormattedValue);
annotation.setAttribute('x', (positionX + (rowWidth / 2)));
annotation.setAttribute('y', positionY);
annotation.setAttribute('font-weight', 'bold');
rowIndex++;
}
break;
}
});
});
});
$(window).resize(function() {
waterFallChart.draw();
});
waterFallChart.draw();
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.12.4/jquery.min.js"></script>
<script src="https://www.gstatic.com/charts/loader.js"></script>
<div id="chart_div"></div>

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