Google chart keeps drawing - javascript

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

Related

AmCharts4 line chart with vertically draggable bullets which don't follow the zoom

Here is a line chart with vertically draggable bullets. Problem: when we zoom the x-axis (with the scrollbar), the bullets don't follow.
am4core.useTheme(am4themes_animated);
// Create chart instance
var chart = am4core.create("chartdiv", am4charts.XYChart);
// Add data
chart.data = [
{
date: new Date(2018, 0, 1),
value: 450
},
{
date: new Date(2018, 0, 2),
value: 269
},
{
date: new Date(2018, 0, 3),
value: 700
},
{
date: new Date(2018, 0, 4),
value: 490
},
{
date: new Date(2018, 0, 5),
value: 500
},
{
date: new Date(2018, 0, 6),
value: 550
},
{
date: new Date(2018, 0, 7),
value: 420
}
];
// Create axes
var dateAxis = chart.xAxes.push(new am4charts.DateAxis());
dateAxis.renderer.grid.template.location = 0;
dateAxis.renderer.minGridDistance = 40;
var valueAxis = chart.yAxes.push(new am4charts.ValueAxis());
// Create series
function createSeries(field, name) {
var series = chart.series.push(new am4charts.LineSeries());
series.dataFields.valueY = field;
series.dataFields.dateX = "date";
series.name = name;
series.tooltipText = "{dateX}: [b]{valueY}[/]";
series.strokeWidth = 2;
var bullet = series.bullets.push(new am4charts.CircleBullet());
bullet.circle.stroke = am4core.color("#fff");
bullet.circle.strokeWidth = 2;
bullet.draggable = true;
// resize cursor when over
bullet.cursorOverStyle = am4core.MouseCursorStyle.verticalResize;
// while dragging
bullet.events.on("drag", (event) => {
handleDrag(event);
});
// on dragging stop
bullet.events.on("dragstop", (event) => {
handleDragStop(event);
});
// when line position changes, adjust minX/maxX of bullets so that we could only dragg vertically
bullet.events.on("positionchanged", (event) => {
let dataItem = event.target.dataItem;
if (dataItem.bullets) {
let itemBullet = dataItem.bullets.getKey(bullet.uid);
let point = dataItem.point;
itemBullet.minX = point.x;
itemBullet.maxX = itemBullet.minX;
itemBullet.minY = 0;
itemBullet.maxY = chart.seriesContainer.pixelHeight;
}
});
}
createSeries("value", "Series #1");
chart.cursor = new am4charts.XYCursor();
chart.scrollbarX = new am4core.Scrollbar();
/* ~~~~\ function handling the drag event /~~~~ */
function handleDrag(event) {
let dataItem = event.target.dataItem;
// convert coordinate to value
let value = valueAxis.yToValue(event.target.pixelY);
// set new value
dataItem.valueY = value;
// make line hover
dataItem.segment.isHover = true;
// hide tooltip not to interrupt
dataItem.segment.hideTooltip(0);
// make bullet hovered (as it might hide if mouse moves away)
event.target.isHover = true;
}
/* ~~~~\ function handling the dragstop event /~~~~ */
function handleDragStop(event) {
handleDrag(event);
let dataItem = event.target.dataItem;
dataItem.component.isHover = false;
event.target.isHover = false;
}
#chartdiv {
width: 100%;
height: 500px;
}
<script src="//www.amcharts.com/lib/4/core.js"></script>
<script src="//www.amcharts.com/lib/4/charts.js"></script>
<script src="//www.amcharts.com/lib/4/themes/animated.js"></script>
<div id="chartdiv"></div>
I think I have a solution:
dateAxis.events.on("startchanged", event => {
event.target.series.each(function(s) {
s.bulletsContainer.children.each(function(b) {
b.dispatch("positionchanged");
});
});
});
dateAxis.events.on("endchanged", event => {
event.target.series.each(function(s) {
s.bulletsContainer.children.each(function(b) {
b.dispatch("positionchanged");
});
});
});
Or, shorter:
dateAxis.events.on("selectionextremeschanged", event => {
event.target.series.each(function(s) {
s.bulletsContainer.children.each(function(b) {
b.dispatch("positionchanged");
});
});
});

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: Data in the axis

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>

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