简体   繁体   English

使用highcharts进行动态更新

[英]Dynamic updates with highcharts

I'm working with Highcharts and Highstock from a few weeks ago. 几个星期前我正在与Highcharts和Highstock合作。 Step by step, following the documentation and help online, I have builded some charts with interesting options. 一步一步,按照文档和在线帮助,我已经建立了一些有趣的选项图表。 But now I have a question, and my skills with mysql and php are limited. 但现在我有一个问题,我的mysql和php技能有限。

I get temperature values from a data base, every minute. 我每分钟从数据库中获取温度值。 I use a php file to connect to database, and then I build the chart. 我使用php文件连接数据库,然后构建图表。 Now, I want to update the chart like in this example . 现在,我想像这个例子中那样更新图表。 But I can't find a right way. 但我找不到正确的方法。 I was reading in Highcharts documentation, and Stackoverflow some answers, but I can't implement into my code. 我正在读Highcharts文档,而Stackoverflow有一些答案,但我无法实现我的代码。

I was working in 2 ways to implement the dynamic updates. 我正在以两种方式实现动态更新。 The first one is: 第一个是:

<?php

     function conectarBD(){ 
                $server = "localhost";
                $usuario = "user";
                $pass = "password";
                $BD = "databasename";
                $conexion = mysqli_connect($server, $usuario, $pass, $BD); 
                if(!$conexion){ 
                   echo 'Ha sucedido un error inexperado en la conexion de la base de datos<br>'; 
                } 
                return $conexion; 
        }  
        function desconectarBD($conexion){
                $close = mysqli_close($conexion); 
                if(!$close){  
                   echo 'Ha sucedido un error inexperado en la desconexion de la base de datos<br>'; 
                }    
                return $close;         
        }

        function getArraySQL($sql){
            $conexion = conectarBD();
            if(!$result = mysqli_query($conexion, $sql)) die();
            $rawdata = array();
            $i=0;
            while($row = mysqli_fetch_array($result))
            {   
                $rawdata[$i] = $row;
                $i++;
            }
            desconectarBD($conexion);
            return $rawdata;
        }

    $sql = "SELECT Probe1,Time from table2;";
    $rawdata = getArraySQL($sql);

    for($i=0;$i<count($rawdata);$i++){
        $time = $rawdata[$i]["Time"];
        $date = new DateTime($time);
        $rawdata[$i]["Time"]=$date->getTimestamp()*1000;
    }

    ?>

    <HTML>
    <BODY>

    <meta charset="utf-8"> 

    <script src="https://code.jquery.com/jquery.js"></script>
    <script src="http://code.highcharts.com/stock/highstock.js"></script>
    <script src="http://code.highcharts.com/modules/exporting.js"></script>

    <div id="container">
    </div>


    <script type='text/javascript'>
    $(function () {
        $(document).ready(function() {
            Highcharts.setOptions({
                global: {
                    useUTC: false
                }
            });

            var chart;
            $('#container').highcharts({
                chart: {
                    type: 'spline',
                    animation: Highcharts.svg, // don't animate in old IE
                    marginRight: 10,
        events: {
            load: function () {
                var series = this.series[0];
                setInterval(function () {
                    <?php
                        for($i = 0 ;$i<count($rawdata);$i++){
                    ?>
                            series.addPoint([<?php echo $rawdata[$i]["Time"];?>,<?php echo $rawdata[$i]["Probe1"];?>], true, true);
                    <?php } ?>
                }, 90000);
            }
        }

                },
                title: {
                    text: 'Tunnel temperature'
                },
                xAxis: {
                    type: 'datetime',
                    tickPixelInterval: 150
                },
                yAxis: {
                    title: {
                        text: 'ºC'
                    },
                    plotLines: [{
                        value: 0,
                        width: 1,
                        color: '#808080'
                    }]
                },
                tooltip: {
                    formatter: function() {
                            return '<b>'+ this.series.name +'</b><br/>'+
                            Highcharts.dateFormat('%d-%b %H:%M', this.x) +'<br/>'+
                            '<b>'+ Highcharts.numberFormat(this.y, 1) +'</b>';
                    }
                },
                legend: {
                    enabled: true
                },
                exporting: {
                    enabled: true
                },
                series: [{
                    name: 'Probe-1',
                    data: (function() {
                       var data = [];
                        <?php
                            for($i = 0 ;$i<count($rawdata);$i++){
                        ?>
                        data.push([<?php echo $rawdata[$i]["Time"];?>,<?php echo $rawdata[$i]["Probe1"];?>]);
                        <?php } ?>
                    return data;
                    })()
                }]
            });
        });

    });


    </script>
    </html>

And this other way: 另一种方式:

Connection to datatest2.php: 连接到datatest2.php:

<?php
    //convert the date values to Unix Timestamp
    //Convert from 2017-02-28 19:30:01 to Tuesday, February 28 2017 19:30:01
    $con = mysql_connect("localhost","username","password"); 
    if (!$con) { die('Could not connect: ' . mysql_error()); } mysql_select_db("databasename", $con); 
    $result = mysql_query("SELECT * FROM table2"); 

    while ($row = mysql_fetch_array($result)) { 
    $uts=strtotime($row['Time']);   //convertir a Unix Timestamp
    $date=date("l, F j Y H:i:s",$uts);
    //echo $valor3 . “\t” . $row[$valor2]. “\n”;
    echo $date . "\t" . $row['Probe1'] . "\n";
    }
    mysql_close($con); ?>

