Google Charts: Data in the axis - javascript

This code creates a scatterplot with an image of a pie chart on it.
I'm having a problem making the data row entry to be shown in the axis of the Scatterplot.
Any idea in how to make that happen?
Many thanks :)
google.charts.load('current', {'packages':['corechart']});
function draw0hedgeChart() { var data = new google.visualization.DataTable(); data.addColumn('number', 'X'); data.addColumn('number', 'Y');
data.addRows([ [ 9.87, 6.53], ]);
var options = {
colors: ['#000000'],
legend: 'none',
title: 'Risk vs. Return with 0% Hedge Fund',
hAxis: {title: 'Risk', minValue: 3, maxValue: 11, gridlineColor: '#fff', direction: -1},
vAxis: {title: 'Return', minValue: 4, maxValue: 10, gridlineColor: '#fff'},
width:900,
height:500
};
var container = document.getElementById('chart0_div');
var chart = new google.visualization.ScatterChart(container);
google.visualization.events.addListener(chart, 'ready', function () {
var layout = chart.getChartLayoutInterface();
for (var i = 0; i < data.getNumberOfRows(); i++) {
var xPos = layout.getXLocation(data.getValue(i, 0));
var yPos = layout.getYLocation(data.getValue(i, 1));
var widget0 = container.appendChild(document.createElement('img'));
widget0.src = 'img/0.png';
widget0.className = 'chart0';
// (overlay the dot)
widget0.style.top = (yPos - 50) + 'px';
widget0.style.left = (xPos - 50) + 'px';
} });
chart.draw(data, options); }

i think you may be referring to the configuration options for...
{hAxis,vAxis,hAxes.*,vAxes.*}.ticks
hAxis.ticks - Replaces the automatically generated X-axis ticks with the specified array. Each element of the array should be either a valid tick value (such as a number, date, datetime, or timeofday)
e.g.
google.charts.load('current', {
callback: draw0hedgeChart,
packages: ['corechart']
});
function draw0hedgeChart() {
var data = new google.visualization.DataTable();
data.addColumn('number', 'X');
data.addColumn('number', 'Y');
data.addRows([
[9.87, 6.53],
]);
var ticksX = [];
var ticksY = [];
for (var i = 0; i < data.getNumberOfRows(); i++) {
ticksX.push(data.getValue(i, 0));
ticksY.push(data.getValue(i, 1));
}
var options = {
colors: ['#000000'],
legend: 'none',
title: 'Risk vs. Return with 0% Hedge Fund',
hAxis: {
title: 'Risk',
minValue: 3,
maxValue: 11,
//gridlineColor: '#fff',
direction: -1,
ticks: ticksX
},
vAxis: {
title: 'Return',
minValue: 4,
maxValue: 10,
//gridlineColor: '#fff',
ticks: ticksY
},
width:900,
height:500
};
var container = document.getElementById('chart0_div');
var chart = new google.visualization.ScatterChart(container);
google.visualization.events.addListener(chart, 'ready', function () {
var layout = chart.getChartLayoutInterface();
for (var i = 0; i < data.getNumberOfRows(); i++) {
var xPos = layout.getXLocation(data.getValue(i, 0));
var yPos = layout.getYLocation(data.getValue(i, 1));
var widget0 = container.appendChild(document.createElement('img'));
widget0.src = 'http://findicons.com/files/icons/512/star_wars/16/clone_old.png';
widget0.className = 'chart0';
// (overlay the dot)
widget0.style.position = 'absolute';
widget0.style.top = yPos + 'px';
widget0.style.left = xPos + 'px';
}
});
chart.draw(data, options);
}
<script src="https://www.gstatic.com/charts/loader.js"></script>
<div id="chart0_div"></div>

Related

Chart.js not showing all labels on pie chart

