How to update options of an existing google chart in a wrapper - javascript

How can I change / update an existing google chart's options. Let's say I want to with a click of a button apply these options to an existing chart:
var options = {
width: 400,
height: 240,
title: 'Toppings I Like On My Pizza',
colors: ['#e0440e', '#e6693e', '#ec8f6e', '#f3b49f', '#f6c7b6']
};
and yes, I do know that you can do al this with the chartEditor but that solution will not work for me in this case

If your chart is a ChartWrapperin a Dashboard, you may be inspired by
https://developers.google.com/chart/interactive/docs/gallery/controls#8-programmatic-changes-after-draw
google.charts.load('current', {
'packages': ['corechart', 'controls']
});
google.charts.setOnLoadCallback(drawStuff);
function drawStuff() {
var dashboard = new google.visualization.Dashboard(
document.getElementById('programmatic_dashboard_div'));
var programmaticSlider = new google.visualization.ControlWrapper({
'controlType': 'NumberRangeFilter',
'containerId': 'programmatic_control_div',
'options': {
'filterColumnLabel': 'Donuts eaten',
'ui': {
'labelStacking': 'vertical'
}
}
});
// We omit "var" so that programmaticChart is visible to changeOptions().
programmaticChart = new google.visualization.ChartWrapper({
'chartType': 'PieChart',
'containerId': 'programmatic_chart_div',
'options': {
'width': 300,
'height': 300,
'legend': 'none',
'chartArea': {
'left': 15,
'top': 15,
'right': 0,
'bottom': 0
},
'pieSliceText': 'value'
}
});
var data = google.visualization.arrayToDataTable([
['Name', 'Donuts eaten'],
['Michael', 5],
['Elisa', 7],
['Robert', 3],
['John', 2],
['Jessica', 6],
['Aaron', 1],
['Margareth', 8]
]);
dashboard.bind(programmaticSlider, programmaticChart);
dashboard.draw(data);
}
<script type="text/javascript" src="https://www.gstatic.com/charts/loader.js"></script>
<button onclick="changeOptions();">
Change Options
</button>
<script type="text/javascript">
function changeOptions() {
programmaticChart.setOptions({
width: 400,
height: 240,
title: 'Toppings I Like On My Pizza',
colors: ['#e0440e', '#e6693e', '#ec8f6e', '#f3b49f', '#f6c7b6']
});
programmaticChart.draw();
}
</script>
<div id="programmatic_dashboard_div">
<div id="programmatic_control_div"></div>
<div id="programmatic_chart_div"></div>
</div>

Call the draw() function with the new options
google.charts.load('current', {
packages: ['corechart', 'bar']
});
google.charts.setOnLoadCallback(drawBasic);
var changeOptions; // global variable for callback function
function drawBasic() {
var data = new google.visualization.DataTable();
data.addColumn('string', 'X');
data.addColumn('number', 'Quantity');
data.addRows([
['one',5],
['two',15],
['three',8]
]);
var options = {
title: 'Original Title',
};
var chart = new google.visualization.ColumnChart(
document.getElementById('chart_div'));
chart.draw(data, options);
// function to change options on button click
changeOptions = function() {
// define new options
options.width = 200;
options.height = 200;
options.title = 'Toppings I Like On My Pizza';
options.colors = ['#e0440e', '#e6693e', '#ec8f6e', '#f3b49f', '#f6c7b6'];
// call draw() with new options
chart.draw(data, options);
}
}
<script src="//www.gstatic.com/charts/loader.js"></script>
<button onclick="changeOptions();">change options</button>
<div id="chart_div"></div>

Related

Loop trough JSON with Ajax and pass value to Google Chart

