Getting Type of Google Chart - javascript

I was looking through the API and couldn't find anything about getting the type of chart.
I have this code:
<script type="text/javascript">
var chart;
function drawTest( dataTable ) {
google.load("visualization", "1", {packages:["corechart"]});
var options = {
title: 'test chart',
hAxis: {title: 'Day', titleTextStyle: {color: 'black'},
animation: {
duration: 1000,
easing: 'out',
}}
};
var data = new google.visualization.DataTable();
data.addColumn('string', 'String');
data.addColumn('number', 'Number1');
data.addColumn('number', 'Number2');
dataTable.forEach( function(row) {
data.addRow( row );
} );
chart = new google.visualization.ColumnChart( document.getElementById( 'chart' ) );
chart.draw( data, options );
}
What I want to do is instead of setting chart to a new chart in the bottom I want to check if it's already set. I'm not sure if this is in the API.
if( chart.getType() == "ColumnChart" ){
chart.draw( data, options );
}
However, I have multiple charts so I can't just check if chart is initialized.
Any help about completing this task is appreciated.

If you use a chartWrapper instead, there is a getChartType method that returns the class name of the wrapped chart. You can view more info about chartWrapper class here:
https://developers.google.com/chart/interactive/docs/reference#chartwrapperobject
Here is an example using google visualization playground:
function drawVisualization() {
// Create and populate the data table.
var wrapper = new google.visualization.ChartWrapper({
chartType: 'ColumnChart',
dataTable: [['', 'Germany', 'USA', 'Brazil', 'Canada', 'France', 'RU'],
['', 700, 300, 400, 500, 600, 800]],
options: {'title': 'Countries'},
containerId: 'visualization'
});
wrapper.draw();
console.log(wrapper.getChartType()) // ColumnChart
}

Related

Google Visualization ChartWrapper set cell value programmatically

When I click on a line item a Google visualization ChartWrapper table, I want to programmatically update the product value in the row that was clicked.
I'm getting stuck here: dataTable.setValue(row, col, valNew);
According to the documentation I should be able to use setValue to update a value in the datable. I'm getting error "setValue is not a function".
Hoping that someone can point me in the right direction...
Here is my code so far. The problem is in the selectHandler_table_db function.
google.charts.load('current', {
packages: ['table', 'controls']
}).then(function() {
var data = new google.visualization.DataTable();
data.addColumn('date', 'Date');
data.addColumn('string', 'Product');
data.addColumn('number', 'Quantity');
var dt1 = new Date(moment().endOf('month').subtract(3, 'month'));
var dt2 = new Date(moment().endOf('month').subtract(2, 'month'));
var dt3 = new Date(moment().endOf('month').subtract(1, 'month'));
var dt4 = new Date(moment().startOf('month'));
var dt5 = new Date(moment().startOf('month').add(1, 'day'));
var dt6 = new Date(moment().startOf('month').add(2, 'day'));
data.addRows([
[dt1, 'a', 100],
[dt2, 'b', 200],
[dt3, 'a', 300],
[dt4, 'b', 400],
[dt5, 'a', 500],
[dt6, 'b', 600],
]);
var view = new google.visualization.DataView(data);
example_dashboard(view);
});
function example_dashboard(view) {
var dashboard = new google.visualization.Dashboard(document.getElementById('div_dashboard'));
var categoryPicker1 = new google.visualization.ControlWrapper({
controlType: 'CategoryFilter',
containerId: 'div_categoryPicker1',
options: {
filterColumnIndex: view.getColumnIndex('Product'),
matchType: 'any',
ui: {
labelStacking: 'vertical',
allowTyping: false,
allowMultiple: false,
allowNone: true
}
}
});
var table_db = new google.visualization.ChartWrapper({
chartType: 'Table',
containerId: 'div_table',
options: {
width: '100%',
height: 'auto',
}
});
dashboard.bind(categoryPicker1, table_db);
dashboard.draw(view);
google.visualization.events.addListener(table_db, 'select', selectHandler_table_db);
function selectHandler_table_db() {
let chartWrapper = table_db.getChart();
let dataTable = table_db.getDataTable();
let row = chartWrapper.getSelection()[0].row;
let col = 1;
let valNew = "c";
//This errors dataTable.setValue is not a function
dataTable.setValue(row, col, valNew);
chartWrapper.draw();
} //END selectHandler_table
} //END example_dashboard(){
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.1.1/jquery.min.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/moment.js/2.22.1/moment.min.js"></script>
<script src="https://www.gstatic.com/charts/loader.js"></script>
<div id='div_dashboard'>
<div id='div_categoryPicker1'></div>
<div id="div_table"></div>
</div>
the error occurs because you are using a DataView to draw the Dashboard,
which is the object returned from the ChartWrapper, and not a DataTable.
you could resolve by passing the DataTable instead,
example_dashboard(data); // use data table here
it doesn't appear you are modifying the data using the view.
or if that code just isn't included here,
you can convert the DataView to a DataTable, before drawing the dashboard...
example_dashboard(view.toDataTable()); // convert view to DataTable

