javascript JQuery FLOT图表动态Y轴

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/13023529/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-10-26 17:39:32  来源:igfitidea点击:

JQuery FLOT chart dynamic Y-axis

javascriptjqueryflot

提问by Silvertiger

I have a flot chart that calculates the max Y-axis value based on the last 100 data points and then plots successfully... BUT Sometimes, the running total of an ongoing plot (5 second delay with new data point plotted) exceeds the current max limit. Is there a way to have the Y-axis scale dynamically while plotting new points on the chart?

我有一个浮图,它根据最后 100 个数据点计算最大 Y 轴值,然后成功绘制......但有时,正在进行的绘图(绘制新数据点延迟 5 秒)的运行总数超过当前最大限制。有没有办法在图表上绘制新点时动态调整 Y 轴比例?

This is a valid question about how to dynamically scale the Y Axis of the chart if the current Y-axis is exceeded, since the chart is plotted over time with new points being added every 5 seconds, I was asking how to scale the Y-Axis to fit the NEW plot data if it reaches above the current Max Y Axis value..

这是一个关于如何在超过当前 Y 轴的情况下动态缩放图表的 Y 轴的有效问题,因为图表是随时间绘制的,每 5 秒添加一次新点,我问的是如何缩放 Y-如果新绘图数据达到当前最大 Y 轴值以上,则该轴适合新绘图数据。

UPDATE:

更新:

here is the code I use (Json returned data) as well as the plot update timer: The "highY" takes the last 100 datapoints from a database and sets the max value to the highest count + 10%

这是我使用的代码(Json 返回的数据)以及绘图更新计时器:“highY”从数据库中获取最后 100 个数据点并将最大值设置为最高计数 + 10%

        <script type="text/javascript">
            $(function () {
                var str1 = [], totalPoints = 300;
                var str2 = [], totalPoints = 300;
                var pts1 = '';
                var pts2 = '';
                if (pts1 == "" || pts == null) { pts = '2012-10-02 17:17:02'; }
                if (pts2 == "" || pts == null) { pts = '2012-10-02 17:17:02'; }
                var maxYaxis = <?PHP echo $highY; ?>;
                function getStr1() {
                    var ts1 = new Date().getTime();
                    var json1 = (function () {
                        var json1 = null;
                        var myURL = '<?PHP echo $updateURL; ?>?s=1&ts=' + ts1;
                        $.ajax({
                            'async': false,
                            'global': false,
                            'url': myURL,
                            'dataType': "json",
                            'success': function (data) {
                                json1 = data;
                            }
                        });
                        return json1;
                    })(); 
                    var y1 = json1['data']['avgpersec'];
                    var total_1 = json1['data']['running_total'];
                    document.getElementById('<?PHP echo $string1; ?>Total').innerHTML = total_1;
                    if (str1.length > 0) { str1 = str1.slice(1); }

                    while (str1.length < totalPoints) {
                        var prev = str1.length > 0 ? str1[str1.length - 1] : 50;
                        str1.push(y1);
                    }

                    // zip the generated y values with the x values
                    var res = [];
                    for (var i = 0; i < str1.length; ++i){ res.push([i, str1[i]]) }
                    return res;
                }

                function getStr2() {
                    var ts2 = new Date().getTime();
                    var json2 = (function () {
                        var json2 = null;
                        var myURL = '<?PHP echo $updateURL; ?>?s=2&ts=' + ts2;
                        $.ajax({
                            'async': false,
                            'global': false,
                            'url': myURL,
                            'dataType': "json",
                            'success': function (data) {
                                json2 = data;
                            }
                        });
                        return json2;
                    })(); 
                    var y2 = json2['data']['avgpersec'];
                    var total_2 = json2['data']['running_total'];
                    document.getElementById('<?PHP echo $string2; ?>Total').innerHTML = total_2;
                    if (str2.length > 0) { str2 = str2.slice(1); }

                    while (str2.length < totalPoints) {
                        var prev = str2.length > 0 ? str2[str2.length - 1] : 50;
                        str2.push(y2);
                    }

                    // zip the generated y values with the x values
                    var res = [];
                    for (var i = 0; i < str2.length; ++i){ res.push([i, str2[i]]) }
                    return res;
                }

                // setup control widget
                var updateInterval = 5000;
                $("#updateInterval").val(updateInterval).change(function () {
                    var v = $(this).val();
                    if (v && !isNaN(+v)) {
                        updateInterval = +v;
                    if (updateInterval < 1)
                        updateInterval = 1;
                    if (updateInterval > 2000)
                        updateInterval = 2000;
                        $(this).val("" + updateInterval);
                    }
                });

                // setup plot
                var options = {
                    series: { shadowSize: 0 }, // drawing is faster without shadows
                    yaxis: { min: 0, max: maxYaxis},
                    xaxis: { show: false },
                    colors: ["<?PHP echo $string1Color; ?>","<?PHP echo $string2Color; ?>"]
                };
                var plot = $.plot($("#placeholder"), [ getStr1(), getStr2() ], options);

                function update() {
                    plot.setData([ getStr1(), getStr2() ]);
                    plot.draw();
                    setTimeout(update, updateInterval);
                }

                update();
            });
        </script>

What i am hoping to accomplish is to adjust the "$highY" (Y-axis) value real time as i plot new data points so that the chart will scale if the value of the new data plot point exceeds the current "yaxis { max: # }" set in the chart options.

我希望完成的是在绘制新数据点时实时调整“$highY”(Y 轴)值,以便在新数据绘制点的值超过当前“yaxis { max : # }" 在图表选项中设置。

采纳答案by Ryley

I'm assuming that right now you're using flot.setDataand flot.draw?

我假设您现在正在使用flot.setDataflot.draw

The simplest solution is just to call $.plotwith the new data each time you receive it. At various times, this has been recommended by the authors of the flot plugin as a reasonably efficient way of dealing with this situation. I've used this on graphs that refresh every second and found that it does not use an excessive amount of CPU on the user's computer, even with 3-4 graphs refreshing every second on one page.

最简单的解决方案是$.plot每次收到新数据时调用它。在不同的时候,flot 插件的作者都推荐这是一种处理这种情况的合理有效的方法。我已经在每秒刷新的图表上使用了它,发现它不会在用户计算机上使用过多的 CPU,即使在一页上每秒刷新 3-4 个图表。

EDITbased on the code you added (and your suggested edit), I would change the update function to look like this:

编辑根据您添加的代码(和你的建议编辑),我会改变更新功能如下所示:

function update() {
   var data = [ getStr1(), getStr2() ];

   //modify options to set the y max to the new y max
   options.yaxis.max = maxYaxis;
   $.plot($("#placeholder"), data, options);
   setTimeout(update, updateInterval);
}

Additionally, you would add code to getStrand getStrthat keep the maxYaxisvariable up to date.

此外,您将添加代码getStr,并getStr认为保持maxYaxis变量是最新的。