I recently updated Chart.js and got the following bug afterwards.
Some of the labels under my pie chart are not showing anymore, until I click on one of the visible ones. Then everything shows as it should.
Here you can see how it looks before clicking on something:
before clicking
and here you can see the chart after clicking on a visible label: after clicking
Here you can see the options section of my chart code:
options: {
maintainAspectRatio : false,
animation: {
duration: 0
},
elements: {
center: center
},
legend: {
position: 'bottom',
//fullWidth: 'true',
labels: {
generateLabels: (chart) => {
chart.legend.afterFit = function () {
var width = this.width;
this.lineWidths = this.lineWidths.map( () => this.width - 12 );
this.options.labels.padding = 30;
this.options.labels.boxWidth = 15;
};
var data = chart.data;
if (data.labels.length && data.datasets.length) {
return data.labels.map((label, i) => {
var meta = chart.getDatasetMeta(0);
var ds = data.datasets[0];
var arc = meta.data[i];
var custom = arc && arc.custom || {};
var getValueAtIndexOrDefault = this.getValueAtIndexOrDefault;
var arcOpts = chart.options.elements.arc;
var fill = custom.backgroundColor ? custom.backgroundColor : getValueAtIndexOrDefault(ds.backgroundColor, i, arcOpts.backgroundColor);
var stroke = custom.borderColor ? custom.borderColor : getValueAtIndexOrDefault(ds.borderColor, i, arcOpts.borderColor);
var bw = custom.borderWidth ? custom.borderWidth : getValueAtIndexOrDefault(ds.borderWidth, i, arcOpts.borderWidth);
return {
text: label,
fillStyle: fill,
strokeStyle: stroke,
lineWidth: bw,
hidden: isNaN(ds.data[i]) || meta.data[i].hidden,
// Extra data used for toggling the correct item
index: i
};
});
}
return [];
}
},
},
cutoutPercentage: 85,
plugins: {
datalabels: {
anchor: 'end',
align: 'end',
display: function(context) {
var index = context.dataIndex;
var value = context.dataset.data[index];
return value > 0; // display labels with a value greater than 0
},
font: {
weight: 'bold',
size: 16,
},
}
}
}
chart.legend.afterFit = function () {
if (keys.length > 4) {
this.options.labels.padding = 15;
this.height = this.height + 25;
}
else {
this.options.labels.padding = 20;
this.height = this.height + 18;
}
var width = this.width; // guess you can play with this value to achieve needed layout
this.lineWidths = this.lineWidths.map(function () { return width; });
};
I changed the part at afterFit to this, so it is formatting right, the problem is, the padding settings are set back when i click on a label.

Google chart keeps drawing

So I have this chart:
google.charts.load('44', {
callback: drawAxisTickColors,
packages: ['controls', 'corechart']
});
function drawAxisTickColors() {
var data = new google.visualization.DataTable();
data.addColumn('datetime', 'Date');
data.addColumn('number', 'value');
var dateArr2 = (<?php echo json_encode($dateArr); ?>);
console.log(dateArr2);
var bitcoinArr = (<?php echo json_encode($numbers); ?>);
console.log(bitcoinArr);
bitcoinArr = bitcoinArr.map(Number);
var array = [];
var length = Math.min(dateArr2.length, bitcoinArr.length);
for (var i = 0; i < length; ++i) {
array.push([ new Date(dateArr2[i]), bitcoinArr[i] ]);
}
data.addRows(array);
var control = new google.visualization.ControlWrapper({
controlType: 'ChartRangeFilter',
containerId: 'control_div',
options: {
filterColumnIndex: 0,
ui: {
chartOptions: {
height: 50,
width: 600,
chartArea: {
width: '80%'
}
}
}
}
});
var chart = new google.visualization.ChartWrapper({
chartType: 'LineChart',
containerId: 'chart_div',
options: {
width: 620,
chartArea: {
width: '80%'
},
hAxis: {
format: 'hh:ss',
slantedText: false,
maxAlternation: 1
}
}
});
function setOptions() {
var firstDate;
var lastDate;
var v = control.getState();
if (v.range) {
document.getElementById('dbgchart').innerHTML = v.range.start + ' to ' + v.range.end;
firstDate = new Date(v.range.start.getTime() + 1);
lastDate = new Date(v.range.end.getTime() - 1);
data.setValue(v.range.start.getMonth(), 0, firstDate);
data.setValue(v.range.end.getMonth(), 0, lastDate);
} else {
firstDate = data.getValue(0, 0);
lastDate = data.getValue(data.getNumberOfRows() - 1, 0);
}
var ticks = [];
for (var i = firstDate.getMonth(); i <= lastDate.getMonth(); i++) {
ticks.push(data.getValue(i, 0));
}
chart.setOption('hAxis.ticks', ticks);
chart.setOption('hAxis.viewWindow.min', firstDate);
chart.setOption('hAxis.viewWindow.max', lastDate);
if (dash) {
chart.draw();
}
}
setOptions();
google.visualization.events.addListener(control, 'statechange', setOptions);
var dash = new google.visualization.Dashboard(document.getElementById('dashboard'));
dash.bind([control], [chart]);
dash.draw(data);
}
I use this chart to show import per user, but every time I draw the chart this happens:
As you can see the chart keeps it's old data, this slows down my website. I tried clearChart() but my chart ingores it's or give's an error:
clearchart is not a function
I also tried this:
Google Chart Constant Redrawing Memory Increase
but this doesn't seem to work for me.
What am I doing wrong?
Please help.
I solved it
don't call the google api a 100 times

