Google pie chart color depending on value - javascript

I have a chart where I only count the number of values for only two categories.
What I want is to color in green for that category having the max value and in blue for the one having the min value.
From the two quantity values, I want to determine inside the loop, the value that has the higher value. So the green color will be displayed for that value inside the pie chart, in this case, to be able to choose either 0 or 1 inside the options part, at the slices.
So far this is my code:
<script type="text/javascript">
google.charts.load('current', {'packages':['corechart']});
google.charts.setOnLoadCallback(interinstituctionals_quantity);
function interinstituctionals_quantity(){/*Quantity de proyectos interinstitucionales del total de los proyectos vigentes*/
var data = new google.visualization.DataTable();
var interinstituctionals_quantity = {{interinstituctionals_quantity|json_encode|raw}};
var projectstotal = 0;
/****This is the array I get from the database:
['¿Interinstitutional?', 'Quantity'],
['yes', 70],
['no', 166],
****/
data.addColumn('string', '¿Interinstitucional?');
data.addColumn('number', 'Quantity');
$.each(interinstituctionals_quantity, function(index, value){
projectstotal += value.Quantity;/*Adding total of the quantity gotten from query*/
/*HOW can I determine inside this loop which of the two values has the highest value? And what if they're the same?*/
data.addRow([value.Interinstitucional,value.Quantity]);
});
var optionMax=1;
var optionMin=0;
var options = {
title: 'Number of interinstitutional projects (total: '+projectstotal+')',
backgroundColor: { fill:'transparent'},
height: 500,
is3D: true,
slices: {
0: { color: 'blue',offset: 0.5 },/*THIS TURNED OUT TO BE MAX AND SHOULD HAVE THESE OPTIONS*/
1: { color: 'green' }/*THIS TURNED OUT TO BE MIN AND SHOULD HAVE THESE OPTIONS*/
}
//width: 900,
};
var chart = new google.visualization.PieChart(document.getElementById('interinstituctionals_quantity_div'));
chart.draw(data, options);
function resizeHandler () {
chart.draw(data, options);
}
if (window.addEventListener) {
window.addEventListener('resize', resizeHandler, false);
}
else if (window.attachEvent) {
window.attachEvent('onresize', resizeHandler);
}
}
</script>
HOW can I determine inside this loop which of the two values has the highest value? And what if they're the same?
How do I achieve that?

something like this should work...
// assumes values will always exist and be positive
var maxAmount = -1;
var maxIndex = -1;
var areEqual = false;
$.each(interinstituctionals_quantity, function(index, value){
projectstotal += value.Quantity;/*Adding total of the quantity gotten from query*/
/*HOW can I determine inside this loop which of the two values has the highest value? And what if they're the same?*/
if (value.Quantity > maxAmount) {
maxAmount = value.Quantity;
maxIndex = index;
} else if (value.Quantity === maxAmount) {
areEqual = true;
}
data.addRow([value.Interinstitucional,value.Quantity]);
});

Related

error code in console after using destroy function from chart.js

