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()
Related
I am trying to create a hbar graphic with a working hover tool using the JavaScript Bokeh library but I am running into a few problems. I usually use Bokeh in Python but for my current workflow it makes more sense to write it in JavaScrip.
To have the hover tool working correctly for my graphic I need to properly use the ColumnDataSource object correctly in the hbar but for whatever reason I am only able to get it working by populating it directly into it's parameters with arrays.
Any help would be greatly appreciated and thank you in advance to anyone who helps/takes the time to read this.
<!doctype html>
<html lang="en">
<head>
<meta charset="utf-8">
<title>Example Code</title>
<script type="text/javascript" src="https://cdn.bokeh.org/bokeh/release/bokeh-2.4.3.min.js"></script>
<script type="text/javascript" src="https://cdn.bokeh.org/bokeh/release/bokeh-gl-2.4.3.min.js"></script>
<script type="text/javascript" src="https://cdn.bokeh.org/bokeh/release/bokeh-widgets-2.4.3.min.js"></script>
<script type="text/javascript" src="https://cdn.bokeh.org/bokeh/release/bokeh-tables-2.4.3.min.js"></script>
<script type="text/javascript" src="https://cdn.bokeh.org/bokeh/release/bokeh-mathjax-2.4.3.min.js"></script>
<script type="text/javascript" src="https://cdn.bokeh.org/bokeh/release/bokeh-api-2.4.3.min.js"></script>
<script>
//The order of CSS and JS imports above is important.
</script>
<script type="module">
const plt = Bokeh.Plotting;
var x_data = [1,6,-1];
var y_data = ["a","b","c"];
var z_data = [45,62,12];
const
arrays = [x_data, y_data,z_data],
sorted = arrays.map(
(indices => a => indices.map(i => a[i]))
([...arrays[0].keys()].sort((a, b) => arrays[0][a] - arrays[0][b]))
);
// console.log();
x_data = sorted[0];
y_data = sorted[1];
z_data = sorted[2];
const source = new Bokeh.ColumnDataSource({data: { x: x_data,y:y_data,z: z_data }});
// create some ranges for the plot
const xdr = new Bokeh.Range1d({ start: -3, end: 3 });
// const ydr = new Bokeh.Range1d({ start: -7.5, end: 20.5 });
// make the plot
const plot = Bokeh.Plotting.figure({
title: "Hbar test Graph",
x_range: xdr,
y_range: y_data,
toolbar_location: null,
width: 550,
height: 550,
background_fill_color: "#F2F2F7",
source: source,
});
console.log(source);
// add a line with data from the source
const hbar = plot.hbar({
left:0,
name:"Hbar",
right:x_data,
y:y_data,
height:0.7,
source: source,
});
const hover_tool= new Bokeh.HoverTool({renderers:[hbar],
tooltips:[("val", "#z")]});
plot.add_tools(hover_tool);
Bokeh.Plotting.show(plot);
</script>
</head>
<body>
</body>
</html>
<!doctype html>
<html lang="en">
<head>
<meta charset="utf-8">
<title>Complete Example</title>
<script type="text/javascript" src="https://cdn.bokeh.org/bokeh/release/bokeh-2.4.3.min.js"></script>
<script type="text/javascript" src="https://cdn.bokeh.org/bokeh/release/bokeh-gl-2.4.3.min.js"></script>
<script type="text/javascript" src="https://cdn.bokeh.org/bokeh/release/bokeh-widgets-2.4.3.min.js"></script>
<script type="text/javascript" src="https://cdn.bokeh.org/bokeh/release/bokeh-tables-2.4.3.min.js"></script>
<script type="text/javascript" src="https://cdn.bokeh.org/bokeh/release/bokeh-mathjax-2.4.3.min.js"></script>
<script type="text/javascript" src="https://cdn.bokeh.org/bokeh/release/bokeh-api-2.4.3.min.js"></script>
<script>
//The order of CSS and JS imports above is important.
</script>
<script type="module">
// create some data and a ColumnDataSource
const plt = Bokeh.Plotting;
var x_data = [1,6,-1];
var y_data = ["a","b","c"];
var z_data = [45,62,12];
const
arrays = [x_data, y_data,z_data],
sorted = arrays.map(
(indices => a => indices.map(i => a[i]))
([...arrays[0].keys()].sort((a, b) => arrays[0][a] - arrays[0][b]))
);
// console.log();
x_data = sorted[0];
y_data = sorted[1];
z_data = sorted[2];
const source = new Bokeh.ColumnDataSource({data: { x: x_data,y:y_data,z: z_data }});
// create some ranges for the plot
const xdr = new Bokeh.Range1d({ start: -3, end: 3 });
// const ydr = new Bokeh.Range1d({ start: -7.5, end: 20.5 });
// make the plot
const plot = Bokeh.Plotting.figure({
title: "Hbar test Graph",
x_range: xdr,
y_range: y_data,
toolbar_location: null,
width: 550,
height: 550,
background_fill_color: "#F2F2F7",
source: source,
});
console.log(source);
// add a line with data from the source
const hbar = plot.hbar({
left:0,
name:"Hbar",
right:x_data,
y:y_data,
height:0.7,
source: source,
});
const hover_tool= new Bokeh.HoverTool({renderers:[hbar],
tooltips:[("val", "#z")]});
plot.add_tools(hover_tool);
Bokeh.Plotting.show(plot);
</script>
</head>
<body>
</body>
</html>
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 attempting to dynamically create multiple charts in a single html page, everything loads perfectly, except that the graph that is displayed last is the only one that has interactivity available (ex: hover over points to read data, click on legend to highlight line..) while the others will only display static charts.
HTML Code:
<html>
<head>
<title>Dashboard</title>
<script type = "text/javascript" src = "https://www.gstatic.com/charts/loader.js"> </script>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.5.1/jquery.min.js"></script>
<script type = "text/javascript" src = "./scripts/scripts.js"> </script>
</head>
<body>
</body>
<script language = "JavaScript">
var dashboard = getParameterByName("dashboard");
google.charts.load('current', {packages: ['corechart','line']});
buildDashboard(dashboard);
</script>
</html>
Main JS functions:
function buildDashboard(dashboard)
{
var panels = getPanels(dashboard);
google.charts.setOnLoadCallback(function(){
drawCharts(dashboard, panels);
});
}
function drawCharts(dashboard, panels)
{
for(var i = 0; i < panels.length; i++)
{
var panel = panels[i];
var _data = getPanelData(dashboard, panel.Id);
if(panel["Type"] == "LineChart")
{
var legend = JSON.parse(JSON.stringify(_data[0]));
var options = buildLineChartOptions(panel, legend);
var data = google.visualization.arrayToDataTable(beautifyData(panel, _data));
var divname = panel.Id;
if(!document.getElementById(divname))
document.body.innerHTML += "<div id = " + divname + " style = \"width: 100%; height: 600px; margin: 0 auto\"></div>";
var chart = new google.visualization.LineChart(document.getElementById(divname));
chart.draw(data, options);
}
}
}
Solved: The problem was solved by creating the <div> elements for all charts prior to drawing the charts one by one.
I would like to display my retrieved data points from my server side text file
on a google graph. During research i can now retrieve the data from my temps.txt
file using $.get().
I just started learning javascript , so this may be something obvious that i missed.
I can also display a sample google graph with some example datapoints.
How can i put the two together? , below i have both source files
from my attempts so far.
Getting the Datapoints:
<!doctype html>
<html lang="en">
<head>
<meta charset="utf-8">
<title>load demo</title>
<style>
body {
font-size: 16px;
font-family: Arial;
}
</style>
<script src="//code.jquery.com/jquery-1.10.2.js"></script>
</head>
<body>
<script>
var times = [];
$.get('temps.txt', function(data) {
times = data.split("\n");
var html = [];
for (var i in times) {
html.push(times[i] + '<br/>');
}
html.push( times[0] * 3 );
$('body').append(html.join(''));
});
</script>
</html>
Showing the GRAPH:
<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([
['Hours', 'Temperature'],
['18:00', 20.7],
['19:00', 21],
['20:00', 22.3],
['20:30', 22.5],
['21:00', 22.0],
['22:00', 21.6]
]);
var options = {
title: 'Temperatuur Grafiek',
legend: { position: 'bottom' }
};
var chart = new google.visualization.LineChart(document.getElementById('chart_div'));
chart.draw(data, options);
}
</script>
</head>
<body>
<div id="chart_div" style="width: 700px; height: 400px;"></div>
</body>
</html>
Temps.txt file is a simple text file with one measured value every hour
the first line is 00:00 hrs the 2nd line 01:00 hrs and so on see below:
15.3
16.4
16.7
18.8
... etc
Well, would be something like this:
function drawChart() {
$.get('temps.txt', function(txt) {
vals = txt.split("\n");
var hour= 0;
var dataArr=[['Hours', 'Temperature']]
for(var i = 0; i < vals.length;i++){ // build data array
//add the hour in 'hh:00' format and the temperature value
dataArr.push([('0'+hour).substring(-2)+':00', parseFloat(vals[i])]);
hour+=1;
}
var data = google.visualization.arrayToDataTable(dataArr)
var options = {
title: 'Temperatuur Grafiek',
legend: { position: 'bottom' }
};
var chart = new google.visualization.LineChart(document.getElementById('chart_div'));
chart.draw(data, options);
});
}
Am new to highcharts and JS and am trying to plot data from a csv file (data3.csv).
Here is the code at the moment:
<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01//EN" "http://www.w3.org/TR/html4/strict.dtd">
<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=utf-8">
<title>Highcharts Example</title>
<!-- 1. Add these JavaScript inclusions in the head of your page -->
<script type="text/javascript" src="http://ajax.googleapis.com/ajax/libs/jquery/1.3.2/jquery.min.js"></script>
<script type="text/javascript" src="highcharts.js"></script>
<!--[if IE]>
<script type="text/javascript" src="../js/excanvas.compiled.js"></script>
<![endif]-->
<!-- 2. Add the JavaScript to initialize the chart on document ready -->
<script type="text/javascript">
$(document).ready(function() {
var options = {
chart: {
renderTo: 'container',
defaultSeriesType: 'line'
},
title: {
text: 'Stock Chart'
},
xAxis: {
categories: []
},
yAxis: {
title: {
text: 'Price'
}
},
series: []
};
$.get('data3.csv', function(data) {
$.each(lines, function(lineNo, line) {
var items = line.split(',');
var series = {
data: []
};
$.each(items, function(itemNo, item) {
if (itemNo == 0) {
series.name = item;
} else {
series.data.push(parseFloat(item));
}
});
options.series.push(series);
});
var chart = new Highcharts.Chart(options);
});
});
</script>
</head>
<body>
<!-- 3. Add the container -->
<div id="container" style="width: 800px; height: 400px; margin: 0 auto"></div>
</body>
</html>
And the contents of the csv file are:
Date Open
29/01/2010 538.49
28/01/2010 544.49
27/01/2010 541.27
26/01/2010 537.97
25/01/2010 546.59
However, this is not giving a chart (just gives the title).
Could anyone suggest where I am going wrong?
Thanks
In line
var items = line.split(',');
You should spline csv by commas, but you have space. So you can replace this line with:
var items = line.split(' ');
or generate csv which items will separated by comma.
As a result your parser should looks like:
$.get('data.csv', function(data) {
// Split the lines
var lines = data.split('\n');
// Iterate over the lines and add categories or series
$.each(lines, function(lineNo, line) {
var items = line.split(',');
if(lineNo>0)
{
options.xAxis.categories.push(items[0]); //set first column from CSV as categorie
options.series[0].data.push(parseFloat(items[1])); //set second column from CSV as point value
}
});
// Create the chart
var chart = new Highcharts.Chart(options);
});