Make Two Google charts in the same page - javascript

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);
};

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!

Loop Google Chart Data Rows

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>

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.

Unable to Show Labels in Google Scatter Chart

I seem to be unable to get this Google Chart Scatter Plot to display the score.partner as a label. I can only get them to show as tooltips.
What am I doing wrong?
drawChart: function() {
var self = this;
var gdpMin = parseFloat(self.scores[0].gdpScore);
var gdpMax = gdpMin;
var teaMin = parseFloat(self.scores[0].teaScore);
var teaMax = teaMin;
var data = new google.visualization.DataTable();
data.addColumn('number', 'GDP Score');
data.addColumn('number', 'TEA Score');
data.addColumn({type:'string', role:'label'});
$.each(self.scores, function(i, score) {
gdpScore = parseFloat(score.gdpScore);
teaScore = parseFloat(score.teaScore);
data.addRows([[gdpScore, teaScore, score.partner]]);
if (gdpScore < gdpMin) gdpMin = gdpScore;
if (gdpScore > gdpMax) gdpMax = gdpScore;
if (teaScore < teaMin) teaMin = teaScore;
if (teaScore > teaMax) teaMax = teaScore;
});
var options = {
title: 'GDP and TEA Scores',
hAxis: {title: 'GDP', minValue: gdpMin, maxValue: gdpMax},
vAxis: {title: 'TEA', minValue: teaMin, maxValue: teaMax},
legend: 'none',
colors: ['#3B7CBF']
};
var chart = new google.visualization.ScatterChart(document.getElementById('chart_div'));
chart.draw(data, options);
From user asgallant in Google Visualization API Group:
You want to label individual points on a ScatterChart? That isn't
supported. Depending on the structure of your data, you may be able
to use a LineChart in a manner similar to a ScatterChart. See an
example here: jsfiddle.net/asgallant/YFMga/
There you have it. Labels are not supported for scatter plots using the Google Visualization API.
jqPlot may be an acceptable alternative.

Categories