GeoCharts how to show country names instead of codes - charts

I would like to make a visualization with the google GeoChart. I put in country codes. I would like to display the full country names but only the country code pops up.
google.charts.load('current', {
'packages': ['geochart'],
'mapsApiKey': 'AIzaSyD-9tSrke72PouQMnMX-a7eZSW0jkFMBWY'
});
google.charts.setOnLoadCallback(drawRegionsMap);
function drawRegionsMap() {
var data = google.visualization.arrayToDataTable([
['Country', 'Members'],
['LB', 3],
['JO', 2],
['IT', 24],
['PS', 3],
['LY', 1],
['TN', 6],
['LB', 3],
['EG', 2],
]);
var options = {
colorAxis: {
colors: ['#c1c1cd', '#53556e']
},
legend: 'none'
};
var chart = new google.visualization.GeoChart(document.getElementById('regions_div'));
chart.draw(data, options);
}
<script type="text/javascript" src="https://www.gstatic.com/charts/loader.js"></script>
<div id="regions_div" style="width: 900px; height: 500px;"></div>

using object notation,
you can provide the value (v:) and the formatted value (f:)
{v: 'IT', f: 'Italy'}
the tooltip will display the formatted value by default
update the data using object notation and provide the name as the formatted value
see following working snippet,
hover over Italy to see the result...
google.charts.load('current', {
'packages': ['geochart'],
'mapsApiKey': 'AIzaSyD-9tSrke72PouQMnMX-a7eZSW0jkFMBWY'
});
google.charts.setOnLoadCallback(drawRegionsMap);
function drawRegionsMap() {
var data = google.visualization.arrayToDataTable([
['Country', 'Members'],
['LB', 3],
['JO', 2],
[{v: 'IT', f: 'Italy'}, 24],
['PS', 3],
['LY', 1],
['TN', 6],
['LB', 3],
['EG', 2],
]);
var options = {
colorAxis: {
colors: ['#c1c1cd', '#53556e']
},
legend: 'none'
};
var chart = new google.visualization.GeoChart(document.getElementById('regions_div'));
chart.draw(data, options);
}
<script type="text/javascript" src="https://www.gstatic.com/charts/loader.js"></script>
<div id="regions_div" style="width: 900px; height: 500px;"></div>

Based on the WhiteHat's answer I added some code to automatize the introduction of the formatted values.
// iso to name conversion
// https://gist.github.com/maephisto/9228207
var isoCountries = {
'IT': 'Italy',
'JO': 'Jordan',
'LB': 'Lebanon',
};
function getCountryName(countryCode) {
if (isoCountries.hasOwnProperty(countryCode)) {
return isoCountries[countryCode];
} else {
return countryCode;
}
};
// Load the Visualization API and the corechart package.
google.charts.load('current', {
'packages': ['geochart'],
'mapsApiKey': 'AIzaSyD-9tSrke72PouQMnMX-a7eZSW0jkFMBWY'
});
// Set a callback to run when the Google Visualization API is loaded.
google.charts.setOnLoadCallback(drawRegionsMap);
// Callback that creates and populates a data table,
// instantiates the chart, passes in the data and
// draws it.
function drawRegionsMap() {
// Create the data table.
var data = new google.visualization.DataTable();
data.addColumn('string', 'Country');
data.addColumn('number', 'Members');
data.addRows([
['LB', 3],
['JO', 2],
['IT', 24],
]);
// Set chart options
var options = {
colorAxis: {
colors: ['#c1c1cd', '#53556e']
},
legend: 'none',
backgroundColor: '#efefef'
};
// Create new data table for iso and full country name
var dataMod = new google.visualization.DataTable();
dataMod.addColumn('string', 'Country');
dataMod.addColumn('number', 'Members');
// Adding rows with iso and full country name
var numRows = data.getNumberOfRows();
for (var i = 0; i < numRows; i++) {
dataMod.addRows([
[{
v: String(data.getValue(i, 0)),
f: String(getCountryName(data.getValue(i, 0)))
}, data.getValue(i, 1)],
]);
};
// Instantiate and draw our chart, passing in some options.
var chart = new google.visualization.GeoChart(document.getElementById('regions_div'));
chart.draw(dataMod, options);
}
<script type="text/javascript" src="https://www.gstatic.com/charts/loader.js"></script>
<div id="regions_div" style="width: 900px; height: 500px;"></div>

Related

i am working on google bar charts, i am stuck with adding colours to individual bars

