Google Charts - switch between table and chart view - javascript

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" />

Related

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 Bar Chart with Percentage of Total and with Category Filters

I am fairly new to Google Charts and was trying to create a bar chart with % of total, along with the ability to filter the data by using Google Dashboard Controls... I followed this (thanks to #asgallant for this!) google.visualization.ChartWrapper Group Columns View and was able to get a bar chart which picks up data from a google sheet, and draws the chart with counts and also have the ability to filter the data using Google Category filters.
However, this is where I am stuck - when I try to add another columns (dataview) for calculating the total (so that I can draw the chart using the percentage and also show the percentage in the bar labels) - my chart is still drawing using the counts.. Can anyone please let me know what am I going wrong here:
function drawVisualization() {
var query = new google.visualization.Query('https://docs.google.com/spreadsheets/d/1LBoS8Q7qdpWVjks3FytQAefThzY3VbAHllf04nE6qO8/edit?gid=1629614877&range=A:D');
query.send(handleQueryResponse);
function handleQueryResponse(response) {
if (response.isError()) {return; }
var data = response.getDataTable();
// Define category pickers for All Filters
var CardTier = new google.visualization.ControlWrapper({
'controlType': 'CategoryFilter',
'containerId': 'control1',
'options': {
'filterColumnLabel': 'CardTier Filter',
'ui': {
'labelStacking': 'vertical',
'allowTyping': false,
'allowMultiple': false
}
}
});
var Campaign = new google.visualization.ControlWrapper({
'controlType': 'CategoryFilter',
'containerId': 'control2',
'options': {
'filterColumnLabel': 'Campaign Filter',
'ui': {
'labelStacking': 'vertical',
'allowTyping': false,
'allowMultiple': false
}
}
});
// Define a bar chart to show 'Population' data
var barChart = new google.visualization.ChartWrapper({
'chartType': 'BarChart',
'containerId': 'chart1',
'options': {
'width': 400,
'height': 300,
'chartArea': {top: 0, right: 0, bottom: 0}
},
// Configure the barchart to use columns 0 (Card Tier) and 1 (Campaign Filter) (Basically the filters)
'view': {'columns': [0, 1]}
});
var proxyTable = new google.visualization.ChartWrapper({
chartType: 'Table',
containerId: 'proxyTable',
options: {
// minimize the footprint of the table in HTML
page: 'enable',
pageSize: 1
},
view: {
columns: [0]
}
});
// create a "ready" event handler for proxyTable the handles data aggregation and drawing barChart
// Add The question's column index here. We want to draw Status so we Group 2 with dt and also its count...
google.visualization.events.addListener(proxyTable, 'ready', function () {
var dt = proxyTable.getDataTable();
var groupedData = google.visualization.data.group(dt, [2], [{
column: 3,
type: 'number',
label: dt.getColumnLabel(2),
aggregation: google.visualization.data.count
}]);
var view = new google.visualization.DataView(groupedData);
view.setColumns([0, 1, {
calc: function (dt, row) {
var amount = formatShort.formatValue(dt.getValue(row, 1));
var percent = formatPercent.formatValue(dt.getValue(row, 1) / groupedData.getValue(0, 1));
return amount + ' (' + percent + ')';
},
type: 'string',
role: 'annotation'
}]);
// after grouping, the data will be sorted by column 0, then 1, then 2
// if you want a different order, you have to re-sort
barChart.setDataTable(view);
barChart.draw();
});
// Create the dashboard.
new google.visualization.Dashboard(document.getElementById('dashboard')).
// Configure the controls :
bind(CardTier, Campaign).
bind(Campaign, proxyTable).
// Draw the dashboard
draw(data);
}
}
google.load('visualization', '1', {packages:['corechart', 'controls', 'table'], callback: drawVisualization});
</script>
</head>
<body>
<div id="dashboard">
<table>
<tr style='vertical-align: top'>
<td style='width: 300px; font-size: 0.9em;'>
<div id="control1"></div>
<div id="control2"></div>
</td>
<td style='width: 600px'>
<div style="float: left;" id="chart1"></div>
<div style="float: left;" id="chart2"></div>
</td>
</tr>
</table>
<div id="proxyTable" style="display: none;"></div>
</div>
</body>
</html>
for starters, recommend using the newer library loader.js
<script src="https://www.gstatic.com/charts/loader.js"></script>
instead of jsapi, 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.
this will only change the load statement, see following working snippet...
next, didn't see the definitions for the number formatters
formatShort and formatPercent
need to add those
groupedData will give you the total for each status
to get the the total for all the rows,
need to use the modifier function
this will change the value to 'Total' for the first column of all rows
allowing the group method to aggregate all rows
var totalData = google.visualization.data.group(
dataTable,
[{column: 0, type: 'string', modifier: function () {return 'Total';}}],
[{
column: 3,
type: 'number',
label: dataTable.getColumnLabel(2),
aggregation: google.visualization.data.count
}]
);
finally, remove the view option from barChart
since we're providing the view we want drawn
see following working snippet...
google.charts.load('current', {
callback: drawVisualization,
packages: ['corechart', 'controls', 'table']
});
function drawVisualization() {
var query = new google.visualization.Query('https://docs.google.com/spreadsheets/d/1LBoS8Q7qdpWVjks3FytQAefThzY3VbAHllf04nE6qO8/edit?gid=1629614877&range=A:D');
query.send(handleQueryResponse);
function handleQueryResponse(response) {
if (response.isError()) {return; }
var data = response.getDataTable();
// Define category pickers for All Filters
var CardTier = new google.visualization.ControlWrapper({
'controlType': 'CategoryFilter',
'containerId': 'control1',
'options': {
'filterColumnLabel': 'CardTier Filter',
'ui': {
'labelStacking': 'vertical',
'allowTyping': false,
'allowMultiple': false
}
}
});
var Campaign = new google.visualization.ControlWrapper({
'controlType': 'CategoryFilter',
'containerId': 'control2',
'options': {
'filterColumnLabel': 'Campaign Filter',
'ui': {
'labelStacking': 'vertical',
'allowTyping': false,
'allowMultiple': false
}
}
});
// Define a bar chart to show 'Population' data
var barChart = new google.visualization.ChartWrapper({
'chartType': 'BarChart',
'containerId': 'chart1',
'options': {
'width': 400,
'height': 300,
'chartArea': {top: 0, right: 0, bottom: 0}
}
});
var proxyTable = new google.visualization.ChartWrapper({
chartType: 'Table',
containerId: 'proxyTable',
options: {
// minimize the footprint of the table in HTML
page: 'enable',
pageSize: 1
},
view: {
columns: [0]
}
});
// create a "ready" event handler for proxyTable the handles data aggregation and drawing barChart
// Add The question's column index here. We want to draw Status so we Group 2 with dt and also its count...
google.visualization.events.addListener(proxyTable, 'ready', function () {
var formatShort = new google.visualization.NumberFormat({
pattern: 'short'
});
var formatPercent = new google.visualization.NumberFormat({
pattern: '0.0%'
});
var dataTable = proxyTable.getDataTable();
// group by status
var groupedData = google.visualization.data.group(
dataTable,
[2],
[{
column: 3,
type: 'number',
label: dataTable.getColumnLabel(2),
aggregation: google.visualization.data.count
}]
);
// status total
var totalData = google.visualization.data.group(
dataTable,
[{column: 0, type: 'string', modifier: function () {return 'Total';}}],
[{
column: 3,
type: 'number',
label: dataTable.getColumnLabel(2),
aggregation: google.visualization.data.count
}]
);
var view = new google.visualization.DataView(groupedData);
view.setColumns([0, 1, {
calc: function (dt, row) {
var amount = dt.getValue(row, 1);
var total = totalData.getValue(0, 1);
var percent = 0;
if (total > 0) {
percent = amount / total;
}
return formatShort.formatValue(amount) + ' (' + formatPercent.formatValue(percent) + ')';
},
type: 'string',
role: 'annotation'
}]);
// after grouping, the data will be sorted by column 0, then 1, then 2
// if you want a different order, you have to re-sort
barChart.setDataTable(view);
barChart.draw();
});
// Create the dashboard.
new google.visualization.Dashboard(document.getElementById('dashboard')).
// Configure the controls :
bind(CardTier, Campaign).
bind(Campaign, proxyTable).
// Draw the dashboard
draw(data);
}
}
<script src="https://www.gstatic.com/charts/loader.js"></script>
<div id="control1"></div>
<div id="control2"></div>
<div id="chart1"></div>
<div id="proxyTable"></div>
UPDATE
to draw the percentages instead of counts,
just need to add another calculated column to the view
as for showing zero values,
use the original data table to get a distinct list of status values
check if the status exists in groupedData
if not, add a row for the status
// add back missing status
var statusValues = data.getDistinctValues(2);
statusValues.forEach(function (status) {
var statusRow = groupedData.getFilteredRows([{
column: 0,
value: status
}]);
if (statusRow.length === 0) {
groupedData.addRow([
status,
0
]);
}
});
groupedData.sort([{column: 0}]);
see following working snippet...
google.charts.load('current', {
callback: drawVisualization,
packages: ['corechart', 'controls', 'table']
});
function drawVisualization() {
var query = new google.visualization.Query('https://docs.google.com/spreadsheets/d/1LBoS8Q7qdpWVjks3FytQAefThzY3VbAHllf04nE6qO8/edit?gid=1629614877&range=A:D');
query.send(handleQueryResponse);
function handleQueryResponse(response) {
if (response.isError()) {return; }
var data = response.getDataTable();
// Define category pickers for All Filters
var CardTier = new google.visualization.ControlWrapper({
'controlType': 'CategoryFilter',
'containerId': 'control1',
'options': {
'filterColumnLabel': 'CardTier Filter',
'ui': {
'labelStacking': 'vertical',
'allowTyping': false,
'allowMultiple': false
}
}
});
var Campaign = new google.visualization.ControlWrapper({
'controlType': 'CategoryFilter',
'containerId': 'control2',
'options': {
'filterColumnLabel': 'Campaign Filter',
'ui': {
'labelStacking': 'vertical',
'allowTyping': false,
'allowMultiple': false
}
}
});
// Define a bar chart to show 'Population' data
var barChart = new google.visualization.ChartWrapper({
'chartType': 'BarChart',
'containerId': 'chart1',
'options': {
'width': 400,
'height': 300,
'chartArea': {top: 0, right: 0, bottom: 0}
}
});
var proxyTable = new google.visualization.ChartWrapper({
chartType: 'Table',
containerId: 'proxyTable',
options: {
// minimize the footprint of the table in HTML
page: 'enable',
pageSize: 1
},
view: {
columns: [0]
}
});
// create a "ready" event handler for proxyTable the handles data aggregation and drawing barChart
// Add The question's column index here. We want to draw Status so we Group 2 with dt and also its count...
google.visualization.events.addListener(proxyTable, 'ready', function () {
var formatShort = new google.visualization.NumberFormat({
pattern: 'short'
});
var formatPercent = new google.visualization.NumberFormat({
pattern: '0.0%'
});
var dataTable = proxyTable.getDataTable();
// group by status
var groupedData = google.visualization.data.group(
dataTable,
[2],
[{
column: 3,
type: 'number',
label: dataTable.getColumnLabel(2),
aggregation: google.visualization.data.count
}]
);
// add back missing status
var statusValues = data.getDistinctValues(2);
statusValues.forEach(function (status) {
var statusRow = groupedData.getFilteredRows([{
column: 0,
value: status
}]);
if (statusRow.length === 0) {
groupedData.addRow([
status,
0
]);
}
});
groupedData.sort([{column: 0}]);
// status total
var totalData = google.visualization.data.group(
dataTable,
[{column: 0, type: 'string', modifier: function () {return 'Total';}}],
[{
column: 3,
type: 'number',
label: dataTable.getColumnLabel(2),
aggregation: google.visualization.data.count
}]
);
var view = new google.visualization.DataView(groupedData);
view.setColumns([0, {
calc: function (dt, row) {
var amount = dt.getValue(row, 1);
var total = totalData.getValue(0, 1);
var percent = 0;
if (total > 0) {
percent = amount / total;
}
return {
v: percent,
f: formatPercent.formatValue(percent)
};
},
type: 'number',
label: 'Percent'
}, {
calc: function (dt, row) {
var amount = dt.getValue(row, 1);
var total = totalData.getValue(0, 1);
var percent = 0;
if (total > 0) {
percent = amount / total;
}
return formatPercent.formatValue(percent) + ' (' + formatShort.formatValue(amount) + ')';
},
type: 'string',
role: 'annotation'
}]);
// after grouping, the data will be sorted by column 0, then 1, then 2
// if you want a different order, you have to re-sort
barChart.setDataTable(view);
barChart.draw();
});
// Create the dashboard.
new google.visualization.Dashboard(document.getElementById('dashboard')).
// Configure the controls :
bind(CardTier, Campaign).
bind(Campaign, proxyTable).
// Draw the dashboard
draw(data);
}
}
<script src="https://www.gstatic.com/charts/loader.js"></script>
<div id="control1"></div>
<div id="control2"></div>
<div id="chart1"></div>
<div id="proxyTable"></div>
UPDATE 2
to find the total of a multiple choice question,
create a view with a calculated column
the new column should test that all question columns are not blank
then total the view on the calculated column
see following working snippet...
google.charts.load('current', {
callback: drawVisualization,
packages: ['corechart', 'controls', 'table']
});
function drawVisualization() {
var query = new google.visualization.Query('https://docs.google.com/spreadsheets/d/19VWNZkHG5GEuYCibDmtOlKblKiOWcx94Wi9jyuhvEUo/edit#gid=0');
query.setQuery('select A,B,C,D,E,F,G');
query.send(handleQueryResponse);
function handleQueryResponse(response) {
if (response.isError()) {return;}
var data = response.getDataTable();
var view = new google.visualization.DataView(data);
view.setColumns([0, 1, 2, 3, 4, 5, 6, {
calc: function (dt, row) {
var answered = 0;
var q1_1 = dt.getValue(row, 3) || '';
var q1_2 = dt.getValue(row, 4) || '';
var q1_3 = dt.getValue(row, 5) || '';
var q1_4 = dt.getValue(row, 6) || '';
if ((q1_1 !== '') || (q1_2 !== '') || (q1_3 !== '') || (q1_4 !== '')) {
answered = 1;
}
return answered;
},
label: 'Answered',
type: 'number'
}]);
var totalAnswered = google.visualization.data.group(
view,
[{column: 0, type: 'string', modifier: function () {return 'Total';}}],
[{
column: view.getNumberOfColumns() - 1,
type: 'number',
label: view.getColumnLabel(view.getNumberOfColumns() - 1),
aggregation: google.visualization.data.sum
}]
);
var proxyTable = new google.visualization.ChartWrapper({
chartType: 'Table',
containerId: 'proxyTable',
dataTable: view
});
proxyTable.draw();
document.getElementById('proxyTableTotal').innerHTML = 'Total Answered = ' + totalAnswered.getValue(0, 1);
}
}
<script src="https://www.gstatic.com/charts/loader.js"></script>
<div id="proxyTable"></div>
<div id="proxyTableTotal"></div>

Google GeoCharts Colors Not Working

I have tried multiple things to apply but none of them seem to work to change my charts. I am uploading the array through a file and everything seems to work, even changing the defaultColor, but colorAxis does not seem to work. Could you guys(and girls) help me I would be grateful. Thanks
/* CSV handling - START */
var processedData = [];
var continent = $('select[name="continents"] option:selected').val();
$.get('example.csv', function(data) {
processedData = $.csv.toArrays(data);
}, 'text');
/* CSV handling - END */
/* Google Charts */
google.charts.load('current', {
'packages':['geochart'],
// Note: you will need to get a mapsApiKey for your project.
// See: https://developers.google.com/chart/interactive/docs/basic_load_libs#load-settings
'mapsApiKey': //doesn't matter
});
google.charts.setOnLoadCallback(drawRegionsMap);
function drawRegionsMap() {
var data = google.visualization.arrayToDataTable(processedData, false);
var options = {
sizeAxis: { minValue: 0, maxValue: 100 },
colorAxis: {colors: ['#e7711c', '#4374e0']},
region: continent,
width: '100%',
height: '100%',
backgroundColor: 'none'
};
var chart = new google.visualization.GeoChart(document.getElementById('chart_div'));
chart.draw(data, options);
}
/* Google Charts - End */
Please Refer To Google Developer reference
https://developers.google.com/chart/interactive/docs/gallery/geochart#important
var options = {
region: '002', // Africa
colorAxis: {colors: ['#00853f', 'black', '#e31b23']},
backgroundColor: '#81d4fa',
datalessRegionColor: '#f8bbd0',
defaultColor: '#f5f5f5',
};
https://developers.google.com/chart/interactive/docs/gallery/geochart#coloring-your-chart
var options = {
region: 'IT',
displayMode: 'markers',
colorAxis: {colors: ['green', 'blue']}
};
var chart = new google.visualization.GeoChart(document.getElementById('chart_div'));
chart.draw(data, options);
using the data from the comment, the chart colors seem to work
recommend removing the options for sizeAxis
the values in the data table range from 100 to 2313 (not 0 to 100),
the chart will handle by default
see following working snippet...
google.charts.load('current', {
callback: function () {
var processedData = [
['Country','Popularity'],
['HR',300.00],
['RU',100.00],
['FR',200.00],
['BR',2000.00],
['DZ',222.00],
['US',333.00],
['DE',555.00],
['DD',999.00],
['SZ',2313.00],
['AU',2222.00],
['BM',400.00],
['CA',322.00]
];
var data = google.visualization.arrayToDataTable(processedData);
var sizeRange = data.getColumnRange(1);
var options = {
colorAxis: {colors: ['#e7711c', '#4374e0']},
//region: continent,
width: '100%',
height: '100%',
backgroundColor: 'none'
};
var chart = new google.visualization.GeoChart(document.getElementById('chart_div'));
chart.draw(data, options);
},
packages: ['geochart']
});
<script src="https://www.gstatic.com/charts/loader.js"></script>
<div id="chart_div"></div>

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

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>

Animating column chart from google charts

I'm having trouble coming up with a function that will animate a single column bar inside of my chart when I use a slider going back and forth..left and right.. I have read the animation docs on the Google Charts API documentation, but I am having a hard time understanding what I need to do.
Here is my code so far. Where would I start in figuring out how to animate just one of my bars using a slider I have made in titanium? I call the function updateChart() from my app.js file using the evalJS function. I have verified it works, by doing a console.log when my slider goes back and forth. I just can't seem to wrap my head around it how to apply this to animating a single column bar. Any thoughts are appreciated.
Set up Google Charts on my html page.
<script type="text/javascript" src ="https://www.google.com/jsapi" > </script>
<script type="text/javascript ">
google.load("visualization", "1", {packages:["corechart"]});
google.setOnLoadCallback(drawChart);
function drawChart() {
var data = new google.visualization.DataTable();
data.addColumn('string', 'Importance');
data.addColumn('number', 'Earning');
data.addColumn({type: 'string', role: 'style'});
data.addRows([['',5,'#000000'], ['',5,'#ffffff'],['',5,'#666666'],['', 5,'#cccccc']]);
var options =
{
width: 200,
height: 240,
legend: {
position: 'none'
},
chartArea: {
backgroundColor: 'none'
},
bar: {
groupWidth: '100%'
},
animation: {
duration: 1000,
easing: 'out'
}
};
function updateChart() {
}
var chart = new google.visualization.ColumnChart(document.getElementById('chart_div'));
chart.draw(data, options);
}
EDITED CODE:
<script type="text/javascript" src ="https://www.google.com/jsapi" > </script>
<script type="text/javascript ">
google.load("visualization", "1", {packages:["corechart"]});
google.setOnLoadCallback(drawChart);
function drawChart() {
var data = new google.visualization.DataTable();
data.addColumn('string', 'Importance');
data.addColumn('number', 'Earning');
data.addColumn({type: 'string', role: 'style'});
data.addRows([['',5,'#000000'], ['',5,'#ffffff'],['',5,'#666666'],['', 5,'#cccccc']]);
var options = {
width: 200,
height: 240,
legend: {
position: 'none'
},
chartArea: {
backgroundColor: 'none'
},
bar: {
groupWidth: '100%'
},
animation: {
duration: 1000,
easing: 'out'
}
};
function updateChart(value) {
data.setValue(0, 1, value);
chart.draw(data, options);
}
var chart = new google.visualization.ColumnChart(document.getElementById('chart_div'));
chart.draw(data, options);
}
Slider Hook Code in separate file (app.js) Titanium Platform
var sliderBarOne = Titanium.UI.createSlider({
top: '310',
left: '610',
min: '0',
max: '10',
width: '37%',
value: '5',
backgroundImage: 'assets/sliderBar.png'
});
sliderBarOne.addEventListener('change', function(e) {
chartView.evalJS("updateChart('" + e.value + "');");
});
You need to hook up an event listener for your slider that calls the updateChart function. The updateChart function should get the value from the slider and change the value in the DataTable, then cal the chart's draw method. How you hook up an event listener to the slider is going to depend on the library you are using for the slider. Here's some example code that assumes your slider object has a change method to set a change event handler and a `getValue method to get the value of the slider:
[edit: added in your slider code]
function drawChart() {
var data = new google.visualization.DataTable();
data.addColumn('string', 'Importance');
data.addColumn('number', 'Earning');
data.addColumn({type: 'string', role: 'style'});
data.addRows([
['',5,'#000000'],
['',5,'#ffffff'],
['',5,'#666666'],
['', 5,'#cccccc']
]);
var options = {
width: 200,
height: 240,
legend: {
position: 'none'
},
chartArea: {
backgroundColor: 'none'
},
bar: {
groupWidth: '100%'
},
animation: {
duration: 1000,
easing: 'out'
}
};
var chart = new google.visualization.ColumnChart(document.getElementById('chart_div'));
function updateChart(value) {
data.setValue(0, 1, value);
chart.draw(data, options);
}
// create slider
var sliderBarOne = Titanium.UI.createSlider({
top: '310',
left: '610',
min: '0',
max: '10',
width: '37%',
value: '5',
backgroundImage: 'assets/sliderBar.png'
});
sliderBarOne.addEventListener('change', function(e) {
updateChart(e.value);
});
chart.draw(data, options);
}

Categories

Resources