How to add a total to a chart in google charts

I would like to add a total of the amounts to the chart below.
https://jsfiddle.net/porterhouse47/6e0ejxLb/
I created a function to sum the values and you can see that it's correct if you uncomment the alert. I tried adding a new row for the total as you can see at the bottom but it doesn't show.
// Load Charts and the corechart/bar char package.
google.charts.load('current', {
packages: ['corechart']
});
// Draw the pie chart for the Total Costs when Charts is loaded.
google.charts.setOnLoadCallback(drawPieChart);
// Draw the pie
function drawPieChart() {
var data = google.visualization.arrayToDataTable([
['Country', 'Dollars'],
['Canada', 12250000],
['USA', 22750000]
]);
function getSum(data, column) {
var total = 0;
for (i = 0; i < data.getNumberOfRows(); i++)
total = total + data.getValue(i, column);
return total;
}
//alert(getSum(data, 1));
// In order to show currency correctly
var formatter = new google.visualization.NumberFormat({
negativeColor: 'red',
negativeParens: true,
pattern: '$###,###'
});
formatter.format(data, 1);
var options = {
title: "North America 2017",
legend: {
position: 'top'
},
pieSliceText: 'value-and-percentage',
slices: {
0: {
color: '#328213'
},
1: {
offset: 0.1,
color: '#57a33a'
},
},
pieStartAngle: 70,
width: 400,
height: 300
};
var chart = new google.visualization.PieChart(document.getElementById('total_costs_pie'));
chart.draw(data, options);
addRow('Total', getSum(data, 1));
}
<script type="text/javascript" src="https://www.gstatic.com/charts/loader.js"></script>
<script type="text/javascript">
</script>
<body>
<!--Table and divs that hold the pie charts-->
<table class="columns">
<tr>
<td>
<div id="total_costs_pie" style="border: 1px solid #ccc"></div>
</td>
</tr>
</table>
Hi i have maby solution for you:
HTML:
</script>
<body>
<!--Table and divs that hold the pie charts-->
<table class="columns">
<tr>
<td>
<div id="total_costs_pie" style="border: 1px solid #ccc"></div>
</td>
</tr>
<tr>
<td id="total"></td>
<td id="number"></td>
</tr>
</table>
JAVASCRIPT:
// Load Charts and the corechart/bar char package.
google.charts.load('current', {
packages: ['corechart']
});
// Draw the pie chart for the Total Costs when Charts is loaded.
google.charts.setOnLoadCallback(drawPieChart);
// Draw the pie
function drawPieChart() {
var data = google.visualization.arrayToDataTable([
['Country', 'Dollars'],
['Canada', 12250000],
['USA', 22750000]
]);
function getSum(data, column) {
var total = 0;
for (i = 0; i < data.getNumberOfRows(); i++)
total = total + data.getValue(i, column);
return total;
}
//alert(getSum(data, 1));
// In order to show currency correctly
var formatter = new google.visualization.NumberFormat({
negativeColor: 'red',
negativeParens: true,
pattern: '$###,###'
});
formatter.format(data, 1);
var options = {
title: "North America 2017",
legend: {
position: 'top'
},
pieSliceText: 'value-and-percentage',
slices: {
0: {
color: '#328213'
},
1: {
offset: 0.1,
color: '#57a33a'
},
},
pieStartAngle: 70,
width: 400,
height: 300
};
var chart = new google.visualization.PieChart(document.getElementById('total_costs_pie'));
chart.draw(data, options);
//function for addRow.....
function addRow (name, number) {
//add name and number to .total
total_name = document.createTextNode(name + number);
total.appendChild(total_name);
}
addRow('Total: ', getSum(data, 1));
}
i added function for your addRow. And new tr and td to embed this atributes. I hope thats help you or give you path to do something like this ;)