<!DOCTYPE html>
<html lang="en-US">
<body>
<h1>My Web Page</h1>
<div id="piechart"></div>
<script type="text/javascript" src="https://www.gstatic.com/charts/loader.js"></script>
<script type="text/javascript">
// Load google charts
google.charts.load('current', {'packages':['corechart']});
google.charts.setOnLoadCallback(drawChart);
// Draw the chart and set the chart values
var a = [['Work', 8], ['Eat', 2], ['TV', 4], ['Gym', 2], ['Sleep', 8], ['walk', 2], ['games', 2], ['chess', 2], ['drink', 4], ['dance', 6]];
a.sort(compareSecondColumn);
function compareSecondColumn(a, b) {
if (a[1] === b[1]) {
return 0;
}
else {
return (a[1] > b[1]) ? -1 : 1;
}
}
// Draw the chart and set the chart values
function drawChart() {
var data = google.visualization.arrayToDataTable([
['Task', 'Hours per Day'],a[0],a[1],a[2],a[3],a[4]
]);
// Optional; add a title and set the width and height of the chart
var options = { 'title': 'the title', 'width': 550, 'height': 400 };
// Display the chart inside the <div> element with id="piechart"
var chart = new google.visualization.ColumnChart(document.getElementById('piechart'));
chart.draw(data, options);
}
</script>
</body>
</html>
i am using bar chart, it only display default blue color.
i have used an array which removes the column which doesnot have data(like 0)
like sorting the data
i want to display individual color for each column
like red, green any different colors for each bar
i like to add annotations also
thanks in advance
the column headings and values posted in the above comments seem to work fine here...
the only changes made...
add type property to style and annotation roles.
added different colors for style role.
see following working snippet...
var a = [['Work', 8, "#E53935", 8], ['Eat', 2, "#1E88E5", 2], ['TV', 4, "#43A047", 4]];
a.sort(compareSecondColumn);
function compareSecondColumn(a, b) {
if (a[1] === b[1]) {
return 0;
}
else {
return (a[1] > b[1]) ? -1 : 1;
}
}
google.charts.load('current', {
packages: ['corechart']
}).then(function drawChart() {
var data = google.visualization.arrayToDataTable([
['Task', 'Hours per Day', {role: 'style', type: 'string'}, {role: 'annotation', type: 'number'}],a[0],a[1],a[2]
]);
var options = {
title: 'the title',
width: 550,
height: 400,
legend: 'none'
};
var chart = new google.visualization.ColumnChart(document.getElementById('piechart'));
chart.draw(data, options);
});
<script src="https://www.gstatic.com/charts/loader.js"></script>
<div id="piechart"></div>

Google Visualization SteppedAreaChart with time as axis incorrectly aligned

I'm creating a SteppedArea chart in Google Visualization to display queue length at various times of the day. My problem is that the steps in the chart don't align with the associated times. They are always one data point out. In the example below, my dataTable has 9:00 = 0, 12:00 = 3 and 14:00 = 6, but the resultant chart offsets the values, so it appears the queue between 9 and 12 is 3 when it really should be 0.
Is this a bug in the Chart rendering or am misunderstanding something ?
I guess my workaround is to offset my initial dataTable.
google.charts.load('current', {'packages':['corechart']});
google.charts.setOnLoadCallback(drawChart);
function drawChart() {
var data = new google.visualization.DataTable();
data.addColumn('timeofday', 'Time of Day');
data.addColumn('number', 'Queue Length');
// DataTable of Time and Queue length
data.addRows([
[[9,0,0], 0],
[[12,0,0], 3],
[[14,0,0], 6],
]);
var options = {
width: 500,
height: 500,
legend: {position: 'top'},
enableInteractivity: false,
chartArea: {
width: '85%'
},
hAxis: {
viewWindow: {
min: [8,0,0],
max: [15,0,0]
},
gridlines: {
count: -1,
units: {hours: {format: ['h a']}}
},
minorGridlines: {count: 0},
}
};
var chart = new google.visualization.SteppedAreaChart(
document.getElementById('chart_div'));
chart.draw(data, options);
}
<script type="text/javascript" src="https://www.gstatic.com/charts/loader.js"></script>
<div id="chart_div"></div>
I've shifted the data via a view which seems to give me the right looking chart. See the example which shows before and after. Note I had to add a dummy point at the end of the dataset otherwise the last point gets missed off. I also had to assume the first point would be zero which is acceptable in my case. Unless another idea surfaces I'll go with this.
google.charts.load('current', {'packages':['corechart']});
google.charts.setOnLoadCallback(drawChart);
function drawChart() {
var data = new google.visualization.DataTable();
data.addColumn('timeofday', 'Time of Day');
data.addColumn('number', 'Queue Length');
data.addRows([
[[9,0,0], 2],
[[11,30,0], 1],
[[12,0,0], 2],
[[13,0,0], 3],
[[14,0,0], 2],
]);
var options = {
width: 500,
height: 500,
legend: {position: 'top'},
enableInteractivity: false,
chartArea: {
width: '85%'
},
hAxis: {
viewWindow: {
min: [8,0,0],
max: [15,0,0]
},
gridlines: {
count: -1,
units: {hours: {format: ['h a']}}
},
minorGridlines: {count: 0},
}
};
var chart = new google.visualization.SteppedAreaChart(
document.getElementById('chart_div'));
chart.draw(data, options);
// need to add dummy point to end.
data.addRows([
[[23,59,0], 0]
]);
// use a view to shift the data so that it returns the value from previous row.
var data2 = new google.visualization.DataView(data);
data2.setColumns([0,
{calc: function (dt, row) {
if (row === 0) {return 0}
else {return dt.getValue(row-1,1)}
},
label: 'Queue Moved',type: 'number'}
]);
var chart2 = new google.visualization.SteppedAreaChart(
document.getElementById('chart2_div'));
chart2.draw(data2, options);
}
<script type="text/javascript" src="https://www.gstatic.com/charts/loader.js"></script>
<h1>Has Wrong transition times</h1>
<div id="chart_div"></div>
<h1>Looks Correct : Has transition shifted via view</h1>
<div id="chart2_div"></div>

