Loop Google Chart Data Rows - javascript

I have my data in the below format, below is just a sample
var data = google.visualization.arrayToDataTable([
['Medium', 'Expenses'],
['Twitter', 400],
['Facebook', 460],
['Youtube', 1120],
['Instagram', 540]
]);
I want to loop through the records and give appropriate color to each platform.
I know it can be done for columns like below:
var view = new google.visualization.DataView(data);
var colors = [];
for (var i = 1; i < view.getNumberOfColumns(); i++) {
switch (view.getColumnLabel(i)) {
case "Twitter":
colors = colors.concat(["#26CEFF"]);
break;
}
I provide this to the chart in options as below:
var options = {
colors: colors
}
var chart = new google.visualization.PieChart(Div);
chart.draw(view, options);
But I am unable to loop through the rows to do the same functionality. Help appreciated.
Note: I cannot add the color property while creating the datatable. I have to do the functionality after creating the view or datatable only.

for a pie chart, you can loop using --> data.getNumberOfRows()
build the colors array based on the value of the first column --> Medium
see following working snippet...
google.charts.load('current', {
packages: ['corechart']
}).then(function () {
var data = google.visualization.arrayToDataTable([
['Medium', 'Expenses'],
['Twitter', 400],
['Facebook', 460],
['Youtube', 1120],
['Instagram', 540]
]);
var colors = [];
for (var i = 0; i < data.getNumberOfRows(); i++) {
switch (data.getValue(i, 0)) {
case 'Twitter':
colors.push('#26CEFF');
break;
case 'Facebook':
colors.push('blue');
break;
case 'Youtube':
colors.push('red');
break;
case 'Instagram':
colors.push('green');
break;
}
}
var options = {
colors: colors
};
var container = document.getElementById('chart_div');
var chart = new google.visualization.PieChart(container);
chart.draw(data, options);
});
<script src="https://www.gstatic.com/charts/loader.js"></script>
<div id="chart_div"></div>
for column or bar charts, the colors option won't work.
if there is only one series --> 'Expenses'
instead, need to use a 'style' role in the data table / view.
see following working snippet...
google.charts.load('current', {
packages: ['corechart']
}).then(function () {
var data = google.visualization.arrayToDataTable([
['Medium', 'Expenses'],
['Twitter', 400],
['Facebook', 460],
['Youtube', 1120],
['Instagram', 540]
]);
var view = new google.visualization.DataView(data);
view.setColumns([0, 1, {
calc: function (dt, row) {
var color;
switch (dt.getValue(row, 0)) {
case 'Twitter':
color = '#26CEFF';
break;
case 'Facebook':
color = 'blue';
break;
case 'Youtube':
color = 'red';
break;
case 'Instagram':
color = 'green';
break;
}
return color;
},
type: 'string',
role: 'style'
}]);
var options = {
legend: 'none'
};
var container = document.getElementById('chart_div');
var chart = new google.visualization.ColumnChart(container);
chart.draw(view, options);
});
<script src="https://www.gstatic.com/charts/loader.js"></script>
<div id="chart_div"></div>

Related

Why would I have to do chart.draw twice to get a Google pie chart to display?

I have a page in an app that displays all sorts of ticket metrics from several different ticketing systems we use. I use the same function to build each of the charts and display them:
function drawChart(chartData, chartStyle, chartTitle, chartSpanID) {
var data = new google.visualization.DataTable();
data.addColumn('string', 'Hour');
data.addColumn('number', 'Tickets');
data.addRows(chartData);
if(chartStyle == "column"){
var chart = new google.visualization.ColumnChart(document.getElementById(chartSpanID));
var options = {title:chartTitle,chartArea: {left: 30, top:20, bottom:30, right:10},animation:{startup: true, duration:2000}}
};
if(chartStyle == "pie"){
var chart = new google.visualization.PieChart(document.getElementById(chartSpanID));
var options = {title:chartTitle,
chartArea:{left: 0, top:20, bottom:10, right: 0},
is3D: true,
sliceVisibilityThreshold: .01,
animation:{startup: true,easing: 'in', duration:1000},
pieResidueSliceLabel: "Other( < 1%)"};
};
chart.draw(data, options);
}
This works for 13 of the 14 charts displayed on the page. 8 Columns and 5 out of 6 pie charts all display perfectly. One of the pie charts will ONLY display if I draw the chart a second time.
function drawChart(chartData, chartStyle, chartTitle, chartSpanID) {
var data = new google.visualization.DataTable();
data.addColumn('string', 'Hour');
data.addColumn('number', 'Tickets');
data.addRows(chartData);
if(chartStyle == "column"){
var chart = new google.visualization.ColumnChart(document.getElementById(chartSpanID));
var options = {title:chartTitle,chartArea: {left: 30, top:20, bottom:30, right:10},animation:{startup: true, duration:2000}}
};
if(chartStyle == "pie"){
var chart = new google.visualization.PieChart(document.getElementById(chartSpanID));
var options = {title:chartTitle,
chartArea:{left: 0, top:20, bottom:10, right: 0},
is3D: true,
sliceVisibilityThreshold: .01,
animation:{startup: true,easing: 'in', duration:1000},
pieResidueSliceLabel: "Other( < 1%)"};
};
chart.draw(data, options);
chart.draw(data, options);
}
The data is delivered correctly, all calls are made through google.charts.setOnLoadCallback, it all works just fine once called again... so why is it only working on the second call? Why just the one chart that doesn't display as expected? What have I missed?

Hyperlinks on Google GeoChart with Markers

I do have this on my website running:
<script type='text/javascript' src="https://www.gstatic.com/charts/loader.js"></script>
<script type="text/javascript">
google.charts.load('current', {
callback: drawVisualization,
packages:['geochart']
});
function drawVisualization() {
var data = google.visualization.arrayToDataTable([
['Country','Link',],
['United States','https://proyectoviajero.com/destinos/america-del-norte/guia-viaje-estados-unidos/'],
['Japan','https://www.proyectoviajero.com'],
['Saint Lucia','https://www.proyectoviajero.com'],
['Peru','https://proyectoviajero.com/destinos/america-del-sur/guia-viaje-peru/'],
['Chile','https://proyectoviajero.com/destinos/america-del-sur/guia-viaje-chile/'],
['Argentina','https://proyectoviajero.com/destinos/america-del-sur/guia-viaje-argentina/'],
['Bolivia','https://proyectoviajero.com/destinos/america-del-sur/guia-viaje-bolivia/'],
['Brazil','https://proyectoviajero.com/destinos/america-del-sur/guia-viaje-brasil/'],
['Spain','https://proyectoviajero.com/destinos/europa/guia-viaje-espana/'],
['Portugal','https://www.proyectoviajero.com'],
['Italy','https://www.proyectoviajero.com'],
['Belgium','https://www.proyectoviajero.com'],
['France','https://www.proyectoviajero.com'],
['Germany','https://www.proyectoviajero.com'],
['United Kingdom','https://www.proyectoviajero.com'],
['Poland','https://www.proyectoviajero.com'],
['Ukraine','https://www.proyectoviajero.com'],
['Hungary','https://proyectoviajero.com/destinos/europa/guia-viaje-hungria/'],
['Czechia','https://www.proyectoviajero.com'],
['Turkey','https://www.proyectoviajero.com'],
['Morocco','https://proyectoviajero.com/destinos/africa/guia-viaje-marruecos/'],
['Western Sahara','https://proyectoviajero.com/destinos/africa/guia-viaje-marruecos/'],
['Tunisia','https://www.proyectoviajero.com'],
['Switzerland','https://www.proyectoviajero.com'],
['Finland','https://www.proyectoviajero.com'],
['Estonia','https://proyectoviajero.com/destinos/europa/guia-viaje-estonia/'],
['Iceland','https://proyectoviajero.com/destinos/europa/guia-viaje-islandia/'],
['Philippines','https://www.proyectoviajero.com'],
['Greece','https://www.proyectoviajero.com'],
['Bulgary','https://www.proyectoviajero.com'],
['Croatia','https://www.proyectoviajero.com'],
['Brunei','https://proyectoviajero.com/destinos/asia/guia-viaje-brunei/'],
['Qatar','https://proyectoviajero.com/destinos/asia/guia-viaje-qatar/'],
['United Arab Emirates','https://proyectoviajero.com/destinos/asia/guia-viaje-emiratos-arabes/'],
]);
var view = new google.visualization.DataView(data);
view.hideColumns([1]);
var options = {
backgroundColor: 'white',
datalessRegionColor: '#F5F5F5',
defaultColor: '#ffc17f',
displayMode: 'regions',
tooltip: {textStyle: {color: '#222222'}, trigger:'focus',isHtml: true},
legend: 'none',
};
var chart = new google.visualization.GeoChart(document.getElementById('visualization'));
google.visualization.events.addListener(chart, 'select', myClickHandler);
chart.draw(view, options);
function myClickHandler(){
var selection = chart.getSelection();
if (selection.length > 0) {
var link = data.getValue(selection[0].row, 1);
window.open(link, '_blank');
}
}
}
</script>
I am trying to plot a country (i.e. Spain) with two markers (i.e Madrid and Barcelona as a red circle) with hyperlinks to an external webpage.
But I do not know how to modify it. Basically I am trying to reach the same result in THIS webpage.
Can anyone help me please? Thanks!

Google chart, set minimum range on axis

I have an line/area chart, I want to set a minimum range on the y-axis.
Let's say my points are [0,300],[1,270],[2,230],[3,260] (those are retrieved through ajax, so they're not static).
I want the y-axis range to be at least 100, but by default google will set maximum as maximum value (300 in this case), and minimum at minimum value (230 in this case), so range in this case would be (and it is actually) 70, I want it to be at least 100, so the chart maximum should be (300+230)/2+50 and minimum (300+230)/2-50, so that I have a 100 range and the chart i vertically center aligned.
I want the range to have a minimum but not a maximum, if my points are [0,100],[1,240],[5,160] then range should match the data range (140 in this case) also if the optimum is smaller (100).
Basically I don't want the chart to show a big difference when the actual difference in data is small. I know how to set fixed maximum and minimum on axis, but that doesn't solve my problem.
This is my actual code:
$.fn.createChart = function(url,options){
var obj = $(this);
console.log('CREATING CHART: '+url);
// Load the Visualization API and the linechart package.
if(!$.canAccessGoogleVisualization()){
google.charts.load('current', {packages: ['corechart', 'line']});
}
// Set a callback to run when the Google Visualization API is loaded.
google.charts.setOnLoadCallback(drawChart);
function drawChart() {
var jsonData = $.ajax({
url: url ,
dataType: "json",
async: false
}).responseText;
// Create our data table out of JSON data loaded from server.
var data = new google.visualization.DataTable(jsonData);
//Default options
var def = {
width: obj.width(),
height: obj.height(),
curveType: 'function',
legend: { position: 'bottom' },
hAxis: {
format: 'dd/MM'
},
animation:{
"startup": true,
duration: 1000,
easing: 'out',
}
};
//Overwrite default options with passed options
var options = typeof options !== 'undefined' ? $.mergeObjects(def,options) : def;
// Instantiate and draw our chart, passing in some options.
var chart = new google.visualization.AreaChart(obj.get(0));
chart.draw(data, options);
}
}
$.mergeObjects = function(obj1,obj2){
for (var attrname in obj2) { obj1[attrname] = obj2[attrname]; }
return obj1;
}
$.canAccessGoogleVisualization = function()
{
if ((typeof google === 'undefined') || (typeof google.visualization === 'undefined')) {
return false;
}
else{
return true;
}
}
you can use the getColumnRange method on the DataTable to find the min and max
then apply you're logic to set the viewWindow on the vAxis
see following working snippet...
google.charts.load('current', {
callback: function () {
var data = google.visualization.arrayToDataTable([
['X', 'Y'],
[0, 300],
[1, 270],
[2, 230],
[3, 260]
]);
var yMin;
var yMax;
var columnRange = data.getColumnRange(1);
if ((columnRange.max - columnRange.min) < 100) {
yMin = ((columnRange.max + columnRange.min) / 2) - 50;
yMax = ((columnRange.max + columnRange.min) / 2) + 50;
} else {
yMin = columnRange.min;
yMax = columnRange.max;
}
var chart = new google.visualization.AreaChart(document.getElementById('chart_div'));
chart.draw(data, {
vAxis: {
viewWindow: {
min: yMin,
max: yMax
}
}
});
},
packages: ['corechart']
});
<script src="https://www.gstatic.com/charts/loader.js"></script>
<div id="chart_div"></div>