Google Charts: Registering a click on a GeoChart

I've been working on a small project to make a map of, in this case The Netherlands, with a bunch of markers on it. The data is provided through a CSV and i've linked the chart and a slider through a dashboard.
It's worked perfectly so far, however i'm having issues on the next functionality: Registering a click on a marker and then referring the user to a different webpage depending on which marker was clicked.
I've tried many times to get it to work, but i believe it has something to do with the fact that i'm using chartWrappers instead of a normal chart.
Here is my current code:
google.charts.load('current', {
'packages':['geochart', 'controls'],
});
google.charts.setOnLoadCallback(drawMarkersMap);
function drawMarkersMap() {
$.get("output.csv", function(csvString) {
var arrayData = $.csv.toArrays(csvString, {onParseValue: $.csv.hooks.castToScalar});
var data = google.visualization.arrayToDataTable(arrayData)
var dashboard = new google.visualization.Dashboard(document.getElementById('controls_div'));
var Slider = new google.visualization.ControlWrapper({
controlType: 'NumberRangeFilter',
containerId: 'controls_div',
options: {
filterColumnLabel: data.getColumnLabel(1)
}
});
var GeoChart = new google.visualization.ChartWrapper({
chartType: 'GeoChart',
containerId: 'chart_div',
options: {
region: 'NL',
displayMode: 'markers',
resolution: 'provinces',
colorAxis: {colors: ['green', 'blue']}
}
});
google.visualization.events.addListener(GeoChart, 'select', function() {
var selection = GeoChart.getChart().getSelection();
//Above line doesn't work. Console also returns that getSelection property is null.
});
dashboard.bind(Slider, GeoChart);
dashboard.draw(data);
})};
If anyone with experience could help me properly set up a working listener i'd be eternally grateful.
you were right about wrapper vs. regular
the chart wrapper does not have an event for 'select'
you have to wait until the wrapper is 'ready',
then listen for 'select' on the chart,
see following snippet...
google.visualization.events.addListener(GeoChart, 'ready', function() {
google.visualization.events.addListener(GeoChart.getChart(), 'select', function() {
var selection = GeoChart.getChart().getSelection();
});
});
see following working snippet...
google.charts.load('current', {
packages:['controls', 'geochart']
}).then(function () {
var data = google.visualization.arrayToDataTable([
['Country', 'Popularity', 'Domain'],
['England', 400, 'www.example.com/England'],
['Wales', 300, 'www.example.com/Wales'],
['Scotland', 400, 'www.example.com/Scotland'],
['Ireland', 600, 'www.example.com/Ireland'],
]);
var view = new google.visualization.DataView(data);
view.setColumns([0, 1]);
var GeoChart = new google.visualization.ChartWrapper({
chartType: 'GeoChart',
containerId: 'chart_div',
dataTable: view,
options: {
region: 'GB',
displayMode: 'markers',
resolution: 'provinces',
colorAxis: {colors: ['green', 'blue']}
}
});
google.visualization.events.addListener(GeoChart, 'ready', function () {
google.visualization.events.addListener(GeoChart.getChart(), 'select', function () {
var selection = GeoChart.getChart().getSelection();
if (selection.length > 0) {
console.log(data.getValue(selection[0].row, 2));
//window.open('http://' + data.getValue(selection[0].row, 2), '_blank');
}
});
});
GeoChart.draw();
});
<script src="https://www.gstatic.com/charts/loader.js"></script>
<div id="chart_div"></div>