Google Line Chart - Show Data Values on Points by default

I want to show data values on the line chart, i.e. which appear on mouse over, i need them all displayed by default. I tried the solution here Google Charts API: Always show the Data Point Values in Graph
data.addColumn({type: 'number', role: 'annotation'});
I added this to my code (I'm not sure where to put it exactly) but It didn't make any change.
Here is part of my code:
<!DOCTYPE html>
<html>
<head>
<title>Week/Orders</title>
<script type="text/javascript" src="loader.js"></script>
<script type="text/javascript">
google.charts.load('current', {'packages':['corechart']});
google.charts.setOnLoadCallback(drawChart);
function drawChart(){
var data = new google.visualization.DataTable();
var data = google.visualization.arrayToDataTable([
['Week','Orders'],
<?php
while($row = mysqli_fetch_assoc($aresult)){
echo "['".$row["Week"]."', ".$row["Orders"]."],";
}
?>
]);
var options = {
title: 'Week Vs Orders',
'width':1700,
'height':600,
legend: { position: 'bottom' }
};
var chart = new google.visualization.LineChart(document.getElementById('curvechart'));
chart.draw(data, options);
}
</script>
</head>
<body>
<div id="curvechart" style="width: 900px; height: 400px"></div>
</body>
</html>
I have two values; Week and Orders. I need only the "Order" value displayed on the graph by default. How can I do this? Thanks.
you can use a DataView to add annotations to the chart
var view = new google.visualization.DataView(data);
view.setColumns([0, 1, {
calc: 'stringify',
sourceColumn: 1,
type: 'string',
role: 'annotation'
}]);
see following working snippet...
google.charts.load('current', {'packages':['corechart']});
google.charts.setOnLoadCallback(drawChart);
function drawChart(){
var data = google.visualization.arrayToDataTable([
['Week','Orders'],
['1', 5],
['2', 6],
['3', 4]
]);
var view = new google.visualization.DataView(data);
view.setColumns([0, 1, {
calc: 'stringify',
sourceColumn: 1,
type: 'string',
role: 'annotation'
}]);
var options = {
title: 'Week Vs Orders',
width: 1700,
height: 600,
legend: {position: 'bottom'}
};
var chart = new google.visualization.LineChart(document.getElementById('curvechart'));
chart.draw(view, options); // <-- use data view
}
<script src="https://www.gstatic.com/charts/loader.js"></script>
<div id="curvechart"></div>

Second Y axis in stacked (positive/negative) bar chart in Google Charts

I have build a stacked bar chart to illustrate positive and negative values which looks like this:
Because these values indicate opposites I want to add additional labels to a right Y axis. Is this even possible? My code so far:
var data = google.visualization.arrayToDataTable([
['Type', 'Value1', 'Value2'],
['Left-1', 0, -5],
['Left-2', 0, -3],
['Left-3', 0, 0],
['Left-4', 3, 0],
['Left-5', 5, 0]
]);
var options = {
legend: 'none',
hAxis: {
minValue: -6,
maxValue: 6
}
}
var chart = new google.visualization.BarChart(document.getElementById('chart_div'));
chart.draw(data, options);
jsfiddle: https://jsfiddle.net/cLz5nffm/
there aren't any standard options for an additional axis in this configuration
but you can add custom labels
once the 'ready' event fires
see following working snippet...
google.charts.load('current', {
callback: drawChart,
packages: ['corechart']
});
function drawChart() {
var data = google.visualization.arrayToDataTable([
['Type', 'Value1', 'Value2'],
['Left-1', 0, -5],
['Left-2', 0, -3],
['Left-3', 0, 0],
['Left-4', 3, 0],
['Left-5', 5, 0]
]);
var options = {
legend: 'none',
hAxis: {
minValue: -6,
maxValue: 6
}
}
var chartDiv = document.getElementById('chart_div');
var chart = new google.visualization.BarChart(chartDiv);
google.visualization.events.addListener(chart, 'ready', function () {
Array.prototype.forEach.call(chartDiv.getElementsByTagName('text'), function(axisLabel) {
if (axisLabel.getAttribute('text-anchor') === 'end') {
addLabel(
axisLabel,
chart.getChartLayoutInterface().getChartAreaBoundingBox().left +
chart.getChartLayoutInterface().getChartAreaBoundingBox().width - 24 // <-- find good width
);
}
});
function addLabel(label, xOffset) {
var axisLabel = label.cloneNode(true);
axisLabel.setAttribute('x', parseFloat(label.getAttribute('x')) + xOffset);
axisLabel.innerHTML = label.innerHTML.replace('Left-', 'Right ');
chartDiv.getElementsByTagName('svg')[0].appendChild(axisLabel);
}
});
chart.draw(data, options);
}
<script src="https://www.gstatic.com/charts/loader.js"></script>
<div id="chart_div"></div>

How to edit one of two Google charts on the one page?

I've added Google chart to my page. This returns an images of a charts. It is ok. But I want to edit only one of them and this is problem. It edit only the first one, but I want to edit for example only the second one. Can anybody help me? Here is my code:
//draw charts
google.charts.load('current', {'packages': ['corechart']});
google.charts.setOnLoadCallback(drawChart);
function drawChart() {
var data = new google.visualization.DataTable();
data.addColumn('string', 'Value');
data.addColumn('number', 'Total count');
data.addRows([
["A", 4],
["B", 1],
]);
var options = {
title: "Choose something"
};
var chart = new google.visualization.PieChart(document.getElementById(304));
chart.draw(data, options);
var data305 = new google.visualization.DataTable();
data305.addColumn('string', 'Value');
data305.addColumn('number', 'Total count');
data305.addRows([
["Male", 2],
["Female", 2],
]);
var options305 = {
title: "Gender"
};
var chart305 = new google.visualization.PieChart(document.getElementById(305));
chart305.draw(data305, options305);
}
//edit charts
google.load('visualization', '1.0', {packages: ['charteditor']});
var chartEditor = null;
function loadEditor() {
// Create the chart to edit.
var data = new google.visualization.DataTable();
data.addColumn('string', 'Value');
data.addColumn('number', 'Total count');
data.addRows([
["A", 4],
["B", 1],
]);
var wrapper = new google.visualization.ChartWrapper({
chartType: 'PieChart',
dataTable: data,
options: {'title': 'Pohlavi'},
containerId: '304'
});
chartEditor = new google.visualization.ChartEditor();
google.visualization.events.addListener(chartEditor, 'ok', redrawChart);
chartEditor.openDialog(wrapper, {});
//---------------------------------------
// Create the chart to edit.
var data305 = new google.visualization.DataTable();
data305.addColumn('string', 'Value');
data305.addColumn('number', 'Total count');
data305.addRows([
["Male", 2],
["Female", 2],
]);
var wrapper305 = new google.visualization.ChartWrapper({
chartType: 'PieChart',
dataTable: data,
options: {'title': 'Pohlavi'},
containerId: '305'
});
chartEditor305 = new google.visualization.ChartEditor();
google.visualization.events.addListener(chartEditor305, 'ok', redrawChart);
chartEditor.openDialog(wrapper305, {});
}
// On "OK" save the chart to a <div> on the page.
function redrawChart(inputId){
chartEditor.getChartWrapper().draw(document.getElementById(304));
}
function redrawChart305(inputId){
chartEditor305.getChartWrapper().draw(document.getElementById(305));
}
and here ienter code heres my html:
<script type="text/javascript" src="https://www.google.com/jsapi"></script>
<script type="text/javascript" src="https://www.gstatic.com/charts/loader.js"></script>
<button onclick="loadEditor()">Click me</button>
<div id="304" style="height: 400px; width: 600px;"></div>
<button onclick="loadEditor()">Click me</button>
<div id="305" style="height: 400px; width: 600px;"></div>
<div id="vis_div" style="height: 400px; width: 600px;"></div>
Where is mistake?
Thanks