I have the following Javascript code:
<html>
<head>
<script type="text/javascript" src="https://www.gstatic.com/charts/loader.js"></script>
<script type="text/javascript" src="https://www.google.com/jsapi"></script>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.7.2/jquery.min.js"></script>
<script type="text/javascript">
google.charts.load('current', {'packages':['controls']});
google.charts.setOnLoadCallback(drawChart);
function drawChart() {
var countryPicker = new google.visualization.ControlWrapper({
'controlType': 'CategoryFilter',
'containerId': 'control2',
'options': {
'filterColumnLabel': 'Targets',
title: 'Company Performance',
curveType: 'function',
legend: { position: 'bottom' },
'ui': {
'allowTyping': true,
'allowMultiple': false,
'allowNone': false,
}
},
'state': {
selectedValues: ['1970']
}
});
var jsonvalues = $.getJSON("http://localhost:5000/data", function(results) {
$.each(results, function(index) {
alert(results[index].key[1]);
});
});
$
var data = google.visualization.arrayToDataTable([
['Year','Targets', 'Total targets'],
{% for info in jsonvalues %}
['{{info['key'][1]|safe}}','{{info['key'][0]|safe}}', parseInt('{{info['value']|safe}}')],
{% endfor %}
]);
var barChart = new google.visualization.ChartWrapper({
'chartType': 'LineChart',
'containerId': 'curve_chart',
'options': {
'width': 800,
'height': 600,
},
'view': {
'columns': [0, 2]
}
});
var dash = new google.visualization.Dashboard(document.getElementById('dashboard'));
dash.bind(countryPicker, [barChart]);
dash.draw(data);
}
</script>
</head>
<body>
<div id="control2"></div>
<div id="curve_chart" style="width: 1920px; height: 1000px"></div>
</body>
</html>
What I am trying to achieve is to pass the getJSON data that I retrieve with the Ajax call from http://localhost:5000/data to the Google Chart.
I tried a lot of things but so far I am stuck and don't really know how to achieve what I want. I just inserted the alert aspect as test to see if this returns the data. The alert gives me back the JSON data that I am requesting, so that's fine.
MY JSON Data looks as follow:
[
{
key: [
"Abortion Related",
1977
],
value: 4
},
{
key: [
"Abortion Related",
1978
],
value: 6
}
]
Getting back to the question I had yesterday, solved it with the following working code:
<html>
<head>
<script type="text/javascript" src="https://www.gstatic.com/charts/loader.js"></script>
<script type="text/javascript" src="https://www.google.com/jsapi"></script>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.7.2/jquery.min.js"></script>
<script type="text/javascript">
google.charts.load('current', {'packages':['controls']});
google.charts.setOnLoadCallback(drawChart);
function drawChart() {
var countryPicker = new google.visualization.ControlWrapper({
'controlType': 'CategoryFilter',
'containerId': 'control2',
'options': {
'filterColumnLabel': 'Targets',
title: 'Company Performance',
curveType: 'function',
legend: { position: 'bottom' },
'ui': {
'allowTyping': true,
'allowMultiple': false,
'allowNone': false,
}
},
'state': {
selectedValues: ['1970']
}
});
function updateDiv() {
$(document).ready(function(){
var data = new google.visualization.DataTable();
data.addColumn('number', 'Year');
data.addColumn('string', 'Targets');
data.addColumn('number', 'Total Targets');
values = new Array;
$.getJSON("http://localhost:5000/data", function(results)
{
$.each(results, function(index)
{
values.push([results[index].key[1],results[index].key[0],results[index].value]);
});
data.addRows(values);
var barChart = new google.visualization.ChartWrapper({
'chartType': 'LineChart',
'containerId': 'curve_chart',
'options': {
'width': 800,
'height': 600,
},
'view': {
'columns': [0, 2]
}
});
var dash = new google.visualization.Dashboard(document.getElementById('dashboard'));
dash.bind(countryPicker, [barChart]);
dash.draw(data);
});
}); } setInterval(updateDiv, 5000)
}
</script>
</head>
<body>
<div id="control2"></div>
<div id="curve_chart" style="width: 1920px; height: 1000px"></div>
</body>
</html>
First I changed from arrayToDatatable to DataTable. After that I declared the columns and
the type of data with data.addColumn. Then I moved the getJSONwithin the `var data. And that did the trick for me. More information can be found over here: https://developers.google.com/chart/interactive/docs/reference

How to get DatatTable in Google Charts

I am trying to use Google Dashboard, Charts and Wrapper class in my website. I wrote a simple test app for it which I bring it below;
<html>
<head>
<!--Load the AJAX API-->
<script type="text/javascript" src="https://www.gstatic.com/charts/loader.js"></script>
<script type="text/javascript">
// Load the Visualization API and the controls package.
google.charts.load('current', {'packages':['corechart', 'controls','charteditor']});
// Set a callback to run when the Google Visualization API is loaded.
google.charts.setOnLoadCallback(drawDashboard);
// Callback that creates and populates a data table,
// instantiates a dashboard, a range slider and a pie chart,
// passes in the data and draws it.
function drawDashboard() {
// Create our data table.
var data = google.visualization.arrayToDataTable([
['Name', 'Donuts eaten'],
['Michael' , 5],
['Elisa', 7],
['Robert', 3],
['John', 2],
['Jessica', 6],
['Aaron', 1],
['Margareth', 8]
]);
// Create a dashboard.
var dashboard = new google.visualization.Dashboard(
document.getElementById('dashboard_div'));
// Create a range slider, passing some options
var donutRangeSlider = new google.visualization.ControlWrapper({
'controlType': 'NumberRangeFilter',
'containerId': 'filter_div',
'options': {
'filterColumnLabel': 'Donuts eaten'
}
});
// Create a pie chart, passing some options
var wrapper = new google.visualization.ChartWrapper({
'chartType': 'PieChart',
'containerId': 'chart_div',
'dataTable': data,
'options': {
'width': 300,
'height': 300,
'pieSliceText': 'value',
'legend': 'right'
}
});
var chartEditor = new google.visualization.ChartEditor();
google.visualization.events.addListener(chartEditor, 'ok', redrawChart);
// On "OK" save the chart to a <div> on the page.
function redrawChart(){
chartEditor.getChartWrapper().draw(document.getElementById('chart_div'));
dashboard.bind(donutRangeSlider, chartEditor.getChartWrapper());
}
// Establish dependencies, declaring that 'filter' drives 'pieChart',
// so that the pie chart will only display entries that are let through
// given the chosen slider range.
dashboard.bind(donutRangeSlider, wrapper);
// Draw the dashboard.
dashboard.draw(data);
var button = document.createElement('button');
button.textContent = "Edit me";
button.onclick = () => chartEditor.openDialog(wrapper, {});
document.body.appendChild(button);
setInterval(updateChart, 5000);
function updateChart()
{
let rand = Math.floor(Math.random()*10);
/************* THE FOLLOWING TWO LINES IS WORKING ****************************/
data.addRow(['Reza' + rand, rand]);
dashboard.draw(data);
/************* THE FOLLOWING TWO LINES IS NOT WORKING ****************************/
//wrapper.getDataTable().addRow(['Reza' + rand, rand]);
//dashboard.draw(wrapper.getDataTable());
}
}
</script>
</head>
<body>
<!--Div that will hold the dashboard-->
<div id="dashboard_div">
<!--Divs that will hold each control and chart-->
<div id="filter_div"></div>
<div id="chart_div"></div>
</div>
</body>
</html>
My problem is that the "getDataTable" function of my chart wrapper does not have a "addRow" function. It seems that it returns a DataView instead of DataTable. I don't want to keep a reference of my data because it should be in the wrapper! Anyway, Any help would be welcomed.
when you draw the dashboard, it appears to override the data table on the wrapper with a data view
this can easily be changed back to a normal data table using method --> toDataTable()
var wrapperData = wrapper.getDataTable().toDataTable();
wrapperData.addRow(['Reza' + rand, rand]);
dashboard.draw(wrapperData);
see following working snippet...
google.charts.load('current', {
packages: ['corechart', 'controls', 'charteditor']
}).then(drawDashboard);
function drawDashboard() {
var data = google.visualization.arrayToDataTable([
['Name', 'Donuts eaten'],
['Michael' , 5],
['Elisa', 7],
['Robert', 3],
['John', 2],
['Jessica', 6],
['Aaron', 1],
['Margareth', 8]
]);
var dashboard = new google.visualization.Dashboard(
document.getElementById('dashboard_div')
);
var donutRangeSlider = new google.visualization.ControlWrapper({
controlType: 'NumberRangeFilter',
containerId: 'filter_div',
options: {
filterColumnLabel: 'Donuts eaten'
}
});
var wrapper = new google.visualization.ChartWrapper({
chartType: 'PieChart',
containerId: 'chart_div',
options: {
width: 300,
height: 300,
pieSliceText: 'value',
legend: 'right'
}
});
var chartEditor = new google.visualization.ChartEditor();
google.visualization.events.addListener(chartEditor, 'ok', redrawChart);
function redrawChart(){
chartEditor.getChartWrapper().draw(document.getElementById('chart_div'));
dashboard.bind(donutRangeSlider, chartEditor.getChartWrapper());
}
dashboard.bind(donutRangeSlider, wrapper);
dashboard.draw(data);
var button = document.createElement('button');
button.textContent = "Edit me";
button.onclick = () => chartEditor.openDialog(wrapper, {});
document.body.appendChild(button);
setInterval(updateChart, 5000);
function updateChart() {
let rand = Math.floor(Math.random()*10);
var wrapperData = wrapper.getDataTable().toDataTable();
wrapperData.addRow(['Reza' + rand, rand]);
dashboard.draw(wrapperData);
}
}
<script src="https://www.gstatic.com/charts/loader.js"></script>
<div id="dashboard_div">
<div id="filter_div"></div>
<div id="chart_div"></div>
</div>

Google Timeline Visualization doesn't change series row height on slider interaction

So I've got a timeline with data in it that can be concurrent...
When I move the ChartRangeSlider to a different timeframe, some of the timeline bars will either disappear or show because there is nothing happening in the timeframe that is active.
These is how the timeline and the range slider are set up. I don't have any event listeners running...
// Configure range slider
var timelineRangeSlider = new google.visualization.ControlWrapper({
'controlType': 'ChartRangeFilter',
'containerId': 'timeline-filter',
'state':
{
'range':
{
'start': currentTime,
'end': fourWeek
}
},
'options':
{
'filterColumnIndex': 4,
'ui':
{
'chartType': 'ScatterChart',
'chartOptions':
{
'width': '100%',
'height': '50',
'chartArea':
{
'width': '80%', // make sure this is the same for the chart and control so the axes align right
'height': '80%'
},
'hAxis':
{
'baselineColor': 'none'
}
},
'chartView':
{
'columns': [4,6]
}
}
}
});
// Configure timeline
var timeline = new google.visualization.ChartWrapper({
'chartType': 'Timeline',
'containerId': 'timeline-chart',
'options':
{
'timeline':
{
'showBarLabels': false
},
'width': '100%',
'height': '325',
'tooltip':
{
'isHtml': true
},
'chartArea':
{
'width': '80%', // make sure this is the same for the chart and control so the axes align right
'height': '80%'
},
},
'view':
{
'columns': [0,1,2,3,4,5]
}
});
How can I stop this from happening, and have each of the four separate rows (one for each series) have a static height that won't change when I interact with the range slider?
to display the same number of rows, regardless of the filter settings,
replace the rows removed by the filter with "blank" rows,
doing so will require some manipulation
if you're using a dashboard to bind the chart and filter,
it will probably be easier to draw each independently
listen for the 'statechange' event on the filter,
to know when to re-draw the chart
use a data view to exclude the rows hidden by the filter,
add blank rows in their place
use the colors option on the timeline to set blank rows to 'transparent'
also use a blank tooltip for these rows
see following working snippet, for an example of how this could be accomplished...
google.charts.load('current', {
packages: ['controls', 'timeline']
}).then(function () {
var dataTable = google.visualization.arrayToDataTable([
['Row Label', 'Bar Label', {role: 'tooltip', type: 'string', p: {html: true}}, 'Start', 'End', 'Scatter', 'Data / Blank'],
['A', 'Series 0', null, new Date(2018, 1, 1), new Date(2018, 1, 28), 1, 'data'],
['B', 'Series 1', null, new Date(2018, 4, 1), new Date(2018, 4, 31), 1, 'data'],
['C', 'Series 2', null, new Date(2018, 7, 1), new Date(2018, 7, 31), 1, 'data'],
['D', 'Series 3', null, new Date(2018, 10, 1), new Date(2018, 10, 30), 1, 'data']
]);
var blankTooltip = '<div class="hidden"></div>';
var colorPallette = ['cyan', 'magenta', 'lime', 'yellow'];
var dateRange = {
start: dataTable.getColumnRange(3),
end: dataTable.getColumnRange(4)
};
// Configure range slider
var timelineRangeSlider = new google.visualization.ControlWrapper({
controlType: 'ChartRangeFilter',
containerId: 'timeline-filter',
dataTable: dataTable,
state: {
range: {
start: dateRange.start.min,
end: dateRange.end.max
}
},
options: {
filterColumnIndex: 3,
ui: {
chartType: 'ScatterChart',
chartOptions: {
width: '100%',
height: '50',
chartArea: {
width: '80%',
height: '80%'
},
hAxis: {
baselineColor: 'none'
}
},
chartView: {
columns: [3,5]
}
}
}
});
google.visualization.events.addListener(timelineRangeSlider, 'statechange', function (props) {
// filter state
var state = timelineRangeSlider.getState();
// wait until statechange has finished
if (!props.inProgress) {
// delete previously added blank rows
var blankRows = dataTable.getFilteredRows([{
column: 6,
value: 'blank'
}]);
var i = blankRows.length;
while (i--) {
dataTable.removeRow(blankRows[i]);
}
// add blank rows for non-visible rows
var blankRows = [];
var timelineColors = [];
var visibleRows = dataTable.getFilteredRows([{
column: 3,
minValue: state.range.start
}, {
column: 4,
maxValue: state.range.end
}]);
for (var i = 0; i < dataTable.getNumberOfRows(); i++) {
if (visibleRows.indexOf(i) === -1) {
blankRows.push([
dataTable.getValue(i, 0),
dataTable.getValue(i, 1),
blankTooltip,
state.range.start,
state.range.start,
1,
'blank'
]);
timelineColors.push('transparent');
} else {
timelineColors.push(colorPallette[i]);
}
}
// build timeline view rows
var lastRowIndex = dataTable.addRows(blankRows);
var i = blankRows.length;
while (i--) {
visibleRows.push((lastRowIndex - i));
}
// re-config timeline
var timelineView = new google.visualization.DataView(dataTable);
timelineView.setRows(visibleRows);
timelineView = timelineView.toDataTable();
timelineView.sort([{column: 0}]);
timeline.setDataTable(timelineView);
timeline.setOption('colors', timelineColors);
timeline.draw();
}
});
timelineRangeSlider.draw();
// Configure timeline
var timeline = new google.visualization.ChartWrapper({
chartType: 'Timeline',
containerId: 'timeline-chart',
dataTable: dataTable,
options: {
colors: colorPallette,
timeline: {
showBarLabels: false
},
width: '100%',
height: '325',
tooltip: {
isHtml: true
},
chartArea: {
width: '80%',
height: '80%'
}
},
view: {
columns: [0,1,2,3,4]
}
});
timeline.draw();
});
.hidden {
display: none;
visibility: hidden;
}
<script src="https://www.gstatic.com/charts/loader.js"></script>
<div id="dashboard_div">
<div id="timeline-filter"></div>
<div id="timeline-chart"></div>
</div>

Google chart - role: annotation in candlestick bar [duplicate]

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 - switch between table and chart view

There was a similar question (Google Charts: Switching between Line and Column charts) about switching between line and columns charts, but it doesn't seem to work for tables.
I have a line chart that I want to change into table and back... the only way i see this happening is by redeclaring a table similar to...
function changeIntoTable() {
var table = new google.visualization.Table(document.getElementById('dashboard_div'));
table.draw(data, {showRowNumber: true, width: '100%', height: '100%'});
}
function changeIntoChart() {
// Create a dashboard.
var dashboard = new google.visualization.Dashboard(document.getElementById('dashboard_div'));
// Create a line chart, passing some options
var lineChart = new google.visualization.ChartWrapper({
'chartType': 'LineChart',
'containerId': 'chart_div',
'options': {
backgroundColor: { fill:'transparent' },
'legend': 'right',
'pointSize': 5,
crosshair: { trigger: 'both' }, // Display crosshairs on focus and selection.
hAxis: {
title: 'Time'
},
vAxis: {
title: 'Value'
}
}
});
dashboard.bind(lineChart);
dashboard.draw(data);
}
So, i am wondering if there is a simpler solution?
What you have should work fine but...
You could take advantage of the ChartWrapper Class which can draw any chart type...
Here's an example, click the button to switch the chart...
google.charts.load('current', {
packages: ['corechart', 'table'],
callback: initChart
});
function initChart() {
var button;
var chart;
var data;
var showChart = 'Table';
data = google.visualization.arrayToDataTable([
['Year', 'Sales', 'Expenses'],
['2004', 1000, 400],
['2005', 1170, 460],
['2006', 660, 1120],
['2007', 1030, 540]
]);
chart = new google.visualization.ChartWrapper({
containerId: 'chart_div',
dataTable: data
});
button = document.getElementById('btnSwitch');
button.addEventListener('click', switchChart, false);
// draw initial chart
switchChart();
function switchChart() {
button.value = showChart;
showChart = (showChart === 'Table') ? 'LineChart' : 'Table';
drawChart(showChart);
}
function drawChart(chartType) {
chart.setChartType(chartType);
chart.setOptions(getOptions(chartType));
chart.draw();
}
function getOptions(chartType) {
var options;
switch (chartType) {
case 'LineChart':
options = {
backgroundColor: {
fill:'transparent'
},
legend: 'right',
pointSize: 5,
crosshair: {
trigger: 'both'
},
hAxis: {
title: 'Time'
},
vAxis: {
title: 'Value'
}
};
break;
case 'Table':
options = {
showRowNumber: true,
width: '100%',
height: '100%'
};
break;
default:
options = {};
}
return options;
}
}
<script src="https://www.gstatic.com/charts/loader.js"></script>
<div id="chart_div"></div>
<input type="button" id="btnSwitch" />

Categories

Resources