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>
Related
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>
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>
I am new to the world of the Google Visualization Api and was hoping someone can help me conditionally format the color of cells in my google visualization table. I have been able to change the number format that different columns display, but am not having such luck with color formatting. I am using the arrayToDataTable and chartwrapper functions to display some data I have queried from a spreadsheet.
Is it something I need to change with the colorFormat variable or the chartwrapper function that in not accepting the formatting? Thank you in advance!
function drawDashboard(response) {
$('#main-heading').addClass("hidden");
if (response == null) {
alert('Error: Invalid source data.')
return;
} else {
// Transmogrify spreadsheet contents (array) to a DataTable object
var responseObjects = JSON.parse(response);
console.log(responseObjects);
var testData = [];
for (var i = 1; i < responseObjects.length; i++) {
responseObjects[i][0] = new Date(responseObjects[i][0]);
}
var data = google.visualization.arrayToDataTable(responseObjects, false);
console.log(data);
var dashboard = new google.visualization.Dashboard(document.getElementById('dashboard-div'));
var percentFormatter = new google.visualization.NumberFormat({
pattern: '#,###.##%'
});
percentFormatter.format(data, 1);
percentFormatter.format(data, 3);
var numberFormatter = new google.visualization.NumberFormat({
pattern: '#.##'
});
numberFormatter.format(data, 7);
numberFormatter.format(data, 8);
var colorFormatter = new google.visualization.ColorFormat();
colorFormatter.addRange(0, 5, 'white', 'orange');
colorFormatter.addRange(20000, 6, 'red', '#33ff33');
colorFormatter.format(data, 8);
colorFormatter.format(data, 9);
colorFormatter.format(data, 10);
colorFormatter.format(data, 11);
var table = new google.visualization.ChartWrapper({
'chartType': 'Table',
'containerId': 'table-div',
'view': {
'columns': [0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15]
},
});
var donutSlider = new google.visualization.ControlWrapper({
'controlType': 'DateRangeFilter',
'containerId': 'slider-div',
'options': {
'filterColumnLabel': 'Date'
}
});
// Set up dependencies between controls and charts
dashboard.bind(donutSlider, [table]);
// Draw all visualization components of the dashboard
dashboard.draw(data);
}
}
looks like you're using the using the formatter correctly
but the parameters are a little off
also need allowHtml: true in the Table options
see following example using the linked spreadsheet...
google.charts.load('current', {
callback: function () {
var query = new google.visualization.Query(
'https://docs.google.com/spreadsheets/d/1TBTX_OmNUiq_J0uXEstkxeD6mtImi7BAPWKDBAQIiFA/edit#gid=0'
);
query.setQuery("select *");
query.send(drawDashboard);
},
packages: ['controls', 'table']
});
function drawDashboard(response) {
if (response.isError()) {
console.log('Error in query: ' + response.getMessage() + ' ' + response.getDetailedMessage());
return;
}
var data = response.getDataTable();
var dashboard = new google.visualization.Dashboard(document.getElementById('dashboard-div'));
var percentFormatter = new google.visualization.NumberFormat({
pattern: '#,###.##%'
});
percentFormatter.format(data, 1);
percentFormatter.format(data, 3);
var numberFormatter = new google.visualization.NumberFormat({
pattern: '#.##'
});
numberFormatter.format(data, 7);
numberFormatter.format(data, 8);
var colorFormatter = new google.visualization.ColorFormat();
colorFormatter.addRange(-20000, 0, 'white', 'orange');
colorFormatter.addRange(20000, null, 'red', '#33ff33');
colorFormatter.format(data, 8);
colorFormatter.format(data, 9);
colorFormatter.format(data, 10);
colorFormatter.format(data, 11);
var table = new google.visualization.ChartWrapper({
chartType: 'Table',
containerId: 'table-div',
options: {
allowHtml: true
}
});
var donutSlider = new google.visualization.ControlWrapper({
controlType: 'DateRangeFilter',
containerId: 'slider-div',
options: {
filterColumnLabel: 'Date'
}
});
dashboard.bind(donutSlider, [table]);
dashboard.draw(data);
}
<script src="https://www.gstatic.com/charts/loader.js"></script>
<div id="dashboard-div">
<div id="slider-div"></div>
<div id="table-div"></div>
</div>
is it possible to set the width and height of a chart when using the google visualization ChartEditor?
I require the chart to be 100% the width of the page and then set the height in pixels, currently when I set the width and height in the options they are being ignored.
the code that I have worked on so far is below:
<script type="text/javascript">
google.load("visualization", "1", { packages: ["corechart", "controls", "charteditor"] });
google.setOnLoadCallback(loadEditor);
var chartEditor = null;
window.onresize = function() {
loadEditor();
};
function loadEditor() {
var data = google.visualization.arrayToDataTable([#Html.Raw(#ViewBag.ChartData)]);
var dashboard = new google.visualization.Dashboard(document.getElementById('dashboard_div'));
var rangeSlider = new google.visualization.ControlWrapper({
'controlType': 'CategoryFilter',
'containerId': 'filter_div',
'options': {
'filterColumnLabel': 'VAR1',
'ui': {
'label': 'Years'
}
}
});
var wrapper = new google.visualization.ChartWrapper({
chartType: 'ColumnChart',
containerId: 'chart_div',
dataTable: data
});
chartEditor = new google.visualization.ChartEditor();
google.visualization.events.addListener(chartEditor, 'ok', redrawChart);
chartEditor.openDialog(wrapper, {});
dashboard.bind(rangeSlider, wrapper);
dashboard.draw(data);
}
function redrawChart() {
chartEditor.getChartWrapper().draw(document.getElementById('chart_div'));
}
</script>
the chart also incorporates a CategoryFilter linked with a dashboard is required to work with the chart displayed.
Currently when the chart is rendered it is fairly small.
Something like this should work, I switched out the data and modified the slider to get the snippet to work.
google.load("visualization", "1", { packages: ["corechart", "controls", "charteditor"] });
google.setOnLoadCallback(loadEditor);
window.addEventListener('resize', redrawChart, false);
var chartEditor;
var data;
var dashboard;
var rangeSlider;
var wrapper;
function loadEditor() {
data = google.visualization.arrayToDataTable([
['Element', 'Density'],
['Copper', 8.94],
['Silver', 10.49],
['Gold', 19.30],
['Platinum', 21.45]
]);
dashboard = new google.visualization.Dashboard(document.getElementById('dashboard_div'));
rangeSlider = new google.visualization.ControlWrapper({
'controlType': 'CategoryFilter',
'containerId': 'filter_div',
'options': {
'filterColumnLabel': 'Density',
'ui': {
'label': 'Density'
}
}
});
wrapper = new google.visualization.ChartWrapper({
chartType: 'ColumnChart',
containerId: 'chart_div',
dataTable: data
});
chartEditor = new google.visualization.ChartEditor();
google.visualization.events.addListener(chartEditor, 'ok', drawChart);
chartEditor.openDialog(wrapper, {});
}
function drawChart() {
wrapper = chartEditor.getChartWrapper();
redrawChart();
}
function redrawChart() {
var height;
var width;
height = '200px';
width = Math.min(document.documentElement.clientWidth, window.innerWidth || 0) + 'px';
wrapper.setOption('height', height);
wrapper.setOption('width', width);
dashboard.bind(rangeSlider, wrapper);
dashboard.draw(data);
}
<script src="https://www.google.com/jsapi"></script>
<div id="dashboard_div">
<div id="filter_div"></div>
<div id="chart_div"></div>
</div>
I'm using Google Charts for a small projects for myself, and I'm not very good with javascript so I thought I'd ask for some help.
Basically I want to change the current values of the chart by pressing a button.
This is the script:
google.load("visualization", "1", {packages:["corechart"]});
google.setOnLoadCallback(drawChart);
function drawChart() {
var data = google.visualization.arrayToDataTable([
['', 'YES', 'NO'],
['', 5, 2],
]);
var options = {
title: 'Win / Loss ratio',
vAxis: {title: 'Chart', titleTextStyle: {color: 'red'}}
};
var chart = new google.visualization.BarChart(document.getElementById('chart'));
chart.draw(data, options);
}
The values 5 and 2 should be changed when clicking button_1 or button_2
All help is appreciated.
You can do something like this:
function drawChart() {
var data = google.visualization.arrayToDataTable([
['', 'YES', 'NO'],
['', 5, 2],
]);
var options = {
title: 'Win / Loss ratio',
vAxis: {title: 'Chart', titleTextStyle: {color: 'red'}}
};
var chart = new google.visualization.BarChart(document.getElementById('chart'));
chart.draw(data, options);
function incrementYes () {
data.setValue(0, 1, data.getValue(0, 1) + 1);
chart.draw(data, options);
}
function incrementNo () {
data.setValue(0, 2, data.getValue(0, 2) + 1);
chart.draw(data, options);
}
// assumes button_1 and button_2 have id's "button_1" and "button_2"
var btn1 = document.querySelector('#button_1');
var btn2 = document.querySelector('#button_2');
if (document.addEventListener) {
// add event listener in most browsers
btn1.addEventListener('click', incrementYes);
btn2.addEventListener('click', incrementNo);
}
else if (document.attachEvent) {
// add event listener in IE
btn1.attachEvent('onclick', incrementYes);
btn2.attachEvent('onclick', incrementNo);
}
else {
// add event listener in legacy browsers
btn1.onclick = incrementYes;
btn2.onclick = incrementNo;
}
}