Python至chart.js

如何解决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 举报,一经查实,本站将立刻删除。

相关推荐


依赖报错 idea导入项目后依赖报错,解决方案:https://blog.csdn.net/weixin_42420249/article/details/81191861 依赖版本报错:更换其他版本 无法下载依赖可参考:https://blog.csdn.net/weixin_42628809/a
错误1:代码生成器依赖和mybatis依赖冲突 启动项目时报错如下 2021-12-03 13:33:33.927 ERROR 7228 [ main] o.s.b.d.LoggingFailureAnalysisReporter : *************************** APPL
错误1:gradle项目控制台输出为乱码 # 解决方案:https://blog.csdn.net/weixin_43501566/article/details/112482302 # 在gradle-wrapper.properties 添加以下内容 org.gradle.jvmargs=-Df
错误还原:在查询的过程中,传入的workType为0时,该条件不起作用 &lt;select id=&quot;xxx&quot;&gt; SELECT di.id, di.name, di.work_type, di.updated... &lt;where&gt; &lt;if test=&qu
报错如下,gcc版本太低 ^ server.c:5346:31: 错误:‘struct redisServer’没有名为‘server_cpulist’的成员 redisSetCpuAffinity(server.server_cpulist); ^ server.c: 在函数‘hasActiveC
解决方案1 1、改项目中.idea/workspace.xml配置文件,增加dynamic.classpath参数 2、搜索PropertiesComponent,添加如下 &lt;property name=&quot;dynamic.classpath&quot; value=&quot;tru
删除根组件app.vue中的默认代码后报错:Module Error (from ./node_modules/eslint-loader/index.js): 解决方案:关闭ESlint代码检测,在项目根目录创建vue.config.js,在文件中添加 module.exports = { lin
查看spark默认的python版本 [root@master day27]# pyspark /home/software/spark-2.3.4-bin-hadoop2.7/conf/spark-env.sh: line 2: /usr/local/hadoop/bin/hadoop: No s
使用本地python环境可以成功执行 import pandas as pd import matplotlib.pyplot as plt # 设置字体 plt.rcParams[&#39;font.sans-serif&#39;] = [&#39;SimHei&#39;] # 能正确显示负号 p
错误1:Request method ‘DELETE‘ not supported 错误还原:controller层有一个接口,访问该接口时报错:Request method ‘DELETE‘ not supported 错误原因:没有接收到前端传入的参数,修改为如下 参考 错误2:cannot r
错误1:启动docker镜像时报错:Error response from daemon: driver failed programming external connectivity on endpoint quirky_allen 解决方法:重启docker -&gt; systemctl r
错误1:private field ‘xxx‘ is never assigned 按Altʾnter快捷键,选择第2项 参考:https://blog.csdn.net/shi_hong_fei_hei/article/details/88814070 错误2:启动时报错,不能找到主启动类 #
报错如下,通过源不能下载,最后警告pip需升级版本 Requirement already satisfied: pip in c:\users\ychen\appdata\local\programs\python\python310\lib\site-packages (22.0.4) Coll
错误1:maven打包报错 错误还原:使用maven打包项目时报错如下 [ERROR] Failed to execute goal org.apache.maven.plugins:maven-resources-plugin:3.2.0:resources (default-resources)
错误1:服务调用时报错 服务消费者模块assess通过openFeign调用服务提供者模块hires 如下为服务提供者模块hires的控制层接口 @RestController @RequestMapping(&quot;/hires&quot;) public class FeignControl
错误1:运行项目后报如下错误 解决方案 报错2:Failed to execute goal org.apache.maven.plugins:maven-compiler-plugin:3.8.1:compile (default-compile) on project sb 解决方案:在pom.
参考 错误原因 过滤器或拦截器在生效时,redisTemplate还没有注入 解决方案:在注入容器时就生效 @Component //项目运行时就注入Spring容器 public class RedisBean { @Resource private RedisTemplate&lt;String
使用vite构建项目报错 C:\Users\ychen\work&gt;npm init @vitejs/app @vitejs/create-app is deprecated, use npm init vite instead C:\Users\ychen\AppData\Local\npm-