Google GeoCharts Colors Not Working - javascript

I have tried multiple things to apply but none of them seem to work to change my charts. I am uploading the array through a file and everything seems to work, even changing the defaultColor, but colorAxis does not seem to work. Could you guys(and girls) help me I would be grateful. Thanks
/* CSV handling - START */
var processedData = [];
var continent = $('select[name="continents"] option:selected').val();
$.get('example.csv', function(data) {
processedData = $.csv.toArrays(data);
}, 'text');
/* CSV handling - END */
/* Google Charts */
google.charts.load('current', {
'packages':['geochart'],
// Note: you will need to get a mapsApiKey for your project.
// See: https://developers.google.com/chart/interactive/docs/basic_load_libs#load-settings
'mapsApiKey': //doesn't matter
});
google.charts.setOnLoadCallback(drawRegionsMap);
function drawRegionsMap() {
var data = google.visualization.arrayToDataTable(processedData, false);
var options = {
sizeAxis: { minValue: 0, maxValue: 100 },
colorAxis: {colors: ['#e7711c', '#4374e0']},
region: continent,
width: '100%',
height: '100%',
backgroundColor: 'none'
};
var chart = new google.visualization.GeoChart(document.getElementById('chart_div'));
chart.draw(data, options);
}
/* Google Charts - End */

Please Refer To Google Developer reference
https://developers.google.com/chart/interactive/docs/gallery/geochart#important
var options = {
region: '002', // Africa
colorAxis: {colors: ['#00853f', 'black', '#e31b23']},
backgroundColor: '#81d4fa',
datalessRegionColor: '#f8bbd0',
defaultColor: '#f5f5f5',
};
https://developers.google.com/chart/interactive/docs/gallery/geochart#coloring-your-chart
var options = {
region: 'IT',
displayMode: 'markers',
colorAxis: {colors: ['green', 'blue']}
};
var chart = new google.visualization.GeoChart(document.getElementById('chart_div'));
chart.draw(data, options);

using the data from the comment, the chart colors seem to work
recommend removing the options for sizeAxis
the values in the data table range from 100 to 2313 (not 0 to 100),
the chart will handle by default
see following working snippet...
google.charts.load('current', {
callback: function () {
var processedData = [
['Country','Popularity'],
['HR',300.00],
['RU',100.00],
['FR',200.00],
['BR',2000.00],
['DZ',222.00],
['US',333.00],
['DE',555.00],
['DD',999.00],
['SZ',2313.00],
['AU',2222.00],
['BM',400.00],
['CA',322.00]
];
var data = google.visualization.arrayToDataTable(processedData);
var sizeRange = data.getColumnRange(1);
var options = {
colorAxis: {colors: ['#e7711c', '#4374e0']},
//region: continent,
width: '100%',
height: '100%',
backgroundColor: 'none'
};
var chart = new google.visualization.GeoChart(document.getElementById('chart_div'));
chart.draw(data, options);
},
packages: ['geochart']
});
<script src="https://www.gstatic.com/charts/loader.js"></script>
<div id="chart_div"></div>

Related

ColumnChart not show all string labels

