I am using the Google Charts and i need to update a map that is already instantiated as a map worth actually want when you click the refresh button the data inside of a map.
Today I am doing in the following way:
var dataGraf = google.visualization.arrayToDataTable(parsVal);
var chart = document.getElementById('curve_chart');
chart.draw(dataGraf);
But nothing happens. For i instantiate my map i used the following commands:
google.charts.load('current', {'packages':['corechart']});
google.charts.setOnLoadCallback(drawChart);
function drawChart() {
var data = google.visualization.arrayToDataTable(parsVal);
var options = {
title: 'Membros x Visitantes',
curveType: 'function',
legend: { position: 'bottom' }
};
var chart = new google.visualization.LineChart(document.getElementById('curve_chart'));
chart.draw(data, options);
}
How can i do to update, just when I click the button. Remembering that my 'ataGraf' has my array with the new values.
I did a JsFiddle to illustrate my problem.
first...
google.charts.load & setOnLoadCallback should only be called once per page load
you can also include the callback in the load statement
next, by saving a reference to the original chart, you can animate from one dataset to another
on the button click, create data and call draw
also recommend not adding event handlers directly in html tags
see following working snippet, the data is "swapped" on each button click...
google.charts.load('current', {
callback: function () {
// draw first chart
var data = google.visualization.arrayToDataTable([
['Data', 'Membros', 'Visitantes'],
['1', 4, 6],
['2', 5, 7]
]);
var options = {
animation: {
startup: true,
duration: 1200,
easing: 'linear'
},
title: 'Membros x Visitantes',
curveType: 'function',
legend: { position: 'bottom' }
};
var chart = new google.visualization.LineChart(document.getElementById('curve_chart'));
chart.draw(data, options);
// draw same chart with new data on button click
var newData = null;
document.getElementById('chart_button').addEventListener('click', drawNewChart, false);
function drawNewChart() {
// switch between newData and data on each click
if (newData === null) {
newData = google.visualization.arrayToDataTable([
['Data', 'Membros', 'Visitantes'],
['1', 9, 2],
['2', 1, 7]
]);
chart.draw(newData, options);
} else {
chart.draw(data, options);
newData = null;
}
}
},
packages: ['corechart']
});
<script src="https://www.gstatic.com/charts/loader.js"></script>
<button id="chart_button">Atualizar gráficos</button>
<div id="curve_chart"></div>
Related
I am trying to create a function which will open a new window tab and display a chart for a set of values. I am able to get up this but for some reason, the new tab is opening up but no data is displayed in the page. Could you please suggest where I am going wrong.
function drawVisualization() {
var data = google.visualization.arrayToDataTable([
['Name', 'TimeTaken'],
['BookMark1', 10],
['BookMark2', 20],
['BookMark3', 10],
['BookMark4', 20],
['BookMark5', 30],
['BookMark6', 26]
]);
var options = {
title : 'Time Taken to Apply Each Bookmark',
vAxis: {title: 'Time_Seconds'},
hAxis: {title: 'Bookmark_Name'},
seriesType: 'bars',
series: {5: {type: 'line'}}
};
var w=window.open("");
var newNode = w.document.createElement('div');
newNode.setAttribute("Id", "chart_div");
newNode.setAttribute("style", "width: 2000px; height: 1000px;");
var chart = new google.visualization.ComboChart(document.getElementById("chart_div"));
chart.draw(data, options);
}
You are trying to find the node from the wrong document. This solution is working:
var w=window.open("");
w.document.body.innerHTML += '<div id="chart"></div>';
chart = new google.visualization.ColumnChart(w.document.getElementById("chart"));
chart.draw(dataTable, options);
I have seen a lot of answers on the web for this question but everybody have answered in a different way. They have answered with examples of code 90+ lines of code so it's hard to understand the method for applying formats. Can somebody please explain the method of applying formats in google charts and there are different methods for different types of charts? I need to apply the formats on bar charts and donut charts. I want to change format to currency and decimals.
google.charts.load("current", {packages:["corechart"]});
google.charts.setOnLoadCallback(drawChart);
function drawChart() {
var data = google.visualization.arrayToDataTable([
['Marketplaces', 'Number Of Orders','Value of Order'],
var chart = new google.visualization.PieChart(document.getElementById('sales_total_quantity'));
chart.draw(data, options);
}
in order to format the chart values, as shown when the bar or pie slice is hovered,
you need to apply a format to the data table.
you can use google's number formatter.
var patternCurrency = '$#,##0.00';
// format third column of data table
var formatCurrency = new google.visualization.NumberFormat({
pattern: patternCurrency
});
formatCurrency.format(data, 2);
if you also want the y-axis of the bar chart to show as currency,
you need to use config option --> vAxis.format
var optionsBar = {
// format y-axis
vAxis: {
format: patternCurrency
}
};
see following working snippet...
google.charts.load('current', {
packages: ['corechart']
}).then(function () {
var data = google.visualization.arrayToDataTable([
['Marketplaces', 'Number Of Orders', 'Value of Order'],
['A', 10, 100.11],
['B', 20, 200.22],
['C', 30, 300.33],
]);
var patternCurrency = '$#,##0.00';
// format third column of data table
var formatCurrency = new google.visualization.NumberFormat({
pattern: patternCurrency
});
formatCurrency.format(data, 2);
var optionsBar = {
tooltip: {
trigger: 'both'
},
// format y-axis
vAxis: {
format: patternCurrency
}
};
var chartBar = new google.visualization.ColumnChart(document.getElementById('chart-bar'));
google.visualization.events.addListener(chartBar, 'ready', function () {
// show tooltip
chartBar.setSelection([{column: 2, row: 0}]);
});
chartBar.draw(data, optionsBar);
var optionsPie = {
height: 300,
pieHole: 0.2
};
var chartPie = new google.visualization.PieChart(document.getElementById('chart-pie'));
chartPie.draw(data, optionsPie);
});
<script src="https://www.gstatic.com/charts/loader.js"></script>
<div id="chart-bar"></div>
<div id="chart-pie"></div>
I have different countries which I get with json and add to google charts. Each country has a link to a specific site. It works for me. But the name of the tooltip/label is a link. How can I remove the link in the tooltip and add the name of the country?
And how can change the country border color to white?
thx in advance.
HTML
<div id="visualization"></div>
JavaScript
google.load('visualization', '1', {'packages': ['geochart']});
google.setOnLoadCallback(drawVisualization);
function drawVisualization() {
var data = new google.visualization.arrayToDataTable([
['Country','Link',],
['Canada','http://www.google.ca'],
['Russia','http://www.bbc.com'],
['Australia','http://www.nytimes.com'],
]);
var options = {
colorAxis: {colors: 'white'},
backgroundColor: '#81d4fa',
datalessRegionColor: '#f8bbd0',
defaultColor: 'black',
displayMode:'regions',
tooltip: {textStyle: {color: '#FF0000'}, trigger:'focus',isHtml: true},
legend:'none',
height:300,
width:400
};
var chart = new google.visualization.GeoChart(document.getElementById('visualization'));
google.visualization.events.addListener(chart, 'select', myClickHandler);
chart.draw(data, options);
function myClickHandler(){
var link = data.getValue(chart.getSelection()[0]['row'],1);
// Change the current site
location.href = link;
}
}
first, recommend not using jsapi to load the library
according to the release notes...
The version of Google Charts that remains available via the jsapi loader is no longer being updated consistently. Please use the new gstatic loader from now on.
<script src="https://www.gstatic.com/charts/loader.js"></script>
this will only change the load statement, to...
google.charts.load('current', {
callback: drawVisualization,
packages:['geochart']
});
(the callback can be added to the load statement as well)
next, according to the data format for regions mode,
the second column should be a number (not a string / link)
but since the link is needed for the click handler, use a DataView to hide the column from the chart
^ this will fix the tooltip -- adding the name of the country instead of the link
the number column drives the shading of the country, according to the colorAxis
if no number is provided, as in the question, then colorAxis will have no effect
last, there are no standard options to control the country border
see following working snippet...
google.charts.load('current', {
callback: drawVisualization,
packages:['geochart']
});
function drawVisualization() {
var data = google.visualization.arrayToDataTable([
['Country','Link',],
['Canada','http://www.google.ca'],
['Russia','http://www.bbc.com'],
['Australia','http://www.nytimes.com'],
]);
var view = new google.visualization.DataView(data);
view.hideColumns([1]);
var options = {
backgroundColor: '#81d4fa',
datalessRegionColor: '#f8bbd0',
defaultColor: 'black',
displayMode: 'regions',
tooltip: {textStyle: {color: '#FF0000'}, trigger:'focus',isHtml: true},
legend: 'none',
height:300,
width:400
};
var chart = new google.visualization.GeoChart(document.getElementById('visualization'));
google.visualization.events.addListener(chart, 'select', myClickHandler);
chart.draw(view, options);
function myClickHandler(){
var selection = chart.getSelection();
if (selection.length > 0) {
var link = data.getValue(selection[0].row, 1);
window.open(link, '_blank');
}
}
}
<script src="https://www.gstatic.com/charts/loader.js"></script>
<div id="visualization"></div>
I'm trying to use the tooltip.trigger = 'selection' and setSelection([{row:4,column:null}]), but the tooltip doesn't show up automatically. Only when you click on another tooltip.
Here's a jsfiddle showing the problem.
Any ideas what I can try?
Thanks!
I ended up just using annotations. Though I would definitely be interested in the tooltips if anyone figures out a way.
jsfiddle
var gmapData = [[{"label":"Date","type":"date"},"One",{"role":"annotation","type":"string"},"Two",{"role":"annotation","type":"string"},"Three",{"role":"annotation","type":"string"}],["Date(2012, 3, 26)",412,null,278,null,149,null],["Date(2012, 3, 27)",410,null,272,null,147,null],["Date(2012, 3, 30)",414,null,280,null,146,null],["Date(2012, 4, 1)",406,"$406",268,"$268",141,"$141"]];
drawChart();
function drawChart() {
var data = window.data = google.visualization.arrayToDataTable(gmapData);
// apply a tooltip formatting
var formatter = new google.visualization.NumberFormat({pattern: '$#,###'});
var cols = (gmapData[0].length-1) / 2;
x = cols;
// apply a tooltip formatting
while ((--x) >= 0)
formatter.format(data, x*2+1);
var options = {
title: 'Number Watch',
legend: { position: 'bottom' },
interpolateNulls: true,
curveType: 'function',
selectionMode: 'single',
tooltip: {trigger: 'focus'},
focusTarget: 'category',
annotations: {
textStyle: {
fontSize: 18
}
},
vAxis: {format: '$#,###'},
width: 400,
height: 300
};
var chart = window.chart = new google.visualization.LineChart(document.getElementById('num_watch'));
chart.draw(data, options);
}
github issue reply:
Hi,
This is a known bug with focusTarget: 'category'. That particular option uses the mouse position as a signal for how to position the tooltip, and so programmatic selection won't trigger a tooltip to display.
To circumvent this issue, you could use multiple selection on the first load. Here's an example of this, along with a reset that changes the focusTarget back to 'category' at the first opportunity: http://jsfiddle.net/b1kt6mrL/
jsfiddle:
// ..... all previous code, not with the annotations
chart.draw(data, options);
chart.setSelection([{row:4, column:1}, {row:4, column:2}, {row:4, column:3}]);
google.visualization.events.addOneTimeListener(chart, 'onmouseover', function() {
var selection = chart.getSelection();
options.focusTarget = 'category';
options.selectionMode = 'single';
google.visualization.events.addOneTimeListener(chart, 'ready', function() {
chart.setSelection(selection);
});
chart.draw(data, options);
});
if i am passing empty data for chart binding it shows 'no data' i need to change the text 'no data' to some other word.
google.load("visualization", "1", {packages:["corechart"]});
google.setOnLoadCallback(drawChart);
function drawChart() {
var data = google.visualization.arrayToDataTable([
['Task', 'Hours per Day']
]);
var options = {
title: 'My Daily Activities'
};
var chart = new google.visualization.PieChart(document.getElementById('piechart'));
chart.draw(data, options);
}
You can do it manually:
if(data.getNumberOfRows() == 0){
$("#piechart").append("Sorry, not info available")
}else{
var chart = new google.visualization.PieChart(document.getElementById('piechart'));
chart.draw(data, options);
}
As juvian said data.getNuberOfRows() is in the plugin, so if you are good with jquery you can even replace " $("#piechart").append("Sorry, not info available")" with an image for example
if (data.getNumberOfRows() == 0) {
$("#someimage").attr("src","url-to-image");//Or any jquery dom manipulation here
} else {
var chart = new
google.visualization.PieChart(document.getElementById('piechart'));
chart.draw(data, options);
}
You could replace text in SVG after chart drawing
chart.draw(data, options);
if (data.getNumberOfRows() == 0) {
$("#piechart").find("svg text").text("Your text")
}
I found a solution on newbedev.com and here is how I had to modify it.
var data = [ [ 'Label', 'Count' ] ];
var options = { sliceVisibilityThreshold: 0 };
// add your data to the array.
if (data.length == 1) {
data.push(['', 0]);
options.sliceVisibilityThreshold = 0.01;
}
var chartData = google.visualization.arrayToDataTable(this.data);
var chart = new google.visualization.PieChart(document.getElementById('piechart'));
chart.draw(chartData, options);
The sliceVisibilityThreshold determines when a slice will be visible on its own within the chart. If it is set to zero, then all slices show. Ensuring the threshold is greater than zero and having at least one entry set to zero is the key. The single slice will not be visible, the legend will not display, and the "No data" message is gone.