This is my code
<script type='text/javascript' src='http://www.google.com/jsapi'></script>
<script type='text/javascript'>google.load('visualization', '1', {'packages': ['geochart']});
google.setOnLoadCallback(drawVisualization);
function drawVisualization()
{
var query = new google.visualization.Query('https://docs.google.com/spreadsheets/d/1dTfxVvfDKn6iXn4W_m7HJ_86JOGNDsxYSSaXipEo0vM/edit#gid=0');
// query.setQuery('select A,B,C');
query.send(handleQueryResponseTR);
}
function handleQueryResponseTR(response) {
if (response.isError()) {
alert('Error in query: ' + response.getMessage() + ' ' + response.getDetailedMessage());
return;
}
var options = {
backgroundColor: {fill:'#FFFFFF',stroke:'#FFFFFF' ,strokeWidth:0 },
colorAxis: {colors: ['#D95F0E','#FEC44F','#FEC44F','#FEC44F','#FEC44F','#FEC44F','#FEC44F','#FEC44F','#FEC44F','#FFF7BC','#FFF7BC','#FFF7BC','#FFF7BC',]},
backgroundColor: {fill:'#FFFFFF',stroke:'#FFFFFF' ,strokeWidth:0 },
datalessRegionColor: '#F5F0E7',
displayMode: 'regions',
enableRegionInteractivity: 'true',
resolution: 'countries',
sizeAxis: {minValue: 1, maxValue:1,minSize:10, maxSize: 10},
region:'world',
keepAspectRatio: true,
width:800,
height:600,
tooltip: {isHtml:'true',textStyle: {color: '#444444'}, trigger:'focus'}
};
var data = response.getDataTable();
var view = new google.visualization.DataView(data);
view.setColumns([0,{
type:'string',
label : 'num of',
calc: function (dt, row) {
return {
v: dt.getValue(row, 1),
f: dt.getFormattedValue(row, 1) + ': (' + dt.getFormattedValue(row, 2) + ' .)'
}
}
}]);
var chart = new google.visualization.GeoChart(document.getElementById('visualization'));
chart.draw(view, options);
}
</script>
<div id='visualization'></div>
and the spreadsheet here https://docs.google.com/spreadsheets/d/1dTfxVvfDKn6iXn4W_m7HJ_86JOGNDsxYSSaXipEo0vM/edit#gid=0
I don't know why the country name in the first column not show on the geochart
and how can I customize the tooltips such as.. add line break instead of colon(:) I tried br / but it didn't work
anyone can help ?
Thanks
added the following properties to the calculated view field...
role: 'tooltip',
p: {html: true}
see following working snippet...
google.charts.load('current', {
callback: drawVisualization,
packages:['geochart']
});
function drawVisualization() {
var query = new google.visualization.Query('https://docs.google.com/spreadsheets/d/1dTfxVvfDKn6iXn4W_m7HJ_86JOGNDsxYSSaXipEo0vM/edit#gid=0');
query.send(handleQueryResponseTR);
}
function handleQueryResponseTR(response) {
if (response.isError()) {
console.log('Error in query: ' + response.getMessage() + ' ' + response.getDetailedMessage());
return;
}
var options = {
backgroundColor: {fill:'#FFFFFF',stroke:'#FFFFFF' ,strokeWidth:0 },
colorAxis: {colors: ['#D95F0E','#FEC44F','#FEC44F','#FEC44F','#FEC44F','#FEC44F','#FEC44F','#FEC44F','#FEC44F','#FFF7BC','#FFF7BC','#FFF7BC','#FFF7BC',]},
backgroundColor: {fill:'#FFFFFF',stroke:'#FFFFFF' ,strokeWidth:0 },
datalessRegionColor: '#F5F0E7',
displayMode: 'regions',
enableRegionInteractivity: 'true',
resolution: 'countries',
sizeAxis: {minValue: 1, maxValue:1,minSize:10, maxSize: 10},
region:'world',
keepAspectRatio: true,
width:800,
height:600,
tooltip: {isHtml:'true',textStyle: {color: '#444444'}, trigger:'focus'}
};
var data = response.getDataTable();
var view = new google.visualization.DataView(data);
view.setColumns([0, {
type:'string',
label : 'num of',
calc: function (dt, row) {
return dt.getFormattedValue(row, 1) + ': (' + dt.getFormattedValue(row, 2) + ' .)'
},
role: 'tooltip',
p: {html: true}
}]);
var chart = new google.visualization.GeoChart(document.getElementById('visualization'));
chart.draw(view, options);
}
<script src="https://www.gstatic.com/charts/loader.js"></script>
<div id='visualization'></div>
Related
I am displaying pie-chart as a tootip inside a column chart using google charts.
In the pie-chart, I want to do legend: { position: 'labeled' }, but it is not displaying the bars of the Column chart, and so cannot display the Pie chart.
It is only displaying the gridlines.
My current code:
//Create Charts
function AggregateCharts(aggregateResult){
$('#hidden_div').show();
google.charts.load('current', {'packages':['corechart']});
google.charts.setOnLoadCallback( function(){ drawTooltipCharts(aggregateResult) });
}
// Draw tool tip charts
function drawTooltipCharts(aggregateResult) {
//set bar chart data
primaryData=[];
if(aggregateResult){
aggregateResult.map(data=>{
if(data.Count>0 || data.High>0 || data.Medium>0)
{
//Set Options
var tooltipOptions = {
title: 'Data Title',
isStacked: true,
pieHole: 0.4,
sliceVisibilityThreshold:0,
colors: ['#c1c1c1','#0074AA','#1DB2F7','#F7941D' ],
legendTextStyle: { color: '#1DB2F7' ,fontSize: 12},
titleTextStyle: { color: '#1DB2F7', alignment: 'center',fontSize: 15},
chartArea: {width:510, height: 250} ,
legend: { position: 'labeled' },
pieStartAngle: 100,
pieSliceTextStyle: { fontSize:12 },
};
//Create chart View
var view = new google.visualization.DataTable();
view.addColumn('string', 'Criteria');
view.addColumn('number', 'Users');
var total=total;
var Count=data.Count;
var High=data.High;
var Medium=data.Medium;
//calculation part
var Countpercentage =((Count/total).toFixed(2))*100;
var Highpercentage =((High/total).toFixed(2))*100;
var Mediumpercentage =((Medium/total).toFixed(2))*100;
var NoCriteriaEndorsed= 100-(Math.floor(Countpercentage) + Math.floor(Highpercentage) + Math.floor(Mediumpercentage) );
var tooltipData=[];
tooltipData.push(["No Criteria Endorsed",NoCriteriaEndorsed]);
tooltipData.push(["50-69% Criteria Endorsed",Mediumpercentage]);
tooltipData.push(["70-99% Criteria Endorsed",Highpercentage]);
tooltipData.push(["100% Criteria Endorsed",Countpercentage]);
//Add total rows
view.addRows(tooltipData);
var hiddenDiv = document.getElementById('hidden_div');
var tooltipChart = new google.visualization.PieChart(hiddenDiv);
google.visualization.events.addListener(tooltipChart, 'ready', function() {
// Get the PNG of the chart and set is as the src of an img tag.
var tooltipImg = '<img src="' + tooltipChart.getImageURI() + '">';
// Add the new tooltip image to your data rows.
primaryData.push([data.Diagnosis,data.Count,tooltipImg,data.High,tooltipImg,data.Medium,tooltipImg]);
});
tooltipChart.draw(view, tooltipOptions);
}
})
//Create bar chart
drawBarChart(primaryData);
}
}
function drawBarChart(primaryData) {
var fromDate=$("#fromdate").val()?$("#fromdate").val():getMinDate(AggregateData)
var tooltipData = new google.visualization.DataTable();
tooltipData.addColumn('string', 'Event');
tooltipData.addColumn('number', '100% Criteria Endorsed');
// Add a new column for your tooltips.
tooltipData.addColumn({
type: 'string',
label: 'Tooltip Chart',
role: 'tooltip',
'p': {'html': true}
});
tooltipData.addColumn('number', '70-99% Criteria Endorsed');
// Add a new column for your tooltips.
tooltipData.addColumn({
type: 'string',
label: 'Tooltip Chart',
role: 'tooltip',
'p': {'html': true}
});
tooltipData.addColumn('number', '50-69% Criteria Endorsed');
// Add a new column for your tooltips.
tooltipData.addColumn({
type: 'string',
label: 'Tooltip Chart',
role: 'tooltip',
'p': {'html': true}
});
// Add your data (with the newly added tooltipImg).
tooltipData.addRows(primaryData);
var minwidth=tooltipData.getNumberOfRows() <25 ?(25*50) : tooltipData.getNumberOfRows() *50;
var primaryOptions = {
title: 'Results' ,
legend: 'none',
tooltip: {isHtml: true},
isStacked: true,
colors: ['#F7941D', '#1DB2F7', '#0074AA'],
legendTextStyle: { color: '#000000' , fontSize: 20 },
titleTextStyle: { color: '#000000', fontSize: 16, fontName: 'Calibri Light', bold: true },
width: minwidth,
bar: {groupWidth:15},
hAxis: {
textStyle: { color: "#1DB2F7" ,fontSize: 8, bold: true },
gridlines: { count: 4, color: "#1DB2F7" },
baselineColor: '#1DB2F7',
},
vAxis: {
title: 'Number of Respondents',
titleTextStyle: { color: '#000000', fontSize: 18, fontName: 'Calibri Light', bold: true},
textStyle: { color: "#1DB2F7", fontSize: 10, bold: true },
gridlines: { count: 4 , color: "#1DB2F7" },
baselineColor: '#1DB2F7' ,
},
};
var visibleDiv = document.getElementById('visible_div');
var primaryChart = new google.visualization.ColumnChart(visibleDiv);
primaryChart.draw(tooltipData, primaryOptions);
CustomOptions(primaryOptions);
var btndownloadchart = document.getElementById('downloadchart');
btndownloadchart.addEventListener('click', function () {
this.href= primaryChart.getImageURI();
}, false);
}
//Date format to display in chart legend
function dateFormat(requestDate){
var date = requestDate?new Date(requestDate):new Date();
var dateString =date.toLocaleString('en', { month: 'long' })+" "+ date.getDate() +", "+ date.getFullYear() ;
return dateString;
}
//get mindate value for aggregate if from date not selected initially..
function getMinDate(AggregateData){
if(AggregateData){
var minDate = Math.min.apply(null, AggregateData.map(function(o) { return new Date(o.CreatedDate); }))
return date = new Date(minDate)
}
return new Date()
}
function CustomOptions(primaryOptions) {
var $container = $('#visible_div');
var svg = $container.find('svg') ;
var svgWidth=$container.find('svg').width();
var $titleElemWidth = parseInt($container.find('svg').width()/8) ;
var svgMargin= ('-' +((svgWidth/15)>170?170:(svgWidth/15))+ 'px');
svg.css("margin-left", svgMargin);
var $titleElem = $container.find("text:contains(" + primaryOptions.vAxis.title +")");
$titleElem.attr('y',$titleElemWidth<320?320:$titleElemWidth);
//Hide tooltip chart
$('#hidden_div').hide();
}
]]>
When I do legend: { alignment: 'center' } in the 'tooltipOptions', the Column chart and the Pie-chart is displaying correctly.
But I want to do 'legend: { position: 'labeled' }', as the Pie-Chart slices is not displaying the percentage for small values.
Try passing the following to your options:
pieSliceTextStyle: {
color: 'white',
fontSize: '13',
top: 10,
left: 50,
position: 'start',
},
I have a column chart produced with the "classic" corechart package.
But, I don't understand how to put the column values as labels on top of each bar. (eg. 8.50 on the very first).
Here's my code:
google.charts.load('current', {packages: ['corechart']});
google.charts.setOnLoadCallback(drawChart);
function drawChart() {
var data = google.visualization.arrayToDataTable([
[
"",
"Hamburgers",
"Pizzas",
"Flutes",
"Wraps"
],
["29-04-2017", 8.50, 8.2, 8.4, 5.5],
["13-05-2017", 8.60, 8.32, 8.53, 5.67],
["12-06-2017", 8.30, 8.72, 8.13, 5.37],
["23-08-2017", 8.50, 8.22, 8.43, 5.57]
]);
var options = {
chart: {
title: ' ',
animation: {
duration: 2000,
easing: "out",
startup: true
}
},
legend: {position:'top'},
hAxis: { format: "date" },
vAxis: {
format: 'decimal',
viewWindow:{
max:10,
min:0
}
},
height: 400,
bars: 'vertical',
colors: ["#0F5470", "#8EA3A4", "#3EB8BC", "#98D4F2"]
};
var chart = new google.visualization.ColumnChart(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"></div>
you can use the annotation column role to add labels to the bars
the annotation column should follow the series column in the data table
see following working snippet
here, a DataView is used to add annotation columns for each series...
google.charts.load('current', {
callback: drawChart,
packages: ['corechart']
});
function drawChart() {
var data = google.visualization.arrayToDataTable([
[
"",
"Hamburgers",
"Pizzas",
"Flutes",
"Wraps"
],
["29-04-2017", 8.50, 8.2, 8.4, 5.5],
["13-05-2017", 8.60, 8.32, 8.53, 5.67],
["12-06-2017", 8.30, 8.72, 8.13, 5.37],
["23-08-2017", 8.50, 8.22, 8.43, 5.57]
]);
// build view
var viewColumns = [0];
$.each(new Array(data.getNumberOfColumns() - 1), function (index) {
viewColumns.push(index + 1);
viewColumns.push({
calc: function (dt, row) {
return dt.getFormattedValue(row, index + 1);
},
role: 'annotation',
type: 'string'
});
});
var view = new google.visualization.DataView(data);
view.setColumns(viewColumns);
var options = {
chart: {
title: ' ',
animation: {
duration: 2000,
easing: "out",
startup: true
}
},
legend: {position:'top'},
hAxis: { format: "date" },
vAxis: {
format: 'decimal',
viewWindow:{
max:10,
min:0
}
},
height: 400,
bars: 'vertical',
colors: ["#0F5470", "#8EA3A4", "#3EB8BC", "#98D4F2"]
};
var chart = new google.visualization.ColumnChart(document.getElementById('chart_div'));
chart.draw(view, options);
$(window).resize(function() {
chart.draw(view, 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>
EDIT
if you know the number of columns in the data table,
then you don't need to build them dynamically
the setColumns method takes an array,
each entry in the array can be a column index --> 0
or an object, if using a calculated column...
{
calc: function (dt, row) {
return dt.getFormattedValue(row, 1);
},
role: 'annotation',
type: 'string'
}
in this case, we need to include the columns from the data table,
and a calculated column for each annotation column
see following working snippet...
google.charts.load('current', {
callback: drawChart,
packages: ['corechart']
});
function drawChart() {
var data = google.visualization.arrayToDataTable([
[
"",
"Hamburgers",
"Pizzas",
"Flutes",
"Wraps"
],
["29-04-2017", 8.50, 8.2, 8.4, 5.5],
["13-05-2017", 8.60, 8.32, 8.53, 5.67],
["12-06-2017", 8.30, 8.72, 8.13, 5.37],
["23-08-2017", 8.50, 8.22, 8.43, 5.57]
]);
// build view
var view = new google.visualization.DataView(data);
view.setColumns([
0, // <-- x-axis column index
1, // <-- first y-axis column index
{ // annotation column for first y-axis column
calc: function (dt, row) {
return dt.getFormattedValue(row, 1); // get formatted value from first y-axis column
},
role: 'annotation',
type: 'string'
},
2, // <-- second y-axis column index
{ // annotation column for second y-axis column
calc: function (dt, row) {
return dt.getFormattedValue(row, 2); // get formatted value from second y-axis column
},
role: 'annotation',
type: 'string'
},
3,
{
calc: function (dt, row) {
return dt.getFormattedValue(row, 3);
},
role: 'annotation',
type: 'string'
},
4,
{
calc: function (dt, row) {
return dt.getFormattedValue(row, 4);
},
role: 'annotation',
type: 'string'
}
]);
var options = {
chart: {
title: ' ',
animation: {
duration: 2000,
easing: "out",
startup: true
}
},
legend: {position:'top'},
hAxis: { format: "date" },
vAxis: {
format: 'decimal',
viewWindow:{
max:10,
min:0
}
},
height: 400,
bars: 'vertical',
colors: ["#0F5470", "#8EA3A4", "#3EB8BC", "#98D4F2"]
};
var chart = new google.visualization.ColumnChart(document.getElementById('chart_div'));
chart.draw(view, options);
$(window).resize(function() {
chart.draw(view, 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>
NOTE
the reason you cannot build the columns dynamically using a regular for loop,
is because we're assigning the column index in an object
in this case, a reference is saved to i
{
calc: function (dt, row) {
return dt.getFormattedValue(row, i);
},
role: 'annotation',
type: 'string'
}
when the loop finishes and the columns are used in setColumns,
all of the columns reference i, which is the last value of the loop
to use the value of i during the loop, instead of a reference to a i
then the object being built has to be inside a closure, or function
which is why the $.each statement is used in the original answer
this creates a closure and the value of index is used,
rather than a reference to index
$.each(new Array(data.getNumberOfColumns() - 1), function (index) { // <-- this creates the closure...
viewColumns.push(index + 1);
viewColumns.push({
calc: function (dt, row) {
return dt.getFormattedValue(row, index + 1);
},
role: 'annotation',
type: 'string'
});
});
I'm fairly new to coding with google charts/javascript, and for some reason when I try to draw data from a spreadsheet I can't specify the range.I'm using a tiny example spreadsheet and it still won't work. My java code is below, and I've tried every url modification I could find. Using 'https://docs.google.com/spreadsheets/d/1BHeR6LetK5ztqvgIm53OpbNFjMttRICBBDR8j1yEAjg/edit#gid=0range=2:5'doesn't change the result.
Using 'https://docs.google.com/spreadsheets/d/1BHeR6LetK5ztqvgIm53OpbNFjMttRICBBDR8j1yEAjg/gviz/tq?range=2:5'won't generate a chart even though excluding the range will.
The whole java code is here, what am I doing wrong?:
google.charts.load('current', {
'packages': ['line', 'corechart', 'table']
});
google.charts.setOnLoadCallback(drawChart);
function drawChart() {
var queryString = encodeURIComponent('SELECT A, H, O, Q, R, U LIMIT 5 OFFSET 8');
var query = new google.visualization.Query(
'https://docs.google.com/spreadsheets/d/1BHeR6LetK5ztqvgIm53OpbNFjMttRICBBDR8j1yEAjg/edit#gid=0range=A1:C2' + queryString);
query.send(handleSampleDataQueryResponse);
}
function handleSampleDataQueryResponse(response) {
if (response.isError()) {
alert('Error in query: ' + response.getMessage() + ' ' + response.getDetailedMessage());
return;
}
var data = response.getDataTable();
var materialOptions = {
chart: {
title: 'Example Data'
},
width: 900,
height: 500,
series: {
0: {
axis: 'Miles'
},
1: {
axis: 'Heartrate'
}
},
axes: {
y: {
Miles: {
label: 'Miles Run'
},
Heartrate: {
label: 'Heart rate(BPM)'
}
}
}
};
function drawMaterialChart() {
var chartDiv = document.getElementById('chart_div');
var materialChart = new google.charts.Line(chartDiv);
materialChart.draw(data, materialOptions);
}
drawMaterialChart();
}
parameters on the url need to separated by --> &
e.g. --> .../edit#gid=0&range=A1:C2
see following working snippet...
google.charts.load('current', {
callback: drawChart,
packages: ['line', 'corechart', 'table']
});
function drawChart() {
var query = new google.visualization.Query(
'https://docs.google.com/spreadsheets/d/1BHeR6LetK5ztqvgIm53OpbNFjMttRICBBDR8j1yEAjg/edit#gid=0&range=A1:C2');
query.send(handleSampleDataQueryResponse);
}
function handleSampleDataQueryResponse(response) {
if (response.isError()) {
alert('Error in query: ' + response.getMessage() + ' ' + response.getDetailedMessage());
return;
}
var data = response.getDataTable();
var materialOptions = {
chart: {
title: 'Example Data'
},
width: 900,
height: 500,
series: {
0: {
axis: 'Miles'
},
1: {
axis: 'Heartrate'
}
},
axes: {
y: {
Miles: {
label: 'Miles Run'
},
Heartrate: {
label: 'Heart rate(BPM)'
}
}
}
};
function drawMaterialChart() {
var chartDiv = document.getElementById('chart_div');
var materialChart = new google.charts.Line(chartDiv);
materialChart.draw(data, materialOptions);
}
drawMaterialChart();
}
<script src="https://www.gstatic.com/charts/loader.js"></script>
<div id="chart_div"></div>
note: if you're going to include a query string,
the select statement needs to be within the range set on the url
currently, range only includes columns A thru C
but sql has H, O, Q, R, U
EDIT
drop the range and try using method setQuery to use a SQL statement...
query.setQuery('SELECT A, B, C LIMIT 3');
see following working snippet...
google.charts.load('current', {
callback: drawChart,
packages: ['line', 'corechart', 'table']
});
function drawChart() {
var query = new google.visualization.Query(
'https://docs.google.com/spreadsheets/d/1BHeR6LetK5ztqvgIm53OpbNFjMttRICBBDR8j1yEAjg/edit#gid=0');
query.setQuery('SELECT A, B, C LIMIT 3');
query.send(handleSampleDataQueryResponse);
}
function handleSampleDataQueryResponse(response) {
if (response.isError()) {
alert('Error in query: ' + response.getMessage() + ' ' + response.getDetailedMessage());
return;
}
var data = response.getDataTable();
var materialOptions = {
chart: {
title: 'Example Data'
},
width: 900,
height: 500,
series: {
0: {
axis: 'Miles'
},
1: {
axis: 'Heartrate'
}
},
axes: {
y: {
Miles: {
label: 'Miles Run'
},
Heartrate: {
label: 'Heart rate(BPM)'
}
}
}
};
function drawMaterialChart() {
var chartDiv = document.getElementById('chart_div');
var materialChart = new google.charts.Line(chartDiv);
materialChart.draw(data, materialOptions);
}
drawMaterialChart();
}
<script src="https://www.gstatic.com/charts/loader.js"></script>
<div id="chart_div"></div>
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>
I'm trying to pass some data from the Google trends to a Google chart but i'm getting the Incompatible data table: Error: Table contains more columns than expected (Expecting 2 columns) error
I just assumed it would work automatically from one I query it into a chart rather than get an error. The code i'm getting an error with is:
google.charts.load('current', {'packages':['corechart']});
google.charts.setOnLoadCallback(drawChart);
var findTitle = $(".input-wrapper input").val();
function drawChart() {
console.log(findTitle);
var query = new google.visualization.Query('https://www.google.com/trends/fetchComponent?hl=en-US&q=battlefield%201&cid=GEO_MAP_0_0&export=3&w=500&h=300&gprop=youtube&date=today%201-m');
query.send(function (response) {
if (response.isError()) {
alert('Error in query: ' + response.getMessage() + ' - ' + response.getDetailedMessage());
return;
}
data = response.getDataTable();
var view = new google.visualization.DataView(data);
view.setColumns([{
calc: function (data, row) {
return data.getFormattedValue(row, 0);
},
type: 'string',
label: data.getColumnLabel(0)
}, 1]);
var chart = new google.visualization.GeoChart(document.getElementById('chart_region_top'));
chart.draw(view, {
chartArea: {
height: '80%',
width: '100%'
},
});
chart.draw(data, {
width: 1000,
height: 500,
title: 'Tag: Battlefield 1',
colors: ['#ff0000'],
backgroundColor: '#2D2D2D',
legendTextStyle: { color: '#FFF', position: 'bottom' },
titleTextStyle: { color: '#FFF' },
hAxis: {
textStyle: {color: '#FFF'},
gridlines: {color: '#FFF'}
},
vAxis: {
textStyle: {color: '#FFF'},
gridlines: {color: '#FFF'}
}
});
});
}
Any help into why i'm getting this error and a solution is greatly appreciated :)
since the GeoChart expects two columns,
use a DataView to extract the first two columns from the DataTable
also, need to load 'geochart' package, see following working snippet...
google.charts.load('current', {
callback: drawChart,
packages: ['geochart']
});
function drawChart() {
var query = new google.visualization.Query('https://www.google.com/trends/fetchComponent?hl=en-US&q=battlefield%201&cid=GEO_MAP_0_0&export=3&w=500&h=300&gprop=youtube&date=today%201-m');
query.send(function (response) {
if (response.isError()) {
alert('Error in query: ' + response.getMessage() + ' - ' + response.getDetailedMessage());
return;
}
var view = new google.visualization.DataView(response.getDataTable());
view.setColumns([0, 1]);
var chart = new google.visualization.GeoChart(document.getElementById('chart_div'));
chart.draw(view, {
legend: 'none'
});
});
}
<script src="https://www.gstatic.com/charts/loader.js"></script>
<div id="chart_div"></div>