And the php file for the chart: 和图表的PHP文件:

<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN"
        "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
        <html xmlns="http://www.w3.org/1999/xhtml">
        <head> 
        <meta http-equiv="Content-Type" content="text/html; charset=utf-8"/> 

        <title>Highstock & multiple</title>
        <script src="https://code.jquery.com/jquery.js"></script>
        <script src="http://code.highcharts.com/stock/highstock.js"></script>
        <script src="http://code.highcharts.com/modules/exporting.js"></script>

        <script type="text/javascript">
            var chart;
                    $(document).ready(function() {
                        var options = {
                            chart: {
                                renderTo: 'container',
                                defaultSeriesType: 'line',  
                                marginRight: 130,
                                marginBottom: 25
                            },
                            title: {
                                text: 'Temperature Tunnel',
                                x: -20 //center
                            },
                            subtitle: {
                                text: '',
                                x: -20
                            },
                            rangeSelector: {
                            buttons: [
                            {
                                type: 'all',
                                text: 'all'
                            }, {
                                type: 'week',
                                count: 1,
                                text: '1w'
                            }, {
                                type: 'day',
                                count: 1,
                                text: '1d'
                            }, {
                                type: 'hour',
                                count: 18,
                                text: '18h'
                            }, {
                                type: 'hour',
                                count: 12,
                                text: '12h'
                            }, {
                                type: 'hour',
                                count: 6,
                                text: '6h'
                            }]
                            },
                            xAxis: {
                                type: 'datetime',
                                tickWidth: 0,
                                gridLineWidth: 1,
                                labels: {
                                    align: 'center',
                                    x: -3,
                                    y: 20,
                                    formatter: function() {
                                        return Highcharts.dateFormat('%d-%b %H:%M', this.value);
                                    }
                                }
                            },
                            yAxis: {
                                title: {
                                    text: 'Celsius degrees'
                                },
                                plotLines: [{
                                    value: 0,
                                    width: 1,
                                    color: '#808080'
                                }]

                            },
                            tooltip: {
                                formatter: function() {
                                        return Highcharts.dateFormat('%d-%b %H:%M', this.x) +': <b>'+ this.y + '</b>';
                                }
                            },
                            legend: {
                                layout: 'vertical',
                                align: 'right',
                                verticalAlign: 'top',
                                x: -10,
                                y: 100,
                                borderWidth: 0
                            },
                            series: [{
                                name: 'Probe1'
                            }]
                        }
                        jQuery.get('datatest2.php', null, function(tsv) {
                            var lines = [];
                            traffic = [];
                            try {
                                // split the data return into lines and parse them
                                tsv = tsv.split(/\n/g);
                                jQuery.each(tsv, function(i, line) {
                                    line = line.split(/\t/);
                                    date = Date.parse(line[0] +' UTC');
                                    traffic.push([
                                        date,
                                        parseInt(line[1].replace(',', ''), 10)
                                    ]);
                                });
                            } catch (e) {  }
                            options.series[0].data = traffic;
                            chart = Highcharts.stockChart (options);
                            setInterval(function() { tsv; }, 30000);
                            pollChart.series[0].setData(data);
                        });
                    });
        </script>
        </head>
        <body>

        <div id="container" style="width: 100%; height: 400px; margin: 0 auto"></div>

        </body>
        </html>

Can you help me to find and fix the mistake? 你能帮我找到并修复错误吗? Thanks! 谢谢! Alex. 亚历克斯。

Using a combination of your first example and the JSFiddle that you posted, I would try something like this: 使用您的第一个示例和您发布的JSFiddle的组合,我会尝试这样的事情:

chart: {
    events: {
        load: function () {
            var series = this.series[0];
            setInterval(function () {
                <?php
                    for($i = 0 ;$i<count($rawdata);$i++){
                ?>
                        series.addPoint([<?php echo $rawdata[$i]["Time"];?>,<?php echo $rawdata[$i]["Probe1"];?>], true, true);
                <?php } ?>
            }, 1000);
        }
    }
}

Note that I have no idea whether your PHP code there is actually retrieving the data that you wanted, I have simply copied it from your example and made the assumption that that part of the code was ok. 请注意,我不知道您的PHP代码是否实际上正在检索您想要的数据,我只是从您的示例中复制它并假设该部分代码没问题。

The key here is the chart.events.load property, this takes a function that fires once the chart has finished loading. 这里的关键是chart.events.load属性,它接受一个图表加载完毕后触发的函数。 By calling setInterval here, your function will fire continuously after the chart finishes loading the first time. 通过在此处调用setInterval ,您的函数将在图表第一次完成加载后连续触发。

By calling series.addPoint , your chart will redraw every time a new point is added, which I believe is what you want. 通过调用series.addPoint ,每次添加新点时,您的图表都会重绘,我相信这就是您想要的。

More information is available here about the load property. 有关load属性的更多信息,请参见此处

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM