如何选择现有图表并在NVD3.js中更新

voj3qocg  于 2022-11-12  发布在  其他
关注(0)|答案(1)|浏览(138)

请看下面来自NDV3.js图表库的示例:

<!DOCTYPE html>
<html>
<head>
    <meta charset="utf-8">
    <script src="https://d3js.org/d3.v3.min.js"></script>
    <script type="text/javascript" src="https://cdn.rawgit.com/novus/nvd3/v1.8.1/build/nv.d3.min.js"></script>
    <link href="https://cdn.rawgit.com/novus/nvd3/v1.8.1/build/nv.d3.css" rel="stylesheet" type="text/css">

    <style>
        text {
            font: 12px sans-serif;
        }
        svg {
            display: block;
        }
        html, body, #chart1, svg {
            margin: 0px;
            padding: 0px;
            height: 100%;
            width: 100%;
        }

        .dashed {
            stroke-dasharray: 5,5;
        }
    </style>
</head>
<body class='with-3d-shadow with-transitions'>
<div style="position:absolute; top: 0; left: 0;">
    <button onclick="updateChart();">Update Chart</button>
    

    <script>
        var updateChart = function() {
            // GET CHART HERE
            chart.update();
        }
    </script>
</div>
<div id="chart1"></div>

<script>
    // Wrapping in nv.addGraph allows for '0 timeout render', stores rendered charts in nv.graphs, and may do more in the future... it's NOT required
    var chart;
    var data;
    var legendPosition = "top";

    nv.addGraph(function() {
        chart = nv.models.lineChart()
            .options({
                duration: 300,
                useInteractiveGuideline: true
            })
        ;

        // chart sub-models (ie. xAxis, yAxis, etc) when accessed directly, return themselves, not the parent chart, so need to chain separately
        chart.xAxis
            .axisLabel("Time (s)")
            .tickFormat(d3.format(',.1f'))
            .staggerLabels(true)
        ;

        chart.yAxis
            .axisLabel('Voltage (v)')
            .tickFormat(function(d) {
                if (d == null) {
                    return 'N/A';
                }
                return d3.format(',.2f')(d);
            })
        ;

        data = sinAndCos();

        d3.select('#chart1').append('svg')
            .datum(data)
            .call(chart);

        nv.utils.windowResize(chart.update);

        return chart;
    });

    function sinAndCos() {
        var sin = [];

        for (var i = 0; i < 100; i++) {
            sin.push({x: i, y: i % 10 == 5 ? null : Math.sin(i/10) }); //the nulls are to show how defined works
       
        }

        return [
            {
                area: true,
                values: sin,
                key: "Sine Wave",
                color: "#ff7f0e",
                strokeWidth: 4,
                classed: 'dashed'
            }
        ];
    }

</script>
</body>
</html>

这个范例运作良好。请查看“updateChart”函数。问题是我必须保留对图表的指涉,并在那里更新它。是否有替代方法,例如选取“d3.select(...)”并更新它?

5f0d552i

5f0d552i1#

这可能是一个迟来的答复。然而...
尝试了以下解决方案,其中图表仍然作为示例进行维护,并且更新按钮的 onclick 触发数据更新。
(添加了返回不同数据的切换,以演示更新功能)

<html>
   <head>
      <meta charset="utf-8">
      <script src="https://d3js.org/d3.v3.min.js"></script>
      <script type="text/javascript" src="https://cdn.rawgit.com/novus/nvd3/v1.8.1/build/nv.d3.min.js"></script>
      <link href="https://cdn.rawgit.com/novus/nvd3/v1.8.1/build/nv.d3.css" rel="stylesheet" type="text/css">
   </head>
   <body class='with-3d-shadow with-transitions'>
      <div style="position:absolute; top: 0; left: 0;">
         <button onclick="update();">Update Chart</button>
      </div>
      <div id="chart1">
         <svg></svg>
      </div>
      <script>
         var chart;
         var toggle = true;
         var chartData;
         
         nv.addGraph(function () {
            chart = nv.models.lineChart()
                .options({
                    duration: 300,
                    useInteractiveGuideline: true
                });
         
            chart.xAxis
                .axisLabel("Time (s)")
                .tickFormat(d3.format(',.1f'))
                .staggerLabels(true);
         
            chart.yAxis
                .axisLabel('Voltage (v)')
                .tickFormat(function (d) {
                    if (d == null) {
                        return 'N/A';
                    }
                    return d3.format(',.2f')(d);
                });
         
            var data = sinAndCos();
            chartData = d3.select('#chart1 svg').datum(data);
            chartData.transition().duration(500).call(chart);
         
            d3.select('#chart1').append('svg')
                .datum(data)
                .call(chart);
         
            nv.utils.windowResize(chart.update);
         
            return chart;
         });
         
         function update() {
            var data = sinAndCos();
            chartData.datum(data).transition().duration(500).call(chart);
            nv.utils.windowResize(chart.update);
         };
         
         function sinAndCos() {
            var sin = [],
                sin2 = [];
         
         
            for (var i = 0; i < 100; i++) {
         
                sin2.push({
                    x: i,
                    y: i % 10 == 5 ? null : Math.sin(i / 10) * 0.25 + 0.5
                });
         
                sin.push({
                    x: i,
                    y: i % 10 == 5 ? null : Math.sin(i / 10)
                });
         
            }
         
            if (toggle) {
                toggle = !toggle;
                return [{
                    area: false,
                    values: sin2,
                    key: "Sine 2 Wave",
                    color: "#2ca02c",
                    strokeWidth: 4,
                    classed: 'dashed'
                }];
            } else {
                toggle = !toggle;
                return [{
                    area: true,
                    values: sin,
                    key: "Sine Wave",
                    color: "#ff7f0e",
                    strokeWidth: 4,
                    classed: 'dashed'
                }];
         
            }
         
         
         }
         
         
      </script>
      <style>
         text {
         font: 12px sans-serif;
         }
         svg {
         display: block;
         }
         html,
         body,
         #chart1,
         svg {
         margin: 0px;
         padding: 0px;
         height: 100%;
         width: 100%;
         }
         .dashed {
         stroke-dasharray: 5, 5;
         }
      </style>
   </body>
</html>

相关问题