Google Charts fetching from Json

I'm trying to create charts using Google Charts Api. My data is stored as a json file as shown.
{
"1":[{"a":0,"d":0}],
"2":[{"a":0,"d":0}],
"3":[{"a":6,"d":62.92}],
"4":[{"a":1.57,"d":75.32}],
"5":[{"a":1.67,"d":66.45}],
"6":[{"a":1.25,"d":76}],
"7":[{"a":1.36,"d":75.08}],
"8":[{"a":1.59,"d":69.27}],
...
}
I'm fetching json file, pushing the objects to a javascript array. It works with no problem. I added these lines to understand what's happening. However Google Api doesn't accept my values and shows only
dots.push([5, 50]);
dots.push([7,60]);
Here's my code
function drawDots()
{
var data = new google.visualization.DataTable();
data.addColumn('number', 'a');
data.addColumn('number', 'd');
dots = new Array;
dots.push([5, 50]);
dots.push([7,60]);
$.getJSON("/graph/graph.json", function(json)
{
$.each(json, function(id, num)
{
$.each(num, function(i, e)
{
dots.push([e.a, e.d]);
});
});
});
data.addRows(dots);
var options = {
title: '',
hAxis: {title: 'Data 1', minValue: 0, maxValue: 100},
vAxis: {title: 'Data 2', minValue: 0, maxValue: 100},
legend: 'none'
};
var chart = new google.visualization.ScatterChart(document.getElementById('chart_div'));
chart.draw(data, options);
}
Data type of the values are number, I also tried eval() to. In console, values are seems in array. Can't understand what's wrong.
Here's the console log of dots and data with a screen shot.
The problem is with the asynchronous getJSON call. The getJSON call happens but while it's still retrieving the contents of graph.json, the rest of the code executes. This means that the getJSON callback runs after the chart has been drawn.
Solution: Move the chart drawing code into the getJSON callback:
function drawDots()
{
var data = new google.visualization.DataTable();
data.addColumn('number', 'a');
data.addColumn('number', 'd');
dots = new Array;
dots.push([5, 50]);
dots.push([7,60]);
$.getJSON("/graph/graph.json", function(json)
{
$.each(json, function(id, num)
{
$.each(num, function(i, e)
{
dots.push([e.a, e.d]);
});
});
data.addRows(dots);
var options = {
title: '',
hAxis: {title: 'Data 1', minValue: 0, maxValue: 100},
vAxis: {title: 'Data 2', minValue: 0, maxValue: 100},
legend: 'none'
};
var chart = new google.visualization.ScatterChart(document.getElementById('chart_div'));
chart.draw(data, options);
});
}

Google chart change bar color

i am using google chart api to show a chart on a bootstrap modal with framework Laravel, i'm having an issue because i'm not beein able to change the colour of the bar and put one blue and the other one green, another issue is that at the right it only put me the name of une of the bars(RX).
Here is my js code:
// Load the Visualization API and the corechart package.
google.charts.load('current', {'packages':['corechart']});
// Set a callback to run when the Google Visualization API is loaded.
// google.charts.setOnLoadCallback(drawChart);
// Callback that creates and populates a data table,
// instantiates the pie chart, passes in the data and
// draws it.
function drawChart(nombre, unidad, tipo, valor, media) {
var data = new google.visualization.DataTable();
data.addColumn('string', 'Name');
data.addColumn('number', 'RX');
data.addColumn({type: 'string', role: 'annotation'});
data.addRows([
['TĂș', parseInt(valor), valor+' '+unidad],
['Media', parseFloat(media), parseInt(media)+' '+unidad],
]);
var view = new google.visualization.DataView(data);
view.setColumns([0, 1,1,2]);
var chart = new google.visualization.ComboChart(document.getElementById('chart_div'));
chart.draw(view, {
// height: 400,
// width: 600,
series: {
0: {
type: 'bars'
},
1: {
type: 'line',
color: 'grey',
lineWidth: 0,
pointSize: 0,
visibleInLegend: false
}
},
vAxis: {
maxValue: 100,
minValue: 0,
}
});
$("#myModalLabel").empty();
$("#myModalLabel").append(tipo+" - "+nombre);
$("#modalChart").modal();
}
Here is the chart that i get:
you can write your drawchart function like this
<script type="text/javascript">
google.charts.load("current", {packages:['corechart']});
google.charts.setOnLoadCallback(drawChart);
function drawChart() {
var data = google.visualization.arrayToDataTable([
["Element", "Density", { role: "style" } ],
["Copper", 8.94, "#b87333"],
["Silver", 10.49, "silver"],
["Gold", 19.30, "gold"],
["Platinum", 21.45, "color: #e5e4e2"]
]);
var view = new google.visualization.DataView(data);
view.setColumns([0, 1,
{ calc: "stringify",
sourceColumn: 1,
type: "string",
role: "annotation" },
2]);
var options = {
title: "Density of Precious Metals, in g/cm^3",
width: 600,
height: 400,
bar: {groupWidth: "95%"},
legend: { position: "none" },
};
var chart = new google.visualization.ColumnChart(document.getElementById("columnchart_values"));
chart.draw(view, options);
}
</script>
For more https://developers.google.com/chart/interactive/docs/gallery/columnchart#labeling-columns