Google Charts - query all rows, but only draw with 2 of them. How?

I'm trying to use data from a google spreadsheet to draw a pie chart (which is working). And when the user is clicking on a slice, it should show the values in different divs. This doesn't work because I'm only querying row A and D as you can see, because these are the ones that are used to create the Pie Chart. Now what I want to achieve is:
Only use 1 query and draw the pie with row A and D and use the same datatable to fill the variables. Can you help me? :)
google.charts.load('current', {'packages':['corechart']});
google.charts.setOnLoadCallback(drawGID);
function drawGID() {
var populationPieQuery = encodeURIComponent('SELECT A, D LIMIT 10');
/*var serverQuery = encodeURIComponent('SELECT A, C, E, G, H, I, J, K, L, M, N, O LIMIT 20');*/
var queryPopulation = new google.visualization.Query(
'https://docs.google.com/spreadsheets/d/11zIoeZsSi8jPD993uzYYNyY1PaVd4rxIkP4IJ0mUH7U/gviz/tq?sheet=Sheet1&headers=1&tq=' + populationPieQuery);
/*var queryServer = new google.visualization.Query(
'https://docs.google.com/spreadsheets/d/11zIoeZsSi8jPD993uzYYNyY1PaVd4rxIkP4IJ0mUH7U/gviz/tq?sheet=Sheet1&headers=1&tq=' + serverQuery);*/
queryPopulation.send(populationPieQueryResponse);
/*queryServer.send(serverQueryResponse);*/
}
function populationPieQueryResponse(populationResponse) {
if (populationResponse.isError()) {
alert('Error in query: ' + populationResponse.getMessage() + ' ' + populationResponse.getDetailedMessage());
return;
}
// Listen for the 'select' event, and call my function selectHandler() when
// the user selects something on the chart.
var options = {
width: 700, height: 500,
legend: { position: 'right', alignment: 'center' },
chartArea: {width: '70%', height: '70%'},
backgroundColor: 'transparent',
pieStartAngle: 180,
};
var populationData = populationResponse.getDataTable().getValue();
/*var serverData = serverResponse.getDataTable();*/
var chart = new google.visualization.PieChart(document.getElementById('population_chart'));
google.visualization.events.addListener(chart, 'select', selectHandler);
chart.draw(populationData, options);
// The select handler. Call the chart's getSelection() method
function selectHandler() {
var selectedItem = chart.getSelection()[0];
if (selectedItem) {
console.log(serverData.getNumberOfColumns());
var server = serverData.getValue(selectedItem.row, 0);
var ranking = serverData.getValue(selectedItem.row, 1);
var population = serverData.getValue(selectedItem.row, 2);
var scripting = serverData.getValue(selectedItem.row, 3);
var latency_eu = serverData.getValue(selectedItem.row, 4);
var latency_us = serverData.getValue(selectedItem.row, 5);
var staff = serverData.getValue(selectedItem.row, 6);
var community = serverData.getValue(selectedItem.row, 7);
var type = serverData.getValue(selectedItem.row, 8);
var rates = serverData.getValue(selectedItem.row, 9);
var style = serverData.getValue(selectedItem.row, 10);
var language = serverData.getValue(selectedItem.row, 11);
document.getElementById("server").innerHTML=server;
document.getElementById("ranking").innerHTML=ranking;
document.getElementById("population").innerHTML=population;
document.getElementById("scripting").innerHTML=scripting;
document.getElementById("latency_eu").innerHTML=latency_eu;
document.getElementById("latency_us").innerHTML=latency_us;
document.getElementById("staff").innerHTML=staff;
document.getElementById("community").innerHTML=community;
document.getElementById("type").innerHTML=type;
document.getElementById("rates").innerHTML=rates;
document.getElementById("style").innerHTML=style;
document.getElementById("language").innerHTML=language;
}
}
}
Update
google.charts.load('current', {'packages':['corechart']});
google.charts.setOnLoadCallback(drawGID);
function drawGID() {
var queryString = encodeURIComponent('SELECT A, D, B, E, F, G, H, I, J, K, L, M, N, O');
var query = new google.visualization.Query(
'https://docs.google.com/spreadsheets/d/11zIoeZsSi8jPD993uzYYNyY1PaVd4rxIkP4IJ0mUH7U/gviz/tq?sheet=Sheet1&headers=1&tq=' + queryString);
query.send(handleQueryResponse);
}
function handleQueryResponse(response) {
if (response.isError()) {
alert('Error in query: ' + response.getMessage() + ' ' + response.getDetailedMessage());
return;
}
var options = {
width: 700, height: 500,
legend: { position: 'right', alignment: 'center' },
chartArea: {width: '70%', height: '70%'},
backgroundColor: 'transparent',
pieStartAngle: 180,
};
var data = response.getDataTable().getValue();
var populationView = new google.visualization.DataView(data);
populationView.setColumns([0,1]);
var chart = new google.visualization.PieChart(document.getElementById('population_chart'));
google.visualization.events.addListener(chart, 'select', selectHandler);
// The select handler. Call the chart's getSelection() method
function selectHandler() {
var selectedItem = chart.getSelection()[0];
if (selectedItem) {
var server = data.getValue(selectedItem.row, 0);
var ranking = data.getValue(selectedItem.row, 1);
var population = data.getValue(selectedItem.row, 1);
/*var scripting = data.getValue(selectedItem.row, 4);
var latency_eu = data.getValue(selectedItem.row, 5);
var latency_us = data.getValue(selectedItem.row, 6);
var staff = data.getValue(selectedItem.row, 7);
var community = data.getValue(selectedItem.row, 8);
var type = data.getValue(selectedItem.row, 9);
var rates = data.getValue(selectedItem.row, 10);
var style = data.getValue(selectedItem.row, 11);
var language = data.getValue(selectedItem.row, 12);*/
document.getElementById("server").innerHTML=server;
document.getElementById("ranking").innerHTML=ranking;
document.getElementById("population").innerHTML=population;
/*document.getElementById("scripting").innerHTML=scripting;
document.getElementById("latency_eu").innerHTML=latency_eu;
document.getElementById("latency_us").innerHTML=latency_us;
document.getElementById("staff").innerHTML=staff;
document.getElementById("community").innerHTML=community;
document.getElementById("type").innerHTML=type;
document.getElementById("rates").innerHTML=rates;
document.getElementById("style").innerHTML=style;
document.getElementById("language").innerHTML=language; */
}
}
chart.draw(populationView, options);
}
use a DataView to draw the PieChart
this will allow you to return all the data you need and still only pass two columns to the PieChart
assumes columns A and D are first in 'SELECT A, D, ...'
var populationData = populationResponse.getDataTable();
var populationView = new google.visualization.DataView(populationData);
populationView.setColumns([0,1]);
var chart = new google.visualization.PieChart(document.getElementById('population_chart'));
google.visualization.events.addListener(chart, 'select', selectHandler);
chart.draw(populationView, options);

create linear function with javascript or jquery

I was wondering how can I make linear function in javascript like if you search on google:
y=2x+7
I tried using google charts but it didnt work...
here is the code:
google.charts.load('current', {
packages: ['corechart', 'line']
});
google.charts.setOnLoadCallback(drawCurveTypes);
var x = 0;
var y = 0;
var h = window.prompt('enter a number');
function drawCurveTypes() {
var data = new google.visualization.DataTable();
data.addColumn('number', 'linear');
data.addRows([
]);
for (var i = 0; i <= 5; i++) {
addRows('[x,y]');
x = x + h;
y++;
}
var options = {
hAxis: {
title: 'Time'
},
vAxis: {
title: 'Popularity'
},
series: {
1: {
curveType: 'function'
}
}
};
var chart = new google.visualization.LineChart(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>
Thanks!

Categories