let myChart = null;
function draw(){
const labels = [];
for (var i = 0; i < stats.length; i++) {
labels.push(legend[i]);
}
const data = {
labels: labels,
datasets: [{
backgroundColor: ['rgb(204,0,0)', 'rgb(241,194,50)', 'rgb(41,134,204)', 'rgb(106,168,79)', 'rgb(255,62,153)'],
data: stats,
}]
};
const config = {
type: 'doughnut',
data: data,
options: {
radius: 200,
hoverOffset: 30,
aspectRatio: 1,
maintainAspectRatio: false,
responsive: false,
}
};
if (myChart !== null) {
myChart.destroy();
}
myChart = new Chart(document.getElementById('defaultCanvas0'), config);
}
When i run this code my chart just keeps flickering and drawing itself over and over again with a new id each time. I need to be able to destroy my original chart before drawing a new one
This is what console.log displays:
Edit:
function HealthStudy() {
//name for the visualisation to appear in the menu bar
this.name = "Health study";
//each visualisation must have a unique ID with no special characters
this.id = "Health-study";
//property to represent whether stats has been loaded
this.loaded = false;
// Preload the stats. This function is called automatically by the
// gallery when a visualisation is added.
this.preload = function () {
var self = this;
this.stats = loadTable(
'./data/health/causes-of-death.csv', 'csv', 'header',
// Callback function to set the value
// this.loaded to true.
function (table) {
self.loaded = true;
});
};
this.setup = function () {
if (!this.loaded) {
console.log('stats not yet loaded');
return;
}
// Create a select DOM element.
this.select = createSelect();
this.select.position(800, 380);
// Fill the options with all country names.
var countries = this.stats.columns;
// First entry is empty.
for (let i = 1; i < countries.length; i++) {
this.select.option(countries[i]);
}
};
this.destroy = function () {
this.select.remove();
};
// Create a new donut object.
this.donut = new Donut(width / 2, height / 2, width * 0.4);
this.draw = function () {
if (!this.loaded) {
console.log('stats not yet loaded');
return;
}
// Get the value of the country we're interested in from the
// select item.
var country = this.select.value();
// Get the column of raw stats for country.
var col = this.stats.getColumn(country);
// Convert all stats strings to numbers.
col = stringsToNumbers(col);
// Copy the row labels from the table (the first item of each row).
var legend = this.stats.getColumn(0);
// Colour to use for each category.
var colours = ['#CC0000', '#55a5f2', '#4dff00', '#f4e410', '#6a329f'];
// Make a title.
var title = 'Top 5 causes of death in ' + country;
// Draw the Donut!
this.donut.draw(col, legend, colours, title);

Google pie chart animation of the slices colors

I have a Google pie chart that I try to animate using simple JavaScript code.
I wish to change to colors of my pie slices. Why my code is not working?
google.charts.load('current', {'packages':['corechart']});
google.charts.setOnLoadCallback(drawChart);
function drawChart() {
var data1 = google.visualization.arrayToDataTable([
['Task', 'Hours per Day'],
['A1', 0],
['Failed',1],
['A2', 0],
['Passed', 3],
]);
var colors1 = ['#ef7777', '#ef7777', '#b2d284', '#b2d284', '#f6c7b6'];
var colors2 = ['#ff00ff', '#ff00ff', '#02d2ff', '#02d2ff', '#f6c7b6'];
var colors3 = colors2;
var options1 = {'title':'Logic', 'width':'50%', 'height':'50%', legend:{position:'none'}, 'is3D':true,
chartArea: {width: '70%', height: '70%'},
colors: colors3,
'backgroundColor': '#fef7f8',
pieSliceTextStyle: {
color: '#000000',
bold: true,
fontSize:16
}
};
var chart1 = new google.visualization.PieChart(document.getElementById('piechart1'));
chart1.draw(data1, options1);
var percent = 0;
var handler = setInterval(function(){
// values increment
percent += 1;
if (percent%2 == 1) {
colors3 = colors1;
}
else
{
colors3 = colors2;
}
chart1.draw(data1, options1);
if (percent > 74)
clearInterval(handler);
}, 333);
}
So, I am setting here 2 arrays with color sets for my pie chart. The first have colors of red and green, the 2nd one have colors of blue and purple.
I wish to switch between these color sets continuously using the function "setInterval".
colors is a key of your options object. The callback function of your setInterval call changes a variable called colors3 but you don't assign it to the original object so it won't ever be used.
if (percent % 2 == 1) {
colors3 = colors1;
} else {
colors3 = colors2;
}
options1.colors = colors3; // here we're assigning it!
chart1.draw(data1, options1);

Set single point as active / show point and tooltip in Google line chart

Im currently using a Google line chart to show two lines intercepting each other. I would like to show the data point and if possible the tooltip as well, where the lines are intercepting.
My current solution is to show all points and increase the size for the specific point, but actually I want to keep the functionality of seeing the points when pointing on them.
if (!intercept && oldVal > newVal) {
intercept = true
point = 'point { size: 10; }'
}
data.push([i + 1, oldVal, newVal, point])
it looks like you're on the right track with the point size.
we have to set the pointSize config option to something greater than zero,
in order to be able to set the size in our style column.
but we can use something like --> pointSize: 0.1
to prevent the other points from being visible.
as for the tooltip, we can set the tooltip.trigger option to either...
'selection' or 'both'
tooltip: {
trigger: 'both'
}
then we can use the chart's 'ready' event,
to set the chart's selection
google.visualization.events.addListener(chart, 'ready', function () {
chart.setSelection([{row: intercept, column: 2}]);
});
with the above trigger option, when we set the chart's selection,
the tooltip will automatically appear.
see following working snippet...
google.charts.load('current', {
packages: ['corechart']
}).then(function () {
var data = new google.visualization.DataTable();
data.addColumn('number', 'X');
data.addColumn('number', 'Old');
data.addColumn('number', 'New');
data.addColumn({type: 'string', role: 'style'});
var intercept = null;
var rows = new Array(10);
$.each(rows, function (i) {
var oldVal = i;
var newVal = rows.length - i;
var point = null;
if ((intercept === null) && (oldVal === newVal)) {
intercept = i;
point = 'point { size: 10; }';
}
data.addRow([i + 1, oldVal, newVal, point])
});
var chart = new google.visualization.LineChart(document.getElementById('chart_div'));
google.visualization.events.addListener(chart, 'ready', function () {
chart.setSelection([{row: intercept, column: 2}]);
});
chart.draw(data, {
pointSize: 0.1,
tooltip: {
trigger: 'both'
}
});
});
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<script src="https://www.gstatic.com/charts/loader.js"></script>
<div id="chart_div"></div>

Google line chart not working

the following code writes data to the screen and this needs to be plotted in a graph. The graph should be similar to the attachment So, when the array indicator is calculated (line 112), it contains 3 subarrays: one with a date, one with normalised prices and one with the mRS values. The array indicator is also calculated 3 times: one for AAL, one for ABF and one for ADM. So I need 3 graphs displayed, one for each symbol.
So essentially the multilinechart code needs to be integrated into the transpose code whereby 3 line charts are generated, namely after the calculation of the indicator array
<script type="text/javascript" src="https://www.gstatic.com/charts/loader.js"></script>
<script type="text/javascript">
var prices = [['Date', 'AAL', 'ABF', 'ADM'],
['2016-12-01', 1207.5, 2514.55, 1847.00],
['2016-11-01', 1123.5, 2475.00, 1901.00],
['2016-10-01', 1131, 2462.00, 1917.00],
['2016-09-01', 967.6, 2600.00, 2049.00],
['2016-08-01', 779.8, 3041, 2013.36],
['2016-07-01', 830.5, 2691, 2125.32],
['2016-06-01', 726.9, 2719, 1993.72],
['2016-05-02', 600.1, 2933.644, 1933.282],
['2016-04-01', 763.4, 3053.222, 1792.365],
['2016-03-01', 552.1, 3337.219, 1913.98],
['2016-02-01', 480.25, 3394.019, 1671.716],
['2016-01-04', 277.45, 3138.919, 1712.254],
['2015-12-01', 299.45, 3330.244, 1601.257],
['2015-11-02', 408.65, 3508.387, 1564.58],
['2015-10-01', 546.6, 3418.352, 1556.858],
['2015-09-01', 550.9, 3304.572, 1449.722],
['2015-08-03', 741, 3168.036, 1472.785],
['2015-07-01', 789.923, 3189.803, 1407.223],
['2015-06-01', 894.409, 2840.547, 1317.905],
['2015-05-01', 999.089, 2985.838, 1414.824],
['2015-04-01', 1076.017, 2817.219, 1458.897],
['2015-03-02', 985.457, 2778.762, 1432.678],
['2015-02-02', 1119.873, 3081.488, 1381.177],
['2015-01-01', 1030.099, 3059.794, 1355.894],
['2014-12-01', 1111.081, 3109.098, 1237.909],
['2014-11-03', 1223.068, 3134.425, 1161.125],
['2014-10-01', 1218.441, 2695.038, 1250.082],
['2014-09-01', 1280.913, 2621.644, 1201.39],
['2014-08-01', 1416.038, 2801.704, 1227.186],
['2014-07-01', 1461.646, 2718.524, 1339.334],
['2014-06-02', 1307.163, 2983.722, 1423.904],
['2014-05-01', 1332.301, 2943.89, 1340.253],
['2014-04-01', 1446.106, 2898.044, 1285.099],
['2014-03-03', 1395.374, 2712.71, 1290.464],
['2014-02-03', 1369.37, 2924.382, 1296.79],
['2014-01-01', 1284.4, 2648.331, 1305.827],
['2013-12-02', 1180.646, 2384.961, 1183.829],
['2013-11-01', 1206.584, 2212.07, 1123.282],
['2013-10-01', 1328.227, 2186.987, 1155.815],
['2013-09-02', 1357.743, 1809.787, 1114.245],
['2013-08-01', 1322.413, 1779.881, 1119.517],
['2013-07-01', 1242.815, 1875.387, 1245.585],
['2013-06-03', 1117.474, 1673.764, 1178.112],
['2013-05-01', 1347.412, 1738.319, 1187.878],
['2013-04-01', 1381.396, 1856.318, 1118.274],
['2013-03-01', 1493.496, 1823.7, 1162.796],
['2013-02-01', 1664.242, 1776.693, 1092.085],
['2013-01-01', 1633.503, 1677.881, 1067.642],
['2012-12-03', 1639.998, 1500.404, 1012.645]];
// Pairwise multiplication of the elements in two arrays; for use in mUp and mDown calculation
function dotproduct(a, b) {
var n = 0;
for (var i = 0; i < Math.min(a.length, b.length); i++) n += a[i][1] * b[i];
return n;
}
// Define array of weights that is global to the program
var weight = [];
// Weighting function
function weights() {
var k = 1;
var lambda = 2;
for (var x = 0.1; x < 20; x++) {
weight.push([x, k * Math.pow(x/lambda, k-1) * Math.exp(-Math.pow(x/lambda, k)) / lambda]);
}
}
// Create the weights
weights();
document.write(weight + '<hr>');
// Fetch first row of the prices array and keep the remainder as actual prices
var symbols = prices[0];
prices.shift();
// Loop through all columns of prices
for (var c in prices[0]) {
var min = prices[0][c];
var max = prices[0][c];
var up = [];
var down = [];
var indicator = [];
// Loop through all rows of prices and calculate the minimum and maximum, the up-value and down-value
for (var r in prices) {
min = Math.min(prices[r][c], min); // minimum price, for normalisation
max = Math.max(prices[r][c], max); // maximum price, for normalisation
var last = (typeof prices[parseInt(r)+1] != "undefined") ? prices[parseInt(r)+1][c] : 0;
up.push(Math.max(prices[r][c] - last, 0)); // up value
down.push(-Math.min(prices[r][c] - last, 0)); // down value
}
document.write('symbol: ' + symbols[c] + '<br>');
var mUp = []; // weighted up values
var mDown = []; // weighted down values
// Loop through all values of up and down and apply the weighting to the up and down values progressively
for (var i in up) {
mUp.push(dotproduct(weight, up));
up.shift(); // drop the first element off the up array
mDown.push(dotproduct(weight, down));
down.shift(); // drop the first element off the down array
}
// Add date and price to indicator array
for (var r in prices) {
indicator.push([prices[r][0], (prices[r][c]-min)/max, mUp[r]/(mUp[r]+mDown[r])]);
}
// *********
// Add the code to generate the line graph of array indicator here
// *********
document.write('indicator: ' + indicator + '<br>');
// Calculate percentile
document.write('first indicator: ' + indicator[0][2] + '<br>');
// Define a counter
var count = 0;
// Count the number of data points smaller than or equal to n
for (i in indicator) if (indicator[i][2] <= indicator[0][2]) count++;
document.write('count: ' + count + '<br>');
// Return the percentile
document.write('percentile: ' + count/indicator.length + '<br>');
document.write('<hr>');
}
</script>
Assuming that the array prices is the result of those calculations, you use .arrayToDataTable() to interface the data to the Google Visualization API.
SNIPPET
<!DOCTYPE html>
<html>
<head>
<meta charset="utf-8">
<meta name="viewport" content="width=device-width,initial-scale=1, user-scalable=no">
<title>Line Chart</title>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.1.0/jquery.min.js"></script>
<script type="text/javascript" src="https://www.gstatic.com/charts/loader.js"></script>
<script type="text/javascript">
google.charts.load('current', {
'packages': ['corechart']
});
google.charts.setOnLoadCallback(drawChart);
function drawChart() {
var data = google.visualization.arrayToDataTable([
['Date', 'AAL', 'ABF', 'ADM'],
['2016-12-01', 1207.5, 2514.55, 1847.00],
['2016-11-01', 1123.5, 2475.00, 1901.00],
['2016-10-01', 1131, 2462.00, 1917.00],
['2016-09-01', 967.6, 2600.00, 2049.00],
['2016-08-01', 779.8, 3041, 2013.36],
['2016-07-01', 830.5, 2691, 2125.32],
['2016-06-01', 726.9, 2719, 1993.72],
['2016-05-02', 600.1, 2933.644, 1933.282],
['2016-04-01', 763.4, 3053.222, 1792.365],
['2016-03-01', 552.1, 3337.219, 1913.98],
['2016-02-01', 480.25, 3394.019, 1671.716],
['2016-01-04', 277.45, 3138.919, 1712.254],
['2015-12-01', 299.45, 3330.244, 1601.257],
['2015-11-02', 408.65, 3508.387, 1564.58],
['2015-10-01', 546.6, 3418.352, 1556.858],
['2015-09-01', 550.9, 3304.572, 1449.722],
['2015-08-03', 741, 3168.036, 1472.785],
['2015-07-01', 789.923, 3189.803, 1407.223],
['2015-06-01', 894.409, 2840.547, 1317.905],
['2015-05-01', 999.089, 2985.838, 1414.824],
['2015-04-01', 1076.017, 2817.219, 1458.897],
['2015-03-02', 985.457, 2778.762, 1432.678],
['2015-02-02', 1119.873, 3081.488, 1381.177],
['2015-01-01', 1030.099, 3059.794, 1355.894],
['2014-12-01', 1111.081, 3109.098, 1237.909],
['2014-11-03', 1223.068, 3134.425, 1161.125],
['2014-10-01', 1218.441, 2695.038, 1250.082],
['2014-09-01', 1280.913, 2621.644, 1201.39],
['2014-08-01', 1416.038, 2801.704, 1227.186],
['2014-07-01', 1461.646, 2718.524, 1339.334],
['2014-06-02', 1307.163, 2983.722, 1423.904],
['2014-05-01', 1332.301, 2943.89, 1340.253],
['2014-04-01', 1446.106, 2898.044, 1285.099],
['2014-03-03', 1395.374, 2712.71, 1290.464],
['2014-02-03', 1369.37, 2924.382, 1296.79],
['2014-01-01', 1284.4, 2648.331, 1305.827],
['2013-12-02', 1180.646, 2384.961, 1183.829],
['2013-11-01', 1206.584, 2212.07, 1123.282],
['2013-10-01', 1328.227, 2186.987, 1155.815],
['2013-09-02', 1357.743, 1809.787, 1114.245],
['2013-08-01', 1322.413, 1779.881, 1119.517],
['2013-07-01', 1242.815, 1875.387, 1245.585],
['2013-06-03', 1117.474, 1673.764, 1178.112],
['2013-05-01', 1347.412, 1738.319, 1187.878],
['2013-04-01', 1381.396, 1856.318, 1118.274],
['2013-03-01', 1493.496, 1823.7, 1162.796],
['2013-02-01', 1664.242, 1776.693, 1092.085],
['2013-01-01', 1633.503, 1677.881, 1067.642],
['2012-12-03', 1639.998, 1500.404, 1012.645]
]);
var options = {
title: 'Line Chart',
curveType: 'function',
legend: {
position: 'bottom'
}
};
var chart = new google.visualization.LineChart(document.getElementById('curve_chart'));
chart.draw(data, options);
}
</script>
</head>
<body>
<div id="curve_chart" style="width: 900px; height: 500px"></div>
</body>
</html>

How to clear chart before adding new data?

I am using the Google Visualization API. A chart is generated based on values from an ajax call function drawchart().
The user then inputs values in textboxes and this point is added on the chart also (function addUserPoint()). function addUserPoint2() is autogenerated and is also added onto the map. The result of adduserpoint and adduserpoint2 have a line between them.
My issue: If the user adds a new point again, the chart adds those values and the previously added points stay on the chart. I want to get rid of the results of adduserpoint and adduserpoint2 before adding a new point. How can I achieve this?
var chartData;
var options2;
function addUserPoint() {
if (chartData.getNumberOfColumns() === 2) {
chartData.addColumn('number', '');
}
var aa= $("#wbtotala").text();
var bb= $("#wbtotalb").text();
chartData.addRow([
parseFloat(bb),
null,
parseFloat(aa)
]);
myLineChart.draw(chartData, options2);
}
function addUserPoint2(){
if (chartData.getNumberOfColumns() === 2) {
chartData.addColumn('number', '');
}
myLineChart.draw(0,0, options2);
var aa2 = fweight;
var bb2= fcg;
chartData.addRow([
parseFloat(bb2),
null,
parseFloat(aa2)
]);
myLineChart.draw(chartData, options2);
}
function drawchart() {
document.getElementById('addPoint').addEventListener('click', addUserPoint, false);
document.getElementById('addPoint').addEventListener('click', addUserPoint2, false);
chartData = new google.visualization.DataTable();
chartData.addColumn('number', 'Sli');
chartData.addColumn('number', 'Weight');
for (var i = 0; i < chartdatax.length; i++) {
chartData.addRow([parseFloat(chartdatax[i]), parseFloat(chartdatay[i])]);
};
options2 = {
height: 500,
hAxis: {
title: 'AB',
gridlines: {
count: 20
}
},
vAxis: {
title: 'CD',
gridlines: {
count: 15
}
},
chartArea: {top:40, width: "70%", height: "75%"},
legend: { position: 'none' },
pointSize: 5
};
myLineChart = new google.visualization.LineChart(document.getElementById('myChart2'));
myLineChart.draw(chartData, options2);
}
Use the Below Command.Here data is the DataTable Variable.
var data = new google.visualization.DataTable();
Set chartData to an empty object in addUserPoint();
function addUserPoint() {
charData = {};
if (chartData.getNumberOfColumns() === 2) {
...
}
}
This makes sure that anytime you add a new Data, it clears the previous data and you have a fresh new dataset ;)

Categories

Resources