Make Two Google charts in the same page

I am triying to put two google charts of the same style, but when i try it, one is visible and one didnt appear.
So, here's the code.
google.charts.load('current', {'packages':['bar']});
google.charts.setOnLoadCallback(drawChart);
function drawChart() {
var data = google.visualization.arrayToDataTable([
['Year', 'Sales'],
['2014', 1000],
['2015', 1170],
['2016', 660],
['2017', 1030]
]);
var options = {
chart: {
title: 'Company Performance',
subtitle: 'Sales, Expenses, and Profit: 2014-2017',
}
};
var chart = new google.charts.Bar(document.getElementById('columnchart_material'));
chart.draw(data, options);
}
What variables I need to change to make an other chart like this??
the script is looking for the id selector, in html the id is unique
so add a new div with antoher id and at the end of your script do
var chart = new google.charts.Bar(document.getElementById('columnchart_material'));
var chartOther = new google.charts.Bar(document.getElementById('columnchart_material_other'));
chart.draw(data, options);
chartOther.draw(data, options );
if you want to use a classname you could draw the same charts for all elements with class some like this:
var charts = document.getElementsByClassName("yourclass");
for (var i = 0; i < charts; i++) {
var chart = new google.charts.Bar(charts[i]);
chart.draw(data, options);
};

