.csv绑定到d3.js麻烦

时间:2015-05-05 19:00:49

标签: javascript csv d3.js scatter-plot

新人从d3.js开始,来自PHP / python,但我的JS知识非常弱。我试图将X / Y位置绑定到散点图上并且我一直收到错误

  

错误:属性d的值无效=“MNaN,NaN”

  

错误:属性cx =“NaN”的值无效   错误:属性cy =“NaN”的值无效

我有点不清楚我做错了什么。以下是我的方法:简单的html页面,除了必要的html和脚本(见下文)之外没有别的东西:

    <script>

    var margin = {top: 30, right: 20, bottom: 30, left: 50},
        width = 600 - margin.left - margin.right,
        height = 270 - margin.top - margin.bottom;

    var x = d3.scale.linear().range([0, width]);
    var y = d3.scale.linear().range([height, 0]);

    var xAxis = d3.svg.axis().scale(x)
        .orient("bottom").ticks(5);

    var yAxis = d3.svg.axis().scale(y)
        .orient("left").ticks(5);


    var valueline = d3.svg.line()
        .x(function(d) { return x(d.posX); })
        .y(function(d) { return y(d.posY); });


    var svg = d3.select("body")
        .append("svg")
            .attr("width", width + margin.left + margin.right)
            .attr("height", height + margin.top + margin.bottom)
        .append("g")
            .attr("transform",
          "translate(" + margin.left + "," + margin.top + ")");


    d3.csv("test.php", function(error, data) {
        data.forEach(function(d) {
        d.posX = +d.posX
        d.posY = +d.posY;
    });

x.domain(d3.extent(data, function(d) { return d.posX; }));
y.domain(d3.extent(data, function(d) { return d.posY; }));



svg.append("path")
    .attr("class", "line")
    .attr("d", valueline(data));


svg.selectAll("dot")
    .data(data)
  .enter().append("circle")
    .attr("r", 3.5)
    .attr("cx", function(d) { return x(d.posX); })
    .attr("cy", function(d) { return y(d.posY); });


svg.append("g")
    .attr("class", "x axis")
    .attr("transform", "translate(0," + height + ")")
    .call(xAxis);


svg.append("g")
    .attr("class", "y axis")
    .call(yAxis);

});

</script>

'test.php'调用生成csv格式化数组的mysql查询。这是输出的前五行(当他们导航到localhost / test.php时看到的内容):

    "posX","posY"
    -10,50
    20,143
    14,128
    -40,8

等。我已经注意到的一些事情。我打电话给d3.js;我得到一个轴,没有数据。错误也引用了被调用的d3脚本,所以我确信它正在运行。如果这是一种更好的方法,我很乐意切换到json。这可能很明显,但我无法理解它。

感谢您的帮助。

编辑:我的'.csv'是通过mysql数组的简单循环生成的

     echo $posX . "," . $posY . "<br>";

这可能是问题(特别是br)吗?

1 个答案:

答案 0 :(得分:0)

是的,我很笨。这是愚蠢的br 我在我的PHP脚本中打电话打破了d3.js因为它认为br是另一个值。

简单修复。谢谢Lars Kotthhoff。