首页 > 解决方案 > 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,99,132,1)",
    borderWidth: 2,
    hoverBackgroundColor: "rgba(255,99,132,0.4)",
    hoverBorderColor: "rgba(255,99,132,1)",
    data: [],
  }]
};

var options = {
  maintainAspectRatio: false,
  scales: {
    yAxes: [{
      stacked: true,
      gridLines: {
        display: true,
        color: "rgba(255,99,132,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中的标签变量和数据变量中?

我已经取得了一些进展。我现在可以在使用您的 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, 157, 244, 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} ,{"时间戳":"10:00:00.000000","true_count":12},{"时间戳":"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},{"时间戳":"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},{"时间戳":"21:00:00.000000","true_count":10},{"时间戳":"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",
   type: "get",
   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']];
   },

 });

任何建议我现在做错了什么?

标签: javascriptpython-3.xchart.js

解决方案


我正在分享我使用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>

这是我通过 ajax 调用以 json 格式将数据传递给gettemp()函数的 django 文件。在您的情况下,它是数据库,不会有问题。 视图.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',
        textStyle: {
          fontSize : 14,
          bold:'true',
        },
      },
      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

推荐阅读