Pushing into an array - javascript

var data = google.visualization.arrayToDataTable([
['Year', 'Oil', 'Cost', 'Barrel'],
['2004', 1000, 400, 710],
['2005', 1170, 460, 850],
['2006', 660, 1120, 620]
]);
I have the above example, but say I want to add ['2007', 1030, 540, 740] to the end of that outside of the above?
I tried the following but it comes up with push is not a function
setTimeout(function(){
data.push(['2007', 1030, 540, 740]);
chart.draw(data, options);
}, 1000);

Hi Take a look at this: https://developers.google.com/chart/interactive/docs/reference#DataTable_constructors (see section Details)
data is datatable, so it has a method for adding a row onto it. You don't push into it.
What you probably want is this:
data.addRows([
['2007', 1030, 540, 740]
]);

It is the DataTable and looking into the documentation, it seems it has a separate method can addRows() to add data to it.
data.addRows(['2007', 1030, 540, 740]);

Related

Google Charts, AJAX, PHP Problem Encoding JSON Error: Data for arrayToDataTable is not an array

I am trying to do some basic Google Charts filled by databse via PHP/PDO/MSSQL passed via AJAX to the .js
I'm having a very basic problem that i feel is encoding.
I am following the tutorial https://developers-dot-devsite-v2-prod.appspot.com/chart/interactive/docs/gallery/linechart
They hardcode the data into the google chart but i send mine over via Ajax. My data from the Ajax looks like this:
$data = "['Year', 'Sales', 'Expenses'],['2004', 1000, 400],['2005', 1170, 460], ['2006', 660, 1120],['2007', 1030, 540]";
echo (json_encode($data));
resulting in:
"['Year', 'Sales', 'Expenses'],['2004', 1000, 400],['2005', 1170, 460], ['2006', 660, 1120],['2007', 1030, 540]"
However when I run the chart i get the error "Error: Data for arrayToDataTable is not an array."
I'm sending the exact same data verbatim but via AJAX so what am I missing?
Instead of the google sample:
function drawChart() {
var data = google.visualization.arrayToDataTable([
['Year', 'Sales', 'Expenses'],
['2004', 1000, 400],
['2005', 1170, 460],
['2006', 660, 1120],
['2007', 1030, 540]
]);
var options = {
title: 'Company Performance',
curveType: 'function',
legend: { position: 'bottom' }
};
var chart = new google.visualization.LineChart(document.getElementById('curve_chart'));
I'm using:
function drawChart() {
var jsonData = $.ajax({
url: "reports/GoogleCharts/ajax_StationExpenses.php",
dataType: "json"
}).responseText;
var data = new google.visualization.arrayToDataTable(jsonData);
var options = {
title: 'Station Utility Expense Over $250 by Month',
curveType: 'function',
legend: { position: 'bottom' },
width: 800,
height: 600,
animation:{ startup: true, duration: 1700, easing: 'in' }
};
var chart = new google.visualization.LineChart(document.getElementById('chart_div'));
chart.draw(data, options);
}
What am I missing, why does it take it hardcoded but not in what appears to be the exact same format pushed by AJAX from my php page?
Your $data value is a string, not an array.
$data = "anything here"; //a string
$data = "[['also','a','string'],...]"; //also a string
JSON encoding a string will not produce valid JSON.
$data = array(
array("Year","Sales","Expenses"),
array("2004",1000,400),
array("2005",1170,460),
array("2006",660,1120),
array("2007",1030,540)
);
The above is a valid PHP array.
$data = [
["Year","Sales","Expenses"],
["2004",1000,400],
["2005",1170,460],
["2006",660,1120],
["2007",1030,540]
];
.. of course you can also use the PHP shorthand for writing arrays.
$json = json_encode($data);
The above is a valid JSON encoded array.
Add the JSON header:
header('Content-type: application/json');
exit( $json );

How to create downloadable link of google chart in image file

In the code, I am trying to add a hyperlink below the chart. As I click it, it will take me to a new tab with a google chart image for download.Any helps?
https://codepad.remoteinterview.io/KOURCFTBEG
As I viewed a lot of examples, most of them put
google.visualization.events.addListener(chart, 'ready',function() {
console.log(chart.getChart().getImageURI());
document.getElementById('png').innerHTML = '<a href="' +
chart.getChart().getImageURI() + '">Printable version</a>';
});
It seems to me that this would create a downloadable link to an image of the google chart on the <div id=png>But in my case, no link or clickable button is created.
google.charts.load('current', {'packages':['bar']});
google.charts.setOnLoadCallback(drawBar);
function drawBar() {
var data = google.visualization.arrayToDataTable([
['Year', 'Sales', 'Expenses', 'Profit'],
['2013', 1001, 401, 201],
['2014', 1000, 400, 200],
['2015', 1170, 460, 250],
['2016', 660, 1120, 300],
['2017', 1030, 540, 350]
]);
var options = {
chart: {
title: 'Company Performance',
subtitle: 'Sales, Expenses, and Profit: 2014-2017',
}
};
//---------------------------//
var chart = new google.charts.Bar(document.getElementById('chart_div'));
// Wait for the chart to finish drawing before calling the getImageURI() method.
google.visualization.events.addListener(chart, 'ready', function() {
console.log(chart.getChart().getImageURI());
document.getElementById('png').innerHTML = 'Printable version';
});
chart.draw(data, options);
}
<body>
<script type="text/javascript" src="https://www.gstatic.com/charts/loader.js"></script>
<script type="text/javascript" src="https://www.google.com/jsapi?autoload={'modules':[{'name':'visualization','version':'1.0','packages':['corechart']},{'name':'visualization','version':'1.0','packages':['controls']}]}"></script>
<div id="chart_div" style="width: 900px; height: 500px;"></div>
<div id='png'></div>
</body>
I followed the online source as similar as I can, but still get error like chart.getURI() is not function.
Here is the online source I referred most. Here is Fiddle.
Try this
<a href="link_to_image_download" target=_blank>Download here</a>
if you don't have a link to download, go to imgur.com and upload the image and add the share link into your href=
You can use print() as suggested by Google Developer API.
Here is the thing I assume you're looking for:
https://developers.google.com/chart/interactive/docs/printing
By removing getChart() in chart.getChart().getImageURI()and
,in package, by modifying bar to corechart can do the work.
google.charts.load('current', {'packages':['corechart']});
google.charts.setOnLoadCallback(drawBar);
function drawBar() {
var data = google.visualization.arrayToDataTable([
['Year', 'Sales', 'Expenses', 'Profit'],
['2013', 1001, 401, 201],
['2014', 1000, 400, 200],
['2015', 1170, 460, 250],
['2016', 660, 1120, 300],
['2017', 1030, 540, 350]
]);
var options = {
chart: {
title: 'Company Performance',
subtitle: 'Sales, Expenses, and Profit: 2014-2017',
}
};
//---------------------------//
var chart = new google.visualization.ColumnChart(document.getElementById('chart_div'));
// Wait for the chart to finish drawing before calling the getImageURI() method.
google.visualization.events.addListener(chart, 'ready', function() {
// console.log(chart.getImageURI());
document.getElementById('png').innerHTML = 'Printable version';
});
chart.draw(data, options);
}
<body>
<script type="text/javascript" src="https://www.gstatic.com/charts/loader.js"></script>
<script type="text/javascript" src="https://www.google.com/jsapi?autoload={'modules':[{'name':'visualization','version':'1.0','packages':['corechart']},{'name':'visualization','version':'1.0','packages':['controls']}]}"></script>
<div id="chart_div" style="width: 900px; height: 500px;"></div>
<div id='png'></div>
</body>

django variable to javascript

I'm trying to use google charts to visualize some data. As described in docs, i put this code to my template:
<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 tmp = document.getElementById('result').value;
var data = google.visualization.arrayToDataTable([
['Year', 'Sales', 'Expenses'],
['2004', 1000, 400],
['2005', 1170, 460],
['2006', 660, 1120],
['2007', 1030, 540]]
);
var options = {
title: 'Company Performance',
curveType: 'function',
legend: { position: 'bottom' }
};
var chart = new google.visualization.LineChart(document.getElementById('curve_chart'));
chart.draw(data, options);
}
</script>
<div id="curve_chart" style="width: 900px; height: 500px"></div>
And it works fine. But i need to pass some custom data, so i did:
views.py:
def home(request):
example = [
['Year', 'Sales', 'Expenses'],
['2004', 1000, 400],
['2005', 1170, 460],
['2006', 660, 1120],
['2007', 1030, 540]
]
return render(request, 'home.html', {'example': example})
As example data i used the same array. Next i replaced array in javascript code to {{ example }}:
var data = google.visualization.arrayToDataTable( {{example}} );
And nothing happens. Google chart isn't drawing on my webpage anymore.
What im doing wrong? Also i tried to use json.dumps in python code and it didn't worked for me.
You should simply turn your list of lists into valid json before you pass it to the template:
import json
def home(request):
example = [
['Year', 'Sales', 'Expenses'],
['2004', 1000, 400],
['2005', 1170, 460],
['2006', 660, 1120],
['2007', 1030, 540]
]
example = json.dumps(example)
return render(request, 'home.html', {'example': example})
Make sure you're using the safe template tag:
var data = google.visualization.arrayToDataTable( {{example|safe}} );
What is the error you're getting when you try that?