I have The following problem related with ColumnChart (https://developers.google.com/chart/interactive/docs/gallery/columnchart).
If the label (when you mouse hover into any columns that looks like a tooltip) is set as a number, all 2000 items shows correctly. But if the label is set as a string it only shows 289 items in the chart and it is missing 1711 columns for an unknown reason.
I have this code (Label set with String, only shows 289 items instead of 2000):
http://jsfiddle.net/c809mbjx/11/
function drawChart() {
var data = new google.visualization.DataTable();
data.addColumn('string' ,'Day');
data.addColumn('number', 'Matches');
var dataArray = []
let number = 2000
data.addRows(number);
for (var i = 0; i < number;i++) {
data.setCell(i,0,"aaa_"+i)
data.setCell(i,1,i);
}
//var data = new google.visualization.arrayToDataTable(dataArray);
var chart = new google.visualization.ColumnChart(document.getElementById('chart_div'));
var view = new google.visualization.DataView(data);
view.setColumns([0, 1]);
var options = {
colors: ['#0095e8'],
hAxis: {textPosition: 'none'},
vAxis: {minValue: 0, viewWindow: {min: 0}},
legend: 'none',
animation: {duration: 10000, easing: 'out'}
};
chart.draw(view, options);
}
google.load('visualization', '1', {packages: ['corechart'], callback: drawChart});
And this code (Label set with Number and works correctly):
http://jsfiddle.net/c809mbjx/12/
function drawChart() {
var data = new google.visualization.DataTable();
data.addColumn('number' ,'Day');
data.addColumn('number', 'Matches');
var dataArray = []
let number = 2000
data.addRows(number);
for (var i = 0; i < number;i++) {
data.setCell(i,0,i)
data.setCell(i,1,i);
}
//var data = new google.visualization.arrayToDataTable(dataArray);
var chart = new google.visualization.ColumnChart(document.getElementById('chart_div'));
var view = new google.visualization.DataView(data);
view.setColumns([0, 1]);
var options = {
colors: ['#0095e8'],
hAxis: {textPosition: 'none'},
vAxis: {minValue: 0, viewWindow: {min: 0}},
legend: 'none',
animation: {duration: 10000, easing: 'out'}
};
chart.draw(view, options);
}
google.load('visualization', '1', {packages: ['corechart'], callback: drawChart});
we can use numbers on the x-axis and still display the string on the tooltip.
which can be accomplished by setting the last argument of the setCell method --> formattedValue
setCell(rowIndex, columnIndex, value, formattedValue)
the tooltip will display the formatted value by default.
so we provide the number as the value, and our own string as the formatted value.
data.setCell(i,0,i,"aaa_"+i);
see following working snippet...
google.charts.load('current', {
packages: ['corechart']
}).then(drawChart);
function drawChart() {
var data = new google.visualization.DataTable();
data.addColumn('number' ,'Day');
data.addColumn('number', 'Matches');
let number = 2000;
data.addRows(number);
for (var i = 0; i < number;i++) {
data.setCell(i,0,i,"aaa_"+i);
data.setCell(i,1,i);
}
var chart = new google.visualization.ColumnChart(document.getElementById('chart_div'));
var view = new google.visualization.DataView(data);
view.setColumns([0, 1]);
var options = {
colors: ['#0095e8'],
hAxis: {textPosition: 'none'},
vAxis: {minValue: 0, viewWindow: {min: 0}},
legend: 'none',
animation: {duration: 10000, easing: 'out'}
};
chart.draw(view, options);
}
<script src="https://www.gstatic.com/charts/loader.js"></script>
<div id="chart_div" style="width: 900px; height: 500px;"></div>
note: the version of google charts loaded using jsapi has been deprecated and should no longer be used.
instead, use loader.js, this will only change the load statement.
see above snippet...

Google chart stacked bar get key name when onclick

google.charts.load('current', { packages: ['corechart', 'bar'] });
google.charts.setOnLoadCallback(drawChart);
function drawChart() {
var data = google.visualization.arrayToDataTable([
['DATA', 'L', 'P'],
['PCX', 18, 21],['PCG', 131, 34],['PCO', 9, 3],['PGD', 441, 269],['PAH', 1, 1],['POD', 8, 5],['PCT', 80, 180],['PDD', 1, 7],['PZZ', 3, 8],['PKK', 461, 580],['PBI', 494, 248],['PKI', 2, 5],['PKL', 5, 1] ]);
var options = {
isStacked: 'percent',
legend: { position: 'top' },
chartArea: {
left: 40,
width: '100%',
height: '75%'
},
vAxis: {
minValue: 0,
},
hAxis: {
textStyle: { fontSize: 7 }
}
};
var chart = new google.visualization.ColumnChart(document.getElementById('DataChart'));
chart.draw(data, options);
google.visualization.events.addListener(chart, 'select', selectHandler);
function selectHandler(e) {
var selection = chart.getSelection();
if (selection.length > 0) {
var mydata = data.getValue(selection[0].row,0);
alert(mydata);
//i want get key data L when klik stacked data L or P when klik stacked data P, because i want to send data
chart.setSelection([]);
}
}
}
$(window).resize(function () {
drawChart();
});
svg > g > g:last-child { pointer-events: none }
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<script src="https://www.gstatic.com/charts/loader.js"></script>
<div id="DataChart" ></div>
Hello, i have a create stacked bar from google chart plugin, i want to get data when i'm click slice bar (red or blue) when i click red i get data "P" if i click blue get data "L" this demo in Js Fiddle
i'm already get data name data like PCX,PCG,PGD etc but i want get data "L" if click blue color and get data "P" when click red color. Help me thank's
to get the column label, use data table method --> getColumnLabel(colIndex)
pass the column property from the selection...
function selectHandler(e) {
var selection = chart.getSelection();
if (selection.length > 0) {
// get column label
var colLabel = data.getColumnLabel(selection[0].column);
var mydata = data.getValue(selection[0].row,0);
console.log(colLabel + ': ' + mydata);
chart.setSelection([]);
}
}
see following working snippet...
google.charts.load('current', {
packages: ['corechart']
}).then(function () {
$(window).resize(drawChart);
drawChart();
});
function drawChart() {
var data = google.visualization.arrayToDataTable([
['DATA', 'L', 'P'],
['PCX', 18, 21],['PCG', 131, 34],['PCO', 9, 3],['PGD', 441, 269],['PAH', 1, 1],['POD', 8, 5],['PCT', 80, 180],['PDD', 1, 7],['PZZ', 3, 8],['PKK', 461, 580],['PBI', 494, 248],['PKI', 2, 5],['PKL', 5, 1] ]);
var options = {
isStacked: 'percent',
legend: { position: 'top' },
chartArea: {
left: 40,
width: '100%',
height: '75%'
},
vAxis: {
minValue: 0,
},
hAxis: {
textStyle: { fontSize: 7 }
}
};
var chart = new google.visualization.ColumnChart(document.getElementById('DataChart'));
chart.draw(data, options);
google.visualization.events.addListener(chart, 'select', selectHandler);
function selectHandler(e) {
var selection = chart.getSelection();
if (selection.length > 0) {
var colLabel = data.getColumnLabel(selection[0].column);
var mydata = data.getValue(selection[0].row,0);
console.log(colLabel + ': ' + mydata);
chart.setSelection([]);
}
}
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<script src="https://www.gstatic.com/charts/loader.js"></script>
<div id="DataChart"></div>
In google charts document,
"If both row and column are specified, the selected element is a cell. If only row is specified, the selected element is a row. If only column is specified, the selected element is a column."
(https://developers.google.com/chart/interactive/docs/events)
In your demo, when clicking blueBar(L), selection[0].column will be 1 and the other(redBar(P)) will be 2.
Thus you can get P/L in selectHandler
var data = ['DATA', 'L', 'P']
function selectHandler(e) {
var selection = chart.getSelection();
if (selection.length > 0) {
var temp = selection[0].column
console.log(data[temp]) // temp = 1 will be 'L'; temp = 2 will be 'P'
}
}

Google Annotationchart - Rebase index=100 upon Rangechange

I have an Google Annotation Chart to show relative performance of different investments. User should be able compare performance over a selected time frame, that is, the series values should be rebased / indexed to 100 at the startdate of the visible range of the chart once the timeframe is changed.
Other packages like Amcharts offer a "comparable" function, so have been looking for options like "scaleColumns" and "scaleType" in Google Docs and in other questions here, not finding any clue on how to do this.
Is there any feature I can use and might have missed, or what would be the best approach to recalculate the DataTable with index=100 upon "rangechange".
Code and screenshot is below:
google.charts.load('current', {
packages: ['corechart', 'line', 'table','annotationchart']
});
google.charts.setOnLoadCallback(drawChart);
// ---------- Chart ---------------------------- //
function drawChart() {
//data query
var query = new google.visualization.Query(
'https://docs.google.com/spreadsheets/d/1Gw67zHpKyEd1nu_V698yqYqNgE0x21_ZE_QDHJmsgtE/gviz/tq?gid=803335131&headers=1&range=A1:n451');
query.send(handleQueryResponse);
}
function handleQueryResponse(response) {
if (response.isError()) {
alert('Error in query: ' + response.getMessage() + ' ' + response.getDetailedMessage());
return;
}
var data = response.getDataTable();
var options = {
title: 'Development of the choosen Portfolio since 2008',
legend: {
textStyle : { fontSize: 8 },
maxLines : 2,
position: 'top'
},
width: '30%',
height: 700,
lineWidth: 1,
hAxis: {
format: 'M/d/yy',
title: 'Time'
},
vAxis: {
scaleType: 'log',
title: 'Return (log scale)'
},
//theme: 'maximized',
chartArea:{
left:0,
top:20,
width:'30%',
height:'85%'
},
series: {
22: {
lineWidth: 3,
color: 'red'
}
}
};
var chart = new google.visualization.AnnotationChart(document.getElementById('chart_div'))
chart.draw(data, options);
}
google.visualization.events.addListener(chart, 'rangechange', rangechange_handler);
function rangechange_handler(e) {
console.log('You changed the range to ', e['start'], ' and ', e['end']);
// How to recalculate datatable to keep index=100 for all series upon rangechange?
}
Update:
There is a way, working on it: https://groups.google.com/forum/#!searchin/google-visualization-api/compare$20zoom|sort:relevance/google-visualization-api/8HjybllsufY/z5uak6AymLcJ
After an extended period of pain got it working, hope it helps somebody: https://jsfiddle.net/AlexHorn/a9z15syr/
var viewColumns = [0];
var colors = [];
for (var i = 0; i < columnIndices.length; i++) {
viewColumns.push({
label: data.getColumnLabel(columnIndices[i]),
type: 'number',
calc: (function(x) {
// use a closure here to lock the value of i to each column
return function(dt, row) {
// return the value normalized to the first row in the view
return dt.getValue(row, columnIndices[x]) / dt.getValue(0, columnIndices[x]);
};
})(i)
});
}

Google Charts on select event redraw chart with new data

Hey to all i have the code below for a google pie chart that takes data from a jsontable and i want when i click a slice to redraw the chart based on the selection.
I have the code below and i'm at a loss how to proceed
<head>
<style>
div.absolute {
position: absolute;
top: 120px;
}
</style>
<link href="style.css" rel="stylesheet" />
<!--Auto refresh code -->
<meta http-equiv="refresh" content="<?php echo $sec?>;URL='<?php echo $page?>'">
<!--Load the Ajax API-->
<script src="http://ajax.googleapis.com/ajax/libs/jquery/1.8.2/jquery.min.js"></script>
<script src="https://www.google.com/jsapi"></script>
<script src="http://www.google.com/jsapi?ext.js"></script>
<script src="https://rawgit.com/louisremi/jquery-smartresize/master/jquery.throttledresize.js"></script>
<script>
google.load('visualization', '1', {'packages':['corechart']});
google.setOnLoadCallback(initChart);
$(window).on("throttledresize", function (event) {
initChart();
});
function initChart() {
var options = {
title: 'Arrived Today (Email)',
width: '100%',
height: '100%',
sliceVisibilityThreshold: 0,
pieSliceText: 'percentage',
pieStartAngle: 100,
//is3D: 'true',
pieHole: 0.3,
slices: {
1: {offset: 0.2},
2: {offset: 0.3},
3: {offset: 0.4},
4: {offset: 0.5},
5: {offset: 0.6},
},
//slices: {0: {color: 'green'}, 1: {color: 'blue'}},
pieSliceBorderColor: 'black',
legend: 'right',
legendTextStyle: {fontSize: 15},
pieSliceText: 'value' ,
titleTextStyle: {
color: '333333',
fontName: 'Arial',
fontSize: 14 ,
align:'right'
},
chartArea : { left: 35 }
};
var data = new google.visualization.DataTable(<?=$jsonTable?>);
var data2 = new google.visualization.DataTable(<?=$jsonTable2?>);
var total = google.visualization.data.group(data,
[{
type: 'boolean',
column: 0,
modifier: function () {return true;}
}],
[{
type: 'number',
column: 1,
aggregation: google.visualization.data.sum
}]
);
document.getElementById("demo").innerHTML =total.getValue(0,1);
data.addRow(['Total: ' + total.getValue(0, 1), 0]);
drawChart(data, options)
}
function drawChart(data, options) {
var chart = new google.visualization.PieChart(document.getElementById('chart'));
chart.draw(data, options);
google.visualization.events.addListener(chart, 'select', selectHandler);
var label1 = data.pieSliceText('label');
// The selection handler.
// Loop through all items in the selection and concatenate
// a single message from all of them.
function selectHandler() {
var selection = chart.getSelection();
if (selection.length) {
var pieSliceLabel = data.getValue(selection[0].row, 0);
if (pieSliceLabel = 'External')
chart.draw(data2, options);
}
}
}
</script>
</head>
<body>
<h2 align="right"><font size="5">emails Arrived Today</font>
<div id="demo"></div>
</h2>
<div id="chart"></div>
</body>
thanks in advance for any help :)
function initChart() {
....
var data = new google.visualization.DataTable(<?=$jsonTable?>);
var data2 = new google.visualization.DataTable(<?=$jsonTable2?>);
....
}
function drawChart(data, options) {
google.visualization.events.addListener(chart, 'select', selectHandler);
function selectHandler() {
var selection = chart.getSelection();
if (selection.length) {
var pieSliceLabel = data.getValue(selection[0].row, 0);
if (pieSliceLabel = 'External')
chart.draw(data2, options);
}
}
}
Everything looks fine, except the scope of your variable data2.
You initiate it in your function initChart(), and then try to use it in a sub-function from drawChart().
Either you define your var data2 outside any javascript functions, or you pass it as a parameter when you call drawChart.

Animating column chart from google charts

I'm having trouble coming up with a function that will animate a single column bar inside of my chart when I use a slider going back and forth..left and right.. I have read the animation docs on the Google Charts API documentation, but I am having a hard time understanding what I need to do.
Here is my code so far. Where would I start in figuring out how to animate just one of my bars using a slider I have made in titanium? I call the function updateChart() from my app.js file using the evalJS function. I have verified it works, by doing a console.log when my slider goes back and forth. I just can't seem to wrap my head around it how to apply this to animating a single column bar. Any thoughts are appreciated.
Set up Google Charts on my html page.
<script type="text/javascript" src ="https://www.google.com/jsapi" > </script>
<script type="text/javascript ">
google.load("visualization", "1", {packages:["corechart"]});
google.setOnLoadCallback(drawChart);
function drawChart() {
var data = new google.visualization.DataTable();
data.addColumn('string', 'Importance');
data.addColumn('number', 'Earning');
data.addColumn({type: 'string', role: 'style'});
data.addRows([['',5,'#000000'], ['',5,'#ffffff'],['',5,'#666666'],['', 5,'#cccccc']]);
var options =
{
width: 200,
height: 240,
legend: {
position: 'none'
},
chartArea: {
backgroundColor: 'none'
},
bar: {
groupWidth: '100%'
},
animation: {
duration: 1000,
easing: 'out'
}
};
function updateChart() {
}
var chart = new google.visualization.ColumnChart(document.getElementById('chart_div'));
chart.draw(data, options);
}
EDITED CODE:
<script type="text/javascript" src ="https://www.google.com/jsapi" > </script>
<script type="text/javascript ">
google.load("visualization", "1", {packages:["corechart"]});
google.setOnLoadCallback(drawChart);
function drawChart() {
var data = new google.visualization.DataTable();
data.addColumn('string', 'Importance');
data.addColumn('number', 'Earning');
data.addColumn({type: 'string', role: 'style'});
data.addRows([['',5,'#000000'], ['',5,'#ffffff'],['',5,'#666666'],['', 5,'#cccccc']]);
var options = {
width: 200,
height: 240,
legend: {
position: 'none'
},
chartArea: {
backgroundColor: 'none'
},
bar: {
groupWidth: '100%'
},
animation: {
duration: 1000,
easing: 'out'
}
};
function updateChart(value) {
data.setValue(0, 1, value);
chart.draw(data, options);
}
var chart = new google.visualization.ColumnChart(document.getElementById('chart_div'));
chart.draw(data, options);
}
Slider Hook Code in separate file (app.js) Titanium Platform
var sliderBarOne = Titanium.UI.createSlider({
top: '310',
left: '610',
min: '0',
max: '10',
width: '37%',
value: '5',
backgroundImage: 'assets/sliderBar.png'
});
sliderBarOne.addEventListener('change', function(e) {
chartView.evalJS("updateChart('" + e.value + "');");
});
You need to hook up an event listener for your slider that calls the updateChart function. The updateChart function should get the value from the slider and change the value in the DataTable, then cal the chart's draw method. How you hook up an event listener to the slider is going to depend on the library you are using for the slider. Here's some example code that assumes your slider object has a change method to set a change event handler and a `getValue method to get the value of the slider:
[edit: added in your slider code]
function drawChart() {
var data = new google.visualization.DataTable();
data.addColumn('string', 'Importance');
data.addColumn('number', 'Earning');
data.addColumn({type: 'string', role: 'style'});
data.addRows([
['',5,'#000000'],
['',5,'#ffffff'],
['',5,'#666666'],
['', 5,'#cccccc']
]);
var options = {
width: 200,
height: 240,
legend: {
position: 'none'
},
chartArea: {
backgroundColor: 'none'
},
bar: {
groupWidth: '100%'
},
animation: {
duration: 1000,
easing: 'out'
}
};
var chart = new google.visualization.ColumnChart(document.getElementById('chart_div'));
function updateChart(value) {
data.setValue(0, 1, value);
chart.draw(data, options);
}
// create slider
var sliderBarOne = Titanium.UI.createSlider({
top: '310',
left: '610',
min: '0',
max: '10',
width: '37%',
value: '5',
backgroundImage: 'assets/sliderBar.png'
});
sliderBarOne.addEventListener('change', function(e) {
updateChart(e.value);
});
chart.draw(data, options);
}

Categories

Resources