I'm trying to get google charts displayed on my page, but i can't figure how to pass values from django views to javascript so i can draw charts.
Django code:
array = ([
['Year', 'Sales', 'Expenses'],
['2004', 1000, 400],
['2005', 1170, 460],
['2006', 660, 1120],
['2007', 1030, 540]
]);
args['array']= array
return render_to_response('progress.html',args)
progres.html :
<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 djangoData = '{{array}}';
var data = google.visualization.arrayToDataTable(djangoData);
var options = {
title: 'Company Performance'
};
var chart = new google.visualization.LineChart(document.getElementById('chart_div'));
chart.draw(data, options);
}
</script>
This way, the chart doesn't get displayed. Any suggestions ?
google.visualization.arrayToDataTable() appears to take a 2D (javascript) array. What you are passing it is a string. You'll need to parse it into an array. Try:
var djangoData = JSON.parse('{{ array }}');
var data = google.visualization.arrayToDataTable(djangoData);
In your view:
remove this line args['array']= array
change this line return render_to_response('progress.html',args) to return render_to_response('progress.html',{'array': json.dumps(array)})
In your template:
change this line var djangoData = '{{array}}'; to var djangoData = '{{ array | safe }}';
The rest of your code is fine. I hope this helps.
for me this combination works:
view:
from django.shortcuts import render
import json
(...)
context= {'array': json.dumps(array)}
return render(request,'progress.html',context)
template:
var djangoData = JSON.parse('{{ array | safe }}';);
Related
I have a problem I don't know how to add my Map with datas from my db to the google.visualization.arrayToDataTable in the Thymeleaf template.
I succeeded to show the map in the view with the console log but my problem is how to add it to the google.visualization.arrayToDataTable.
This is my code from #Controller
#GetMapping("/pourcentageAges")
public String ageDesClients(Model model){
Map<String,Integer>listeAgesTranches =
utilisateurMetier.agesClientsClub();
System.out.println("je suis la tailme de la liste
"+listeAgesTranches.size());
model.addAttribute("liste",listeAgesTranches);
model.addAttribute("tailleListe",listeAgesTranches.size());
return "utilisateur/agePourcentage";
}
And this is my code from my view:
So I repeat I need just to assign the " var ageList" to the google.visualization.arrayToDataTable
<script type="text/javascript" th:inline="javascript" >
// Load google charts
google.charts.load('current', {'packages':['corechart']});
google.charts.setOnLoadCallback(drawChart);
/*<![CDATA[*/
var ageList=new Map();
var tailleListe= /*[[${tailleListe}]]*/
ageList= /*[[${liste}]]*/ 'default';
/*]]>*/
// Draw the chart and set the chart values
// for (i=0; i<tailleListe;i++){
// console.log('je suis la'+[Object.keys(message)[i],Object.values(message)[i]])
// }
function drawChart() {
var data = google.visualization.arrayToDataTable([
['Task', 'ages between 16 and 90 group by 10'],
['age betweeen 20-30',5 ]
]);
// Optional; add a title and set the width and height of the chart
var options = {'title':'Ages en pourcent de 16 a 90 ans', 'width':550,
'height':400,is3D: true};
// Display the chart inside the <div> element with id="piechart"
var chart = new
google.visualization.PieChart(document.getElementById('piechart'));
chart.draw(data, options);
}
</script>
Thank you a lot for any advice.
first, create a new array before using arrayToDataTable
then you can use the concat method to combine the column headings with ageList
then pass the new array to arrayToDataTable
try it like this...
<script type="text/javascript" th:inline="javascript" >
// Load google charts
google.charts.load('current', {'packages':['corechart']});
google.charts.setOnLoadCallback(drawChart);
/*<![CDATA[*/
var ageList=new Map();
var tailleListe= /*[[${tailleListe}]]*/
ageList= /*[[${liste}]]*/ 'default';
/*]]>*/
function drawChart() {
var dataArray = [
['Task', 'ages between 16 and 90 group by 10']
];
dataArray = dataArray.concat(ageList);
var data = google.visualization.arrayToDataTable(dataArray);
// Optional; add a title and set the width and height of the chart
var options = {'title':'Ages en pourcent de 16 a 90 ans', 'width':550, 'height':400,is3D: true};
// Display the chart inside the <div> element with id="piechart"
var chart = new google.visualization.PieChart(document.getElementById('piechart'));
chart.draw(data, options);
}
</script>
I am trying to change the number format of the axis on a google gauge. By default, the axis value is a whole number (e.g. 0, 120) but I would like to show a £ sign and format as currency (e.g. £0, £120). I have been able to change the format of the value shown at the bottom of the gauge using NumberFormat but cannot apply to the rest of the gauge.The code for the basic gauge is as follows:
<!doctype html>
<html>
<head>
<meta charset="UTF-8">
<script type="text/javascript" src="https://www.gstatic.com/charts/loader.js"></script>
<script type="text/javascript">
google.charts.load('current', {'packages':['gauge']});
google.charts.setOnLoadCallback(drawChart);
function drawChart() {
var data1 = google.visualization.arrayToDataTable([
['Label', 'Value'],
['Spend', 80],
]);
var options1 = {
width: 500, height: 300
};
// change number format to £
var formatter = new google.visualization.NumberFormat(
{pattern: '£###,###'});
formatter.format(data1, 1);
var chart = new google.visualization.Gauge(document.getElementById('chart_div1'));
chart.draw(data1, options1);
}
</script>
</head>
<body>
<div id="chart_div1"></div>
</body>
</html>
How do I add a £ sign to the numbers on the outside of the gauge? Thank you.
You can provide an array of strings to majorTicks to specify your own...
google.charts.load('current', {'packages':['gauge']});
google.charts.setOnLoadCallback(drawChart);
function drawChart() {
var data1 = google.visualization.arrayToDataTable([
['Label', 'Value'],
['Spend', 80],
]);
var options1 = {
width: 500, height: 300,
majorTicks: [
'£0', '', '', '', '£100'
]
};
// change number format to £
var formatter = new google.visualization.NumberFormat({
pattern: '£###,###'
});
formatter.format(data1, 1);
var chart = new google.visualization.Gauge(document.getElementById('chart_div1'));
chart.draw(data1, options1);
}
<script src="https://www.gstatic.com/charts/loader.js"></script>
<div id="chart_div1"></div>
I am trying to make a piechart with the google piechart api..I am making this all clientside(html and javascript only)
What I want to do is the following when my webpage loads: load the chart with data, but when I select some other topic through a dropdownlist it should load other data in the chart...
<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);
var Samplevalue =document.getElementById("SampleVAL").value;
function drawChart() {
if(Samplevalue.value="ergo01")
{
var data = google.visualization.arrayToDataTable([
['Soort', 'Aantal'],
['Escherichia', 12.10],
[' Ruminococcus', 6.44],
['Christensenellaceae', 6.15],
['Oscillospira', 13.20],
['Faecalibacterium', 15.50],
['Bacteroides', 3.07],
['Coprococcus', 1.02],
['Bacteroides', 1.00],
['Akkermansia', 0.81],
['Comamonas', 0.69]
]);
}
else if(Samplevalue.value="ergo02")
{
var data = google.visualization.arrayToDataTable([
['Soort', 'Aantal'],
['Escherichia', 25.10],
[' Ruminococcus', 60.44],
['Christensenellaceae', 66.15],
['Oscillospira', 103.20],
['Faecalibacterium', 15.50],
['Bacteroides', 3.07],
['Coprococcus', 1.02],
['Bacteroides', 1.00],
['Akkermansia', 0.81],
['Comamonas', 0.69]
]);
}
else {
var data = google.visualization.arrayToDataTable([
['Soort', 'Aantal'],
['Escherichia', 25.10],
[' Ruminococcus', 60.44],
['Christensenellaceae', 66.15],
['Oscillospira', 103.20],
['Faecalibacterium', 15.50],
['Bacteroides', 3.07],
['Coprococcus', 1.02],
['Bacteroides', 1.00],
['Akkermansia', 0.81],
['Comamonas', 0.69]
alert("hier"); ]);
}
var options = {
title: 'My Daily Activities',
};
var chart = new google.visualization.PieChart(document.getElementById('piechart'));
chart.draw(data, options);
}
</script>
<script>
function myFunction() {
var e = document.getElementById("SampleVAL").value;
//var strUser = e.options[e.selectedIndex].value;
alert(e);
}
</script>
</head>
<body>
<div id="piechart" style="width: 900px; height: 500px;"></div>
<select id="SampleVAL" value="none">
<option value="ergo01">sample1</option>
<option value="ergo02">sample2</option>
<option value="ergo03">sample3</option>
</select>
<button onclick="drawChart()">Try it</button>
</body>
</html>
The issue was that the chart wasn't loading, thanks to #Sourabh Agrawal its working now...I would like this chart to like a little bit more fancy... I am trying to animate it according to google documents .. I should add in the chart options block the following: >>animation:{ >>duration: 1000, easing: 'out', but somehow it isn't working I want my chart to animate as the chart in the following link: navels.yourwildlife.org/explore-your-data Is this possible with google charts?
here is the js Fiddle link to your problem.
https://jsfiddle.net/b7rax1jc/
while comparing values you use "==" and not "="
"=" is for assignment.
2.SampleVAL already contains the value of dropsown so you dont need to use SampleVAL.value when comparing
var Samplevalue =document.getElementById("SampleVAL").value;
if(Samplevalue == "ergo1")
I have been playing around with Line Charts using the Google Charts API and the following example shows a multi-dimensional array being populate into a data table then displayed on the screen.
It works great but I'd like to be able to populate data from a CSV file found in the same folder which may contain n amount of columns.
Can anyone help figure this out?
I think one would access the csv file with JQuery .get and then convert it into an array. I'm just not very JS savvy nowadays..
<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 should try the recommendation from Reading client side text file using Javascript
It's JS way, from that you can turn each line into an array
Other method is by using ajax call to server side and then process the csv and return array
I think that will solve the crossbrowser issue problem.
Hi i want to show "Bangalore"(INDIA) in map using google Geomap.I got one code from developer.google.com site and i have create one for INDIA ,using
option['region']="IN";
but i want "Bangalore" (A major city in India) map instead of india. Is there any way to get that .
Please check the code for INDIA
<html>
<head>
<script type='text/javascript' src='https://www.google.com/jsapi'></script>
<script type='text/javascript'>
google.load('visualization', '1', {'packages': ['geomap']});
google.setOnLoadCallback(drawMap);
function drawMap() {
var data = google.visualization.arrayToDataTable([
['City', 'Popularity'],
['Karnataka', 200],
['Delhi', 300],
['Bihar', 600],
['Kerala', 700]
]);
var options = {};
options['region'] = 'IN';
options['colors'] = [0xFF8747, 0xFFB581, 0xc06000]; //orange colors
var container = document.getElementById('map_canvas');
var geomap = new google.visualization.GeoMap(container);
geomap.draw(data, options);
};
</script>
</head>
<body>
<div id='map_canvas'></div>
</body>
</html>
and output is
Google does not have APIs for cities of India. I was facing the same issue while creating a map of Mumbai.
I used this website to do so.
http://www.image-maps.com/
So you basically give a static map of Bangalore. This website will create a object for you and you can download that code.
Try it out!
Worked for me while dividing Mumbai into Municipality wards.