Unable to populate Google Graph Line Chart

Below is how I populate it but it is not working:
var data = new google.visualization.DataTable();
var newData =[];
for(var j = 0; j<dates.length;j++){
newData.push([dates[j],close[j]]);
document.write(newData[j] + "<br>");
}
// determine the number of rows and columns.
var numRows = newData.length;
var numCols = newData[0].length;
data.addColumn('number', 'Date');
data.addColumn('number', 'Close');
// now add the rows.
for (var j = 0; j < numRows; j++){
data.addRow(newData[j]);
}
var options = {
hAxis: {
title: 'Date'
},
vAxis: {
title: 'Closing Price'
},
backgroundColor: '#f1f8e9'
};
var chart = new google.visualization.LineChart(document.getElementById('chart_div'));
chart.draw(data, options);
newData values are as below when printed out:
20151229,108.74
20151228,106.82
20151224,108.03
20151223,108.61
20151222,107.23
It shows no error and no graph is showing out. What could be wrong in the code above ?
function drawChart() {
var data = google.visualization.arrayToDataTable([
['Year', 'Sales', 'Expenses'],
['2004', 1000, 400],
['2005', 1170, 460],
['2006', 660, 1120],
['2007', 1030, 540]
]);
var options = {
title: 'Company Performance',
curveType: 'function',
legend: { position: 'bottom' }
};
var chart = new google.visualization.LineChart(document.getElementById('curve_chart'));
chart.draw(data, options);
}
So since you have only 2 columns, you can completely get rid of the 3rd expenses.

Categories