使用NVD3.js构建有焦点的折线图.为什么我的焦点条坏了?



我尝试在NVD3示例页面上跟随焦点示例的折线图,但焦点栏不工作,我看不到我错过了什么…

下面的小提琴演示了这个问题。可以看到拖拽焦点栏并不会使图表聚焦

这是我的HTML(我有一些静态测试数据,并在底部测试数据生成器从NVD3示例页面)

<!DOCTYPE html>
<html>
<head>
<title>$title</title>
<script src="http://ajax.googleapis.com/ajax/libs/jquery/1.9.1/jquery.min.js"></script>
<script src="http://cdnjs.cloudflare.com/ajax/libs/d3/3.4.9/d3.js" charset="utf-8"></script>
<script src="http://cdnjs.cloudflare.com/ajax/libs/nvd3/1.1.15-beta/nv.d3.js"></script>
<link rel="stylesheet" href="http://cdnjs.cloudflare.com/ajax/libs/nvd3/1.1.15-beta/nv.d3.css"/>
</head>
<body>
  <h1>$title</h1>
  <div id="chart">
    <svg style="height:500px"></svg>
  </div>
  <script>
    //my fake data
    var testData = [
      {
        key: 'expected',
        //values: $expectedData
        values: [
          {x: 0, y: 1},
          {x: 1, y: 2},
          {x: 2, y: 3},
          {x: 3, y: 4},
          {x: 4, y: 5},
        ]
      },
      {
        key: 'actual',
        //values: $actualData
        values: [
          {x: 0, y: 3},
          {x: 1, y: 4},
          {x: 2, y: 5},
          {x: 3, y: 4},
          {x: 4, y: 6},
        ]
      }
    ]
    console.log(genTestData());
    console.log(testData);
    nv.addGraph(function() {
      var chart = nv.models.lineWithFocusChart();
      chart.xAxis
          .tickFormat(d3.format(',f'));
      chart.yAxis
          .tickFormat(d3.format(',.2f'));
      chart.y2Axis
          .tickFormat(d3.format(',.2f'));
      d3.select('#chart svg')
          .datum(testData)
          .transition().duration(500)
          .call(chart);
      nv.utils.windowResize(chart.update);
      return chart;
    });
    /**************************************
     * The data generator for the working test example
     */
    function genTestData() {
      return stream_layers(3,128,.1).map(function(data, i) {
        return { 
          key: 'Stream' + i,
          values: data
        };
      });
    }
    /* Inspired by Lee Byron's test data generator. */
    function stream_layers(n, m, o) {
      if (arguments.length < 3) o = 0;
      function bump(a) {
        var x = 1 / (.1 + Math.random()),
            y = 2 * Math.random() - .5,
            z = 10 / (.1 + Math.random());
        for (var i = 0; i < m; i++) {
          var w = (i / m - y) * z;
          a[i] += x * Math.exp(-w * w);
        }
      }
      return d3.range(n).map(function() {
          var a = [], i;
          for (i = 0; i < m; i++) a[i] = o + o * Math.random();
          for (i = 0; i < 5; i++) bump(a);
          return a.map(stream_index);
        });
    }
    function stream_index(d, i) {
      return {x: i, y: Math.max(0, d)};
    }
  </script>
</body>
</html>

小提琴在大多数情况下工作。很明显,如果你的焦点少于2点,主图表就是空白的。您会注意到nvd3的示例页面有这个问题,但有足够的数据,必须故意放大到极端。(不像你的小提琴,只有5个数据点)

只要确保焦点上的最小选择尺寸足够大,至少可以跨越两个点,就可以解决您的问题。

最新更新