changing colors of google bar chart and convert data into percentage

While using google bar chart how to change color of individual bar , and how to convert the data values into percentage.
You can preview it on http://jsfiddle.net/u4Lwwx1k/
<script type="text/javascript" src="https://www.google.com/jsapi?autoload={'modules':[{'name':'visualization','version':'1','packages':['corechart']}]}"></script>
<div id="chart_div" style="width: 500px; height: 200px;"></div>
google.setOnLoadCallback(drawChart);
function drawChart() {
var data = google.visualization.arrayToDataTable([
['Year', 'Sales'],
['2004', 1000],
['2005', 1170],
['2006', 660],
['2007', 1030, ]
]);
var options = {
title: 'Company Performance',
};
var chart = new google.visualization.BarChart(document.getElementById('chart_div'));
chart.draw(data, options);
}
To get the colours you need to change your first line of the array:
Change ['Year', 'Sales'],
To: ['Year', 'Sales', { role: 'style' }],
then each value add the colour to the end like:
['2004', 1000, 'blue'],
['2005', 1170, '#cccccc'],
I think you will have to program the percentage yourself. Im looking to do the same and cant find any examples.

Draw a based line in Google line chart

I working with Google line chart I want to draw a based line but I don't know how should I do that for example I want to draw line in 2004 between 400 and 600 how should I do that
here Google Sample:
<html>
<head>
<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 = google.visualization.arrayToDataTable([
['Year', 'Sales', 'Expenses'],
['2004', 1000, 400],
['2005', 1170, 460],
['2006', 660, 1120],
['2007', 1030, 540]
]);
var options = {
title: 'Company Performance'
};
var chart = new google.visualization.LineChart(document.getElementById('chart_div'));
chart.draw(data, options);
}
</script>
</head>
<body>
<div id="chart_div" style="width: 900px; height: 500px;"></div>
</body>
</html>
You can do this in a few different ways, depending on exactly what you want to achieve. The easiest way is to use "interval" role columns:
function drawChart() {
var data = google.visualization.arrayToDataTable([
['Year', 'Sales', 'Expenses', {role: 'interval', type: 'number'}, {role: 'interval', type: 'number'}],
['2004', 1000, 400, 400, 600],
['2005', 1170, 460, null, null],
['2006', 660, 1120, null, null],
['2007', 1030, 540, null, null]
]);
var options = {
title: 'Company Performance'
};
var chart = new google.visualization.LineChart(document.getElementById('chart_div'));
chart.draw(data, options);
}
There is quite a bit of customization you can do with intervals, see the documentation.
Another way is to add a new series of data for this line, change the data type of the first column from "string" to "number", and add multiple rows of data with the same x-values, eg:
function drawChart() {
var data = google.visualization.arrayToDataTable([
['Year', 'Sales', 'Expenses', 'vertical lines'],
[2004, 1000, 400, 400],
[2004, null, null, 600],
[2005, 1170, 460, null],
[2006, 660, 1120, null],
[2007, 1030, 540, null]
]);
var options = {
title: 'Company Performance',
interpolateNulls: true, // this prevents your other lines from breaking
series: {
2: {
// these options control your new series for the vertical lines
visibleInLegend: false, // hide from the legend
enableInteractivity: false // make the line non-interactive
color: '#9055a6' // set the color of the line
// etc...
}
}
};
var chart = new google.visualization.LineChart(document.getElementById('chart_div'));
chart.draw(data, options);
}

Categories