错误:未捕获的TypeError:无法读取属性' linear'未定义的

时间:2017-04-13 07:18:20

标签: javascript d3.js

我正在尝试从iris.CSV获取加载数据并将其绘制在网页中。

<!DOCTYPE html>
<html>
<head>
    <meta charset="utf-8">
    <title>D3 Example</title>
    <script src="https://d3js.org/d3.v3.js"></script>
    </script>
</head>

<body>
    <script>
        var svg = d3.select("body").append("svg")
            .attr("width", 250)
            .attr("height", 250);

        var xScale = d3.scale.linear().range([0, 250]);
        var yScale = d3.scale.linear().range([0, 250]);

        function render(data) {

            xScale.domain(d3.extent(data, function(d) {
                return d.sepal_length;
            }));
            yScale.domain(d3.extent(data, function(d) {
                return d.petal_length;
            }));

            var circles = svg.selectAll("circle").data(data);
            circles.enter().append("circle").attr("r", 10);
            circles
                .attr("cx", function(d) {
                    return xScale(d.sepal_length);
                })
                .attr("cy", function(d) {
                    return yScale(d.petal_length);
                });

            circles.exit().remove();
        }

        function type(d) {
            d.sepal_length = +d.sepal_length;
            d.sepal_width = +d.sepal_width;
            d.petal_length = +d.petal_length;
            d.petal_width = +d.petal_width;
            return d;
        }

        d3.csv("iris.csv", type, render);
    </script>

</body>

</html>

但我收到错误。

  

错误:未捕获的TypeError:无法读取属性&#39; linear&#39;未定义的

我甚至将linear更改为scaleLinear d3.v4。,这也显示错误。

1 个答案:

答案 0 :(得分:0)

似乎对我有效(我没有CSV文件所以我只是使用了一些假数据):

var svg = d3.select("body").append("svg")
  .attr("width", 250)
  .attr("height", 250);

var xScale = d3.scale.linear().range([10, 240]);
var yScale = d3.scale.linear().range([10, 240]);

function render(data) {

  xScale.domain(d3.extent(data, function(d) {
    return d.sepal_length;
  }));
  yScale.domain(d3.extent(data, function(d) {
    return d.petal_length;
  }));

  var circles = svg.selectAll("circle").data(data);
  circles.enter().append("circle").attr("r", 10);
  circles
    .attr("cx", function(d) {
      return xScale(d.sepal_length);
    })
    .attr("cy", function(d) {
      return yScale(d.petal_length);
    });

  circles.exit().remove();
}

function type(d) {
  d.sepal_length = +d.sepal_length;
  d.sepal_width = +d.sepal_width;
  d.petal_length = +d.petal_length;
  d.petal_width = +d.petal_width;
  return d;
}

render([{
    sepal_length: 10,
    petal_length: 20,
  },
  {
    sepal_length: 15,
    petal_length: 18,
  }
])
<script src="https://cdnjs.cloudflare.com/ajax/libs/d3/3.4.11/d3.min.js"></script>