I have created a form and trying to display submitted values in the google chart. I have tried to create wrapper for drawChart() and want to load drawChart() after submit button is clicked. But, drawChart() function gets called onload. What is the problem with my code?
HTML-
<form method= "post" action = "#" id="formValue">
<label><input type="number" value="1" id="ip1"/>inpu1</label>
<label><input type="number" value="2" id="ip2"/> input2</label>
<input type="submit" value="Add" onclick="initializer()"/>
</form>
JS-
<script>
var ip1, ip2;
var str = "hello";
var str2 = "hello2";
function initializer(){
ip1 = document.getElementById("ip1").value;
ip2 = document.getElementById("ip2").value;
drawChart();
}
google.charts.setOnLoadCallback(initializer);
google.charts.load('current', {'packages':['corechart']});
function drawChart() {
var x2= [
[
str,
ip1
],
[
str2,
ip2
]
];
var data = new google.visualization.DataTable();
data.addColumn('string', 'Topping');
data.addColumn('number', 'Slices');
data.addRows(x2);
var options = {'title':'How Much Pizza I Ate Last Night',
'width':500,
'height':600};
var chart = new google.visualization.PieChart(document.getElementById('chart_div'));
chart.draw(data, options);
remove this...
google.charts.setOnLoadCallback(initializer);
it runs initializer when...
google.charts.load('current', {'packages':['corechart']});
is finished.
Related
I have 3 inputs and from where by click in a button get those input value and create a Google Visualization dynamic Pie Chart depend on those value . I have made like this code below , but did not getting expecting result
HTML
<input type="text" name="BigHalo" id="BigHalo">
<input type="text" name="MediumHalo" id="MediumHalo">
<input type="text" name="SmallHalo" id="SmallHalo">
<button type="button" onclick="onclickChartValur()" >CLICK HERE</button>
<div id="donutchart" style="width:380px; height:380px;"></div>
SCRIPT CODE
<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(BigHalo,MediumHalo,SmallHalo) {
var data = google.visualization.arrayToDataTable([
['Language', 'Speakers (in millions)'],
['Big Halo', BigHalo],
['Medium Halo', MediumHalo],
['Small Halo',SmallHalo]
]);
var options = {
legend: 'none',
pieSliceText: 'label',
title: '',
pieStartAngle: 100,
};
var chart = new google.visualization.PieChart(document.getElementById('donutchart'));
chart.draw(data, options);
}
function onclickChartValur() {
var BigHalo = $("#BigHalo").val();
var MediumHalo = $("#MediumHalo").val();
var SmallHalo = $("#SmallHalo").val();
drawChart(BigHalo,MediumHalo,SmallHalo);
}
</script>
ERROR RESULT ::
EXPECTING RESULT
It is Solved! I made it . Here I am sharing this technique.
HTML
<input type="text" name="BigHalo" id="BigHalo">
<input type="text" name="MediumHalo" id="MediumHalo">
<input type="text" name="SmallHalo" id="SmallHalo">
<button type="button" onclick="onclickChartValur()" >CLICK HERE</button>
<div id="donutchart" style="width:380px; height:380px;"></div>
Script
<script type="text/javascript" src="https://www.gstatic.com/charts/loader.js"></script>
<script type="text/javascript">
google.load("visualization", "1", {packages:["corechart"]});
function drawChart(BigHalo,MediumHalo,SmallHalo) {
var data = google.visualization.arrayToDataTable([
['Language', 'Speakers (in millions)'],
['Big Halo', parseInt(BigHalo)],
['Medium Halo', parseInt(MediumHalo)],
['Small Halo', parseInt(SmallHalo)]
]);
var options = {
legend: 'none',
title: '',
pieStartAngle: 100,
};
var chart = new google.visualization.PieChart(document.getElementById('donutchart'));
chart.draw(data, options);
}
function ontypeChartValur() {
var BigHalo = $("#BigHalo").val();
var MediumHalo = $("#MediumHalo").val();
var SmallHalo = $("#SmallHalo").val();
drawChart(BigHalo,MediumHalo,SmallHalo);
}
</script>
And OnClick event this cart will be generate easily ! Also we can make it with onKeyup / onKeydown event also.
NOTE : parseInt is used here because of convert string to number.
I'm trying to code a web-page that will display a pie-chart with results but the code for my pie-chart is in a HTML file (read_data.html) and the figures I would like to use for the pie-chart are in a JavaScript file (read_data.js)
The figures I want are stored in 4 variables - Booth1,Booth2,Booth3,Booth4
How could I go about transferring these variables to my HTML file?
Here is the code for the pie-chart in the HTML file
<!DOCTYPE html>
<html lang="en-US">
<body>
<h1>My Web Page</h1>
<div id="piechart"></div>
<script type="text/javascript" src="https://www.gstatic.com/charts/loader.js"></script>
<script type="text/javascript">
// Load google charts
google.charts.load('current', {'packages':['corechart']});
google.charts.setOnLoadCallback(drawChart);
// Draw the chart and set the chart values
function drawChart() {
var data = google.visualization.arrayToDataTable([
['Students', 'Votes'],
['Canidate1', Booth1],
['Canidate2', Booth2],
['Canidate3', Booth3],
['Canidate4', Booth4],
]);
// Optional; add a title and set the width and height of the chart
var options = {'title':'Election Results', 'width':550, 'height':400};
// Display the chart inside the <div> element with id="piechart"
var chart = new google.visualization.PieChart(document.getElementById('piechart'));
chart.draw(data, options);
}
</script>
</body>
</html>
Here is the code in the JavaScript file
// Lists to hold the well being states and their corresponding times
var myVotes = [];
var myTimes = [];
// Variables to hold the count for each state
var Booth1 = 0;
var Booth2 = 0;
var Booth3 = 0;
var Booth4 = 0;
// Define database connection to correct child branch, ElectionResults
var myDBConn = firebase.database().ref("ElectionResults");
// Function that acts when a 'new child is added to the DB' - i.e. new data is added this function runs.
myDBConn.on("child_added", function(data, prevChildKey) {
Booth1 = 0;
Booth2 = 0;
Booth3 = 0;
Booth4 = 0;
// The data returned from the branch is put into a variable, dataPoint
var dataPoint = data.val();
// Populate the lists with the various data from the database
myVotes.push(dataPoint.ElectionResults);
myTimes.push(dataPoint.Time);
// Loop each returned state and add 1 to the appropriate counter
for (i = 0; i < myVotes.length; i++) {
if (myVotes[i] == "Canidate1") {
Booth1 = Booth1 + 1;
}
if (myVotes[i] == "Canidate2") {
Booth2 = Booth2 + 1;
}
if (myVotes[i] == "Canidate3") {
Booth3 = Booth3 + 1;
}
if (myVotes[i] == "Canidate4") {
Booth4 = Booth4 + 1;
}
}
// Update the page elements with the average and the last item (most rescent) off the list
document.getElementById("TimeID").innerHTML = myTimes[myTimes.length - 1];
// Update the page elements with the results of each count
document.getElementById("Booth1").innerHTML = Booth1;
document.getElementById("Booth2").innerHTML = Booth2;
document.getElementById("Booth3").innerHTML = Booth3;
document.getElementById("Booth4").innerHTML = Booth4;
});
I think that you can just include the JS file into the HTML file by useing the <script /> tag;
<script type="something" src="read_data.js"></script>
With this tag you inculded the file and can use the variables by opening another script tag;
<script>
//import variables here
</script>
The weights that have been calculated in program needs to be displayed in a graph. I have added into the code an example taken from here: https://developers.google.com/chart/interactive/docs/gallery/linechart#creating-material-line-charts
Obviously the variable data needs to be replaced by weight, so the existing data (line 17 to 31) can be discarded. The latest version of the code is attached
<html>
<head>
<!--Load the AJAX API-->
<script type="text/javascript" src="https://www.gstatic.com/charts/loader.js"></script>
<script type="text/javascript">
google.charts.load('current', { 'packages': ['line'] }); // load the visualisation API and corechart package
google.charts.setOnLoadCallback(drawChart); // set a callback to run when the Google Visualization API is loaded
// Callback that creates and populates a data table, instantiates the chart, passes in the data and draws it.
function drawChart() {
// Create the data table for the symbol in question.
var data = new google.visualization.DataTable();
data.addColumn('number', 'k');
data.addColumn('number', 'lambda');
data.addRows([
[-0.050, 0.00952],
[-0.040, 0.00952],
[-0.030, 0.01904],
[-0.025, 0.03809],
[-0.020, 0.02857],
[-0.015, 0.04761],
[-0.010, 0.02857],
[-0.005, 0.18095],
[0.000, 0.21904],
[0.005, 0.16190],
[0.010, 0.12380],
[0.015, 0.05714],
[0.020, 0.03809],
[0.030, 0.02857],
[0.080, 0.00952]
]);
var chart = new google.charts.Line(document.getElementById('#chart_weights'));
chart.draw(data, { height: 288, width: 550, lineWidth: 1 });
}
</script>
</head>
<body>
<table>
<tr><td>k: </td><td><input id="k" type="number" value="2.2" min="0" max="10" step="0.1" /></td></tr>
<tr><td>lambda: </td><td><input id="lambda" type="number" value="7.6" min="0" max="10" step="0.1" /></td></tr>
</table>
<p id="message"> </p>
<script type="text/javascript">
UpdateValues();
document.getElementById("k").addEventListener("click", function() {
UpdateValues();
});
document.getElementById("lambda").addEventListener("click", function() {
UpdateValues();
});
function UpdateValues() {
var weight = [];
var k = document.getElementById("k").value;
var lambda = document.getElementById("lambda").value;
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]);
document.getElementById("message").innerHTML = weight;
}
}
</script>
<div id="chart_weights"></div>
</body>
</html>
I don't know why these graphs are not beiNg displayed..
THanks in advance to helping hands
Please, check this example
So, The main problem was that Container is not defined.
In your code you write document.getElementById('#chart_weights') but you should write document.getElementById('chart_weights') without #.
My task is to report a graph by accessing sqlite3 database table values. So i created database in python and i used javascript to report a graph.In python, i fetched all values from database and stored in list. Now, my problem is i dono how to access python list values from javascript. please help me..
import sqlite3
list = []
conn = sqlite3.connect('persistentautomation.db')
cursor = conn.execute("SELECT date, gb from memoryused")
for row in cursor:
print "date :", row[0]
print "gb :", row[1]
list.append([row[0],row[1]])
def memory():
return list
req = memory();
print req #This is the list which i created
memory();
ff = open('chart.html','w')
msg='''
<html>
<head>
<script type="text/javascript"
src=\'https://www.google.com/jsapi?autoload={
"modules":[{
"name":"visualization",
"version":"1",
"packages":["corechart"]
}]
}\'></script>
<script type="text/javascript">
google.setOnLoadCallback(drawChart);
function drawChart() {
var data = google.visualization.arrayToDataTable([ .
#i want to pass that list variable here...help please..
]);
var options = {
title: "PERSISTENT AUTOMATION MEMORY USAGE REPORT",
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>'''
ff.write(msg)
ff.close()
import sqlite3
from string import Template
conn = sqlite3.connect('persistentautomation.db')
cursor = conn.execute("SELECT date, gb from memoryused")
results = []
for row in cursor:
results.append({'date': row[0], 'gb': row[1]})
print "date :", row[0]
print "gb :", row[1]
template = '''
<html>
<head>
<script type="text/javascript"
src=\'https://www.google.com/jsapi?autoload={
"modules":[{
"name":"visualization",
"version":"1",
"packages":["corechart"]
}]
}\'></script>
<script type="text/javascript">
google.setOnLoadCallback(drawChart);
function drawChart() {
var data = google.visualization.arrayToDataTable([
["Memory", "Usage (GB)"],
$res
]);
var options = {
title: "PERSISTENT AUTOMATION MEMORY USAGE REPORT",
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>'''
with open('chart.html', 'w') as html:
data = ','.join(['["{date}", {gb}]'.format(**r) for r in results])
html.write(Template(template).substitute(res=data))
You should iterate over list and concatenate items to the result string.
items = ['apple', 'grape']
html_string = '''
<html> <body> <h1> My list </h1> <ul>{list}</ul> </body> </html>
'''
my_list = ''.join(['<li>{}</li>'.format(i) for i items])
html_string = html_string.format(list=my_list)
with open('test.html', 'w') as html:
html.write(html_string)
This is a very easy way to achieve the above task.
import ast
memory_used = "/Users/Shared/MemoryUsed.log"
memory_used = []
with open(memory_used) as f:
for line in f:
linesplit = line.split()
date = linesplit[1]
gbsplit = linesplit[2]
gb = ast.literal_eval(gbsplit[0])
memory_used.append([date,gb])
print memory_used #This is the list
ff = open('chart_new_try.html','w')
html1="""<html>
<head>
<script type="text/javascript"
src="https://www.google.com/jsapi?autoload={
'modules':[{
'name':'visualization',
'version':'1',
'packages':['corechart']
}]
}"></script>
<script type="text/javascript">
google.setOnLoadCallback(drawChart);
function drawChart() {
var data = google.visualization.arrayToDataTable([
['Date', 'MemoryUsed'],"""
html2 = """ ]);
var options = {
title: 'GRAPH REPORT',
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>"""
msg = html1 + memory_used + html2
ff.write(msg)
ff.close()
I am trying to send array data to draw chart. I am trying to give input values [x and y] from user by using html. I could be able to get data from html but when i pass to chart the format is not getting recognized. I am using code from this website. In that you can see , values are passed statically. I want to pass dynamically. please help me.
<html>
<head>
<title>JSChart</title>
<script type="text/javascript" src="jschatrs.js"></script>
</head>
<body>
<tr>
<td>
<input type="text" id="xText" name="xvalue">
</td>
<td>
<input type="text" id="yText" name="yvalue">
</td>
</tr>
<div id="graph">Loading graph...</div>
<button onclick="db()">Try it</button>
<script type="text/javascript">
function db() {
var p = document.getElementById("xText").value;
var q = document.getElementById("yText").value;
var myData = new Array([0, 0]);
myData.push([p, q]);
alert(myData);
var myChart = new JSChart('graph', 'line');
myChart.setDataArray(myData);
myChart.setLineColor('#8D9386');
myChart.setLineWidth(4);
myChart.setTitleColor('#7D7D7D');
myChart.setAxisColor('#9F0505');
myChart.setGridColor('#a4a4a4');
myChart.setAxisValuesColor('#333639');
myChart.setAxisNameColor('#333639');
myChart.setTextPaddingLeft(0);
myChart.draw();
}
</script>
</body>
</html>
It may be because the value property of input elements is stored as a string. Try parsing them as integers:
var p = parseInt(document.getElementById("xText").value, 10);
var q = parseInt(document.getElementById("yText").value, 10);
It might be due to the values you're retrieving from xText and yText are strings rather than numbers.
Try this if they're whole integers:
var p = parseInt(document.getElementById("xText").value, 10);
var q = parseInt(document.getElementById("yText").value, 10);
And this if they're not:
var p = parseFloat(document.getElementById("xText").value);
var q = parseFloat(document.getElementById("yText").value);