如何解决Python至chart.js
我有带单个表的sqlite数据库。我正在尝试使用Python和pandas读取数据,并在函数中将数据作为json文件返回。然后的目标是使用Javascript获取json数据并将其用于chart.js。
这是我的Python代码,应从数据库读取数据:
@cherrypy.expose
def chart_data(self):
cnx = sqlite3.connect('Production.db',check_same_thread=False)
daily_df = pd.read_sql_query("SELECT * FROM data_object",cnx)
return daily_df.to_json()
然后这是我试图用来从该python调用中获取数据的JavaScript代码的一部分:
function get_chart_data() {
fetch('/chart_data').then( x => {
return x.json();
}).then( x => {
console.log(x);
});
}
在这种情况下,我试图在console.log中打印数据,只是看是否从Python获取数据。但是我需要将这些数据输入到chart.js
var data = {
labels: [],datasets: [{
label: "Dataset",backgroundColor: "rgba(255,99,132,0.2)",borderColor: "rgba(255,1)",borderWidth: 2,hoverBackgroundColor: "rgba(255,0.4)",hoverBorderColor: "rgba(255,data: [],}]
};
var options = {
maintainAspectRatio: false,scales: {
yAxes: [{
stacked: true,gridLines: {
display: true,color: "rgba(255,0.2)"
}
}],xAxes: [{
gridLines: {
display: false
}
}]
}
};
Chart.Bar('chart',{
options: options,data: data
});
最后,sqilite表具有以下列:timestamp,capacity,max_capacity,true_count。 只有24行数据,一天中的每个小时都有一个行。
这就是我被困住的地方。我不确定如何将这些数据正确地放入图表中。目的是绘制24小时内的真实计数。
到目前为止,我拥有的代码我知道我已经很接近了,但是我缺少一些东西来使这项工作有效。 我可以使用python中的javascript正确提取数据吗? 然后我该如何将javascript中的json数据推送到chart.js中的label变量和data变量中?
我取得了一些进展。现在,在使用您的Ajax示例时,我可以将数据获取到javascript控制台日志中。
/* chart.js chart examples */
$(document).ready(function(){
var _data;
var _labels;
$.ajax({
url: "chart_data",type: "get",success: function(response) {
full_data = JSON.parse(response);
_data = full_data['true_count'];
_labels = full_data['timestamp'];
},});
// chart colors
var colors = ['#007bff','#28a745','#333333','#c3e6cb','#dc3545','#6c757d'];
/* large line chart */
var chLine = document.getElementById("chLine");
var chartData = {
labels:_labels,datasets: [
{
data:_data,backgroundColor: [
'rgba(42,157,244,0.1)'
],borderColor: [
'rgba(42,1)','rgba(33,145,81,0.2)',],borderWidth: 1
}]
};
if (chLine) {
new Chart(chLine,{
type: 'line',data: chartData,options: {
scales: {
yAxes: [{
ticks: {
beginAtZero: false
}
}]
},legend: {
display: false
}
}
});
}
;
});
因此,如果我执行console.log(full_data),我可以根据需要从json格式的python中获取数据。但是,我收到错误消息:在我说标签的那一行没有定义full_data:full_data ['timestamp']
似乎无法从图表块访问我的完整数据。我敢肯定,为了完成这项工作,我放了几个括号,但我不知道该在哪里。 有什么想法吗?
我的json文件如下:
[{“ timestamp”:“ 00:00:00.000000”,“ true_count”:0},{“ timestamp”:“ 01:00:00.000000”,“ true_count”:0},{“ timestamp”:“ 02:00:00.000000“,” true_count“:0},{” timestamp“:” 03:00:00.000000“,” true_count“:0},{” timestamp“:” 04:00:00.000000“,” true_count“ :0},{“ timestamp”:“ 05:00:00.000000”,“ true_count”:0},{“ timestamp”:“ 06:00:00.000000”,“ true_count”:2},{“ timestamp”:“ 07:00:00.000000“,” true_count“:5},{” timestamp“:” 08:00:00.000000“,” true_count“:7},{” timestamp“:” 09:00:00.000000“,” true_count“ :8},{“ timestamp”:“ 10:00:00.000000”,“ true_count”:12},{“ timestamp”:“ 11:00:00.000000”,“ true_count”:15},{“ timestamp”:“ 12:00:00.000000“,” true_count“:20},{” timestamp“:” 13:00:00.000000“,” true_count“:17},{” timestamp“:” 14:00:00.000000“,” true_count“ :14},{“ timestamp”:“ 15:00:00.000000”,“ true_count”:13},{“ timestamp”:“ 16:00:00.000000”,“ true_count”:11},{“ timestamp”:“ 17:00:00.000000“,” true_count“:19},{” timestamp“:” 18:00:00.000000“,” true_count“:22},{” timestamp“:” 19:00:00.000000“,” true_count“ :16},{“ timestamp”:“ 20:00:00.000000”,“ true_count”:14 },{“ timestamp”:“ 21:00:00.000000”,“ true_count”:10},{“ timestamp”:“ 22:00:00.000000”,“ true_count”:7},{“ timestamp”:“ 23: 00:00.000000“,” true_count“:4}]
我一直在尝试解析此内容,因此时间戳记为_labels,而true_count则为_data,但是没有运气。
这是我所拥有的:
$(document).ready(function(){
var _data =[];
var _labels = [];
$.ajax({
url: "chart_data",success: function(response) {
full_data = JSON.parse(response);
full_data.forEach(function(key,index){
_data = key.true_count;
_labels= key.timestamp;
});
//_data = [full_data['true_count']];
//_labels = [full_data['timestamp']];
},});
有人建议我现在在做什么错吗?
解决方法
我正在分享使用 Google图表使用的示例。我正在使用ajax从 OPC Server 获取实时数据,并更新了实时图形。如果您使用数据库而不是opc服务器,则不会有太大区别。我希望您可以将其与您的示例联系起来。
HTML
<div class="row" id="grap">
<div class="col-lg-12">
<div class="row">
<div class="col-12">
<div class="card">
<div class="chart-wrapper">
<div id="graph"></div>
</div>
</div>
</div>
</div>
</div>
</div>
这是django文件,通过该文件我通过json格式的ajax调用将数据传递给 gettemp()函数。在您的情况下,它是数据库,不会有问题。 Views.py
def plcdata(request):
url="opc.tcp://127.0.0.1:9000"
client=Client(url)
client.connect()
print("Client Connected")
data={}
dt=[]
while True:
pres=client.get_node("ns=2;i=2")
Pressure=pres.get_value()
adp=client.get_node("ns=2;i=3")
ap=adp.get_value()
rh=client.get_node("ns=2;i=4")
r=rh.get_value()
sp=client.get_node("ns=2;i=5")
s=sp.get_value()
nitro=client.get_node("ns=2;i=6")
n=nitro.get_value()
o2n=client.get_node("ns=2;i=7")
o=o2n.get_value()
hgl=client.get_node("ns=2;i=8")
h=hgl.get_value()
stempress=client.get_node("ns=2;i=9")
sps=stempress.get_value()
cond=client.get_node("ns=2;i=10")
co=cond.get_value()
dmwp=client.get_node("ns=2;i=11")
dmp=dmwp.get_value()
dmwf=client.get_node("ns=2;i=12")
dmf=dmwf.get_value()
chwp=client.get_node("ns=2;i=13")
chp=chwp.get_value()
chwt=client.get_node("ns=2;i=14")
cht=chwt.get_value()
icp=client.get_node("ns=2;i=16")
ip=icp.get_value()
icf=client.get_node("ns=2;i=15")
iff=icf.get_value()
ict=client.get_node("ns=2;i=17")
it=ict.get_value()
dcpp=client.get_node("ns=2;i=19")
dpp=dcpp.get_value()
dcff=client.get_node("ns=2;i=18")
dff=dcff.get_value()
dctt=client.get_node("ns=2;i=20")
dtt=dctt.get_value()
#Time=client.get_node("ns=2;i=3")
#Ti=Time.get_value()
#Ti1=datetime.time(Ti.hour,Ti.minute,Ti.second)
ti=datetime.now()
ti1=(str(ti.strftime('%Y-%m-%d %H:%M:%S')))
dt.append(str(Pressure)+','+ti1+','+str(ap)+','+str(r)+','+str(s)+','+str(n)+','+str(o)+','+str(h)+','+str(sps)+','+str(co)+','+str(dmp)+','+str(dmf)+','+str(chp)+','+str(cht)+','+str(ip)+','+str(it)+','+str(iff)+','+str(dpp)+','+str(dtt)+','+str(dff))
data['final']=dt
return JsonResponse(data)
请检查 getTemp()函数,因为成功函数中的数据来自django。这是您必须根据需要进行更改的部分。
JS
<script type="text/javascript">
google.charts.load('current',{
callback: function () {
var chart = new google.visualization.LineChart(document.getElementById('graph'));
var options = {'title' : 'CTL-2 AIR PRESSURE (Bar)',titleTextStyle: {
fontName: "Arial",fontSize: 18,},animation: {
duration: 1000,easing: 'out',startup: true
},hAxis: {
title: 'Time',format: "HH:mm:ss",textStyle: {
fontSize : 14,bold:'true',vAxis: {
title: 'Air Pressure',format: '0.00',height: 450,width:1000,legend:'bottom'
};
var data = new google.visualization.DataTable();
data.addColumn('datetime','Time');
data.addColumn('number','Air Pressure');
var go=[];
function getTemp() {
$.ajax({
type:"get",url:"{% url 'plcdata' %}",success:function(dat){
for(i=0;i<dat.final.length;i++){
var go=dat.final[i].split(',');
var tm = new Date();
if(data.hg.length>15){
data.removeRow(0);
}
data.addRow([tm,Number(go[0])]);
chart.draw(data,options);
}
return dat;
},error: function(){
console.log("Error Occurred");
}
})
}
getTemp();
setInterval(getTemp,3000);
},packages:['corechart']
});
</script>
[1]: https://i.stack.imgur.com/bMWVB.png
版权声明:本文内容由互联网用户自发贡献,该文观点与技术仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请发送邮件至 dio@foxmail.com 举报,一经查实,本站将立刻删除。