如何更新散点图?

How to update the scattergraph?

我有这个 table 和带有散点图的图表:

https://jsfiddle.net/horacebury/bygscx8b/6/

我正在尝试在第二个 table 列中的值发生变化时更新散点的位置。

基于此,我想我可以只使用一条线(因为我没有改变点数,只是改变它们的位置):

然而,这段代码:

svg.selectAll("circle")
    .data(data)
    .transition()
    .duration(1000)
    .attr("cx", function(d) {
    return xScale(d[0]);
  })
    .attr("cy", function(d) {
    return yScale(d[1]);
  });

给我这个错误:

Uncaught TypeError: svg.selectAll(...).data is not a function

主要问题是:

svg.selectAll("circle") 不是典型选择,因为您已将 svg 重新定义为过渡而不是一般选择:

 var svg = d3.select("#chart").transition();

使用此 svg 变量的任何选择都将 return 转换 (from the API documentation),例如 transition.selectAll():

For each selected element, selects all descendant elements that match the specified selector string, if any, and returns a transition on the resulting selection.

对于转换,.data 方法不可用。

如果您使用d3.selectAll('circle'),您将获得更大的成功。或者,您可以在定义 svg 时删除 .transition() 并将其仅应用于单个元素:

var svg = d3.select('#chart');

svg.select(".line").transition() 
  .duration(1000).attr("d", valueline(data));

...

这里 updated fiddle 采用后一种方法。


此外,对于您的更新过渡,您可能想要更改比例和您正在使用的值以获得新的 x,y 值(以匹配您的变量名称):

    //Update all circles
    svg.selectAll("circle")
        .data(data)
        .transition()
        .duration(1000)
        .attr("cx", function(d) {
        return x(d.date);
      })
        .attr("cy", function(d) {
        return y(d.close);
      });
  }