How to create multi-series line chart

I am writing to seek help, in how do can I create multi-series line chart from [name] column below. Currently, I am plotting the chart using [date] and [tag] points. However, I would like to show multi-series line chart for each names. Is this plausible or does this task require manual functions to be created to link in with the API.
Please advice.
function drawVisualization() {
// Prepare the data
var data = google.visualization.arrayToDataTable([
['Name', 'Tag', 'Date'],
['ACCA', 45, 'May 14'],
['ABBA', 85, 'May 14'],
['ANNA', 100, 'May 14'],
['AMMA', 100.5, 'May 14'],
['ACCA', 99.5, 'May 15'],
['ABBA', 85.5, 'May 15'],
['ACCA', 99.6, 'May 15'],
['BACM', 94, 'May 15'],
['MMBS', 96, 'May 15']
]);
// Define category pickers for 'Name',
var countryPicker = new google.visualization.ControlWrapper({
'controlType': 'CategoryFilter',
'containerId': 'control1',
'options': {
'filterColumnLabel': 'Name',
'ui': {
'labelStacking': 'vertical',
'allowTyping': false,
'allowMultiple': false
}
}
});
var barChart = new google.visualization.ChartWrapper({
'chartType': 'LineChart',
'containerId': 'chart1',
'options': {
'width': 400,
'height': 300,
'chartArea': { top: 0, right: 0, bottom: 0 }
},
// Configure the Linechart to use columns 2 (Date) and 1 (Tag)
'view': { 'columns': [2, 1] }
});
// Define a table.
var table = new google.visualization.ChartWrapper({
'chartType': 'Table',
'containerId': 'chart2',
'options': {
'width': '300px'
}
});
new google.visualization.Dashboard(document.getElementById('dashboard')).bind([countryPicker], [barChart, table]).draw(data);
}
Edit:
Thanks.
To make this work, I would suggest removing the LineChart from your Dashboard, and using the Table's "ready" event to get the filtered data, create appropriate settings for the chart's view.columns parameter, and then drawing the chart with the filtered data:
google.visualization.events.addListener(table, 'ready', function () {
var filteredData = table.getDataTable();
// get a list of all the labels in column 0
var group = filteredData.getDistinctValues(0);
// build the columns for the view
var columns = [0];
for (var i = 0; i < group.length; i++) {
var label = group[i];
// set the columns to use in the chart's view
// calculated columns put data belonging to each country in the proper column
columns.push({
type: 'number',
label: label,
calc: (function (name) {
return function (dt, row) {
return (dt.getValue(row, 0) == name) ? dt.getValue(row, 1) : null;
}
})(label)
});
}
var view = barChart.getView() || {};
view.columns = columns;
barChart.setView(view);
barChart.setDataTable(filteredData);
barChart.draw();
});
new google.visualization.Dashboard(document.getElementById('dashboard')).bind([countryPicker], [table]